movingAveragesUtilitiesLibrary "movingAveragesUtilities"
get_movingAverages_data(source, length_fast, length_medium, length_slow)
Parameters:
source (float)
length_fast (simple int)
length_medium (simple int)
length_slow (simple int)
Индикаторы и стратегии
gridUtilitiesLibrary "gridUtilities"
TODO: add library description here
get_fibonacciGrid_data(length, trend_direction, plot_grid, plot_labels, bars_to_right, include_levels)
: Gets and plots a fibonacci grid.
Parameters:
length (int) : (int): The direction flag that indicates where the trend is going.
trend_direction (string) : (string): Direction of the trend (Long, Short or Neutral)
plot_grid (bool) : (bool): Plots the fibonacci grid.
plot_labels (bool) : (bool): Plots the datatable.
bars_to_right (int) : (bool): Plots the datatable.
include_levels (bool) : (bool): Plots the datatable.
Returns: : Returns a map with the grid levels, as string with the direction of the grid and a map with the values for the dataTable.
BinaryInsertionSortLibrary "BinaryInsertionSort"
Library containing functions which can help create sorted array based on binary insertion sort.
This sorting will be quicker than array.sort function if the sorting needs to be done on every bar and the size of the array is comparatively big.
method binary_search_basic(sortedArray, item, order)
binary_search_basic - finds the closest index of the value
Namespace types: array
Parameters:
sortedArray (array) : array which is assumed to be sorted in the requested order
item (float) : float item which needs to be searched in the sorted array
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns: int index at which the item can be inserted into sorted array
method binary_search_basic(sortedArray, item, order)
binary_search_basic - finds the closest index of the value
Namespace types: array
Parameters:
sortedArray (array) : array which is assumed to be sorted in the requested order
item (int) : int item which needs to be searched in the sorted array
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns: int index at which the item can be inserted into sorted array
method binary_insertion_sort(sortedArray, item, order)
binary insertion sort - inserts item into sorted array while maintaining sort order
Namespace types: array
Parameters:
sortedArray (array) : array which is assumed to be sorted in the requested order
item (float) : float item which needs to be inserted into sorted array
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns: int index at which the item is inserted into sorted array
method binary_insertion_sort(sortedArray, item, order)
binary insertion sort - inserts item into sorted array while maintaining sort order
Namespace types: array
Parameters:
sortedArray (array) : array which is assumed to be sorted in the requested order
item (int) : int item which needs to be inserted into sorted array
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns: int index at which the item is inserted into sorted array
update_sort_indices(sortIndices, newItemIndex)
adds the sort index of new item added to sorted array and also updates existing sort indices.
Parameters:
sortIndices (array) : array containing sort indices of an array.
newItemIndex (int) : sort index of new item added to sorted array
Returns: void
get_array_of_series(item, order)
Converts series into array and sorted array.
Parameters:
item (float) : float series
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns:
get_array_of_series(item, order)
Converts series into array and sorted array.
Parameters:
item (int) : int series
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns:
get_sorted_arrays(item, order)
Converts series into array and sorted array. Also calculates the sort order of the value array
Parameters:
item (float) : float|int series
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns:
get_sorted_arrays(item, order)
Converts series into array and sorted array. Also calculates the sort order of the value array
Parameters:
item (int) : int series
order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
Returns:
volumeUtilitiesLibrary "volumeUtilities"
generate_and_plot_volumeProfile(length, valueArea_perc, plot_vp, show_vp_labels, include_vp_levels)
: Generate and plot volume profile
Parameters:
length (int) : (int): Length of the volume profile indicator
valueArea_perc (float) : (float): Percentage of the volume that will be in the value area
plot_vp (bool) : (bool): Flag to plot or not the indicator
show_vp_labels (bool) : (bool): Flag to plot the labels of the levels
include_vp_levels (bool) : (bool): Flag to include the values inside the labels of the levels
Returns: : Returns POC level, upper value area level, lower value area level and alerts if close is above or below the value area.
regressionUtilitiesLibrary "regressionUtilities"
get_linear_regression(bar_index_array, prices_array, stdDev_mult)
: Generates the linear regression channel for an array of values.
Parameters:
bar_index_array (array) : (array): Array with bar indexes
prices_array (array) : (array): Array with prices
stdDev_mult (float) : (float): Standard deviation multiple for the channels
Returns: : Returns x1, x2, y1_mid, y2_mid, y1_up, y2_up, y1_dn, y2_dn, m, b, R2, stdDev
get_optimal_linearRegression_channel(max_length, min_length, source, stdDev_mult)
: Gets the best fitting linear regression using optimum length
Parameters:
max_length (int) : (int): Maximum bar length
min_length (int) : (int): Minimum bar length
source (float) : (float): Source for the regression
stdDev_mult (float) : (float): Array with prices
Returns: : Returns three line objects
get_cuadratic_Regression(x_array, y_array, bars_to_project)
: Gets the best fitting linear regression using optimum length
Parameters:
x_array (array) : (array): Maximum bar length
y_array (array) : (array): Minimum bar length
bars_to_project (int) : (int): Array with prices
Returns: : Returns three line objects
dataTableUtilitiesLibrary "dataTableUtilities"
generate_dataTable(dataTable_map, title, tableYpos, tableXpos)
: Generates and shows a data table.
Parameters:
dataTable_map (map)
title (string) : (string): Title of the table
tableYpos (string) : (string): Vertical position of the table
tableXpos (string) : (string): Horizontal position of the table
Returns: : None
formattingUtilitiesLibrary "formattingUtilities"
toPercentageString(x, decimals)
: Converts a decimal number into a string formatted as percentage.
Parameters:
x (float) : (simple float): Float number to be converted
decimals (int) : (simple int): Number of decimals to apply
Returns: : Returns a string with x as percentage.
toFactorString(x, decimals)
: Converts a decimal number into a string formatted as Factor.
Parameters:
x (float) : (simple float): Float number to be converted
decimals (int) : (simple int): Number of decimals to apply
Returns: : Returns a string with x as a Factor.
toCurrencyString(x, decimals)
: Converts a decimal number into a string formatted as currency.
Parameters:
x (float) : (simple float): Float number to be converted
decimals (int) : (simple int): Number of decimals to apply
Returns: : Returns a string with x as currency.
toNumberString(x, decimals)
: Converts a decimal number into a string formatted as decimal.
Parameters:
x (float) : (simple float): Float number to be converted
decimals (int) : (simple int): Number of decimals to apply
Returns: : Returns a string with x as a decimal.
colorByAboveBelow(x, reference, above, below, equal)
: Returns a different color if the reference is above, below or equal to x.
Parameters:
x (float) : (simple float): The number that will be tested, above, below or equal.
reference (float) : (simple float): The reference for for determining if x is above, below or equal.
above (color)
below (color)
equal (color)
Returns: : The color returned if above, below or equal.
utilitiesLibrary "utilities"
toPercentageString(x, decimals)
: Converts a decimal number into a string formatted as percentage.
Parameters:
x (float) : (simple float): Float number to be converted
decimals (int) : (simple int): Number of decimals to apply
Returns: : Returns a string with x as percentage.
toFactorString(x, decimals)
: Converts a decimal number into a string formatted as Factor.
Parameters:
x (float) : (simple float): Float number to be converted
decimals (int) : (simple int): Number of decimals to apply
Returns: : Returns a string with x as a Factor.
toCurrencyString(x, decimals)
: Converts a decimal number into a string formatted as currency.
Parameters:
x (float) : (simple float): Float number to be converted
decimals (int) : (simple int): Number of decimals to apply
Returns: : Returns a string with x as currency.
toNumberString(x, decimals)
: Converts a decimal number into a string formatted as decimal.
Parameters:
x (float) : (simple float): Float number to be converted
decimals (int) : (simple int): Number of decimals to apply
Returns: : Returns a string with x as a decimal.
bollingerBandsLibrary "bollingerBands"
Bollinger bands related functions
get_multiple_bollinger_bands(stdv1, stdv2, stdv3, stdv4, stdv5, stdv6, stdv7, length, source)
Parameters:
stdv1 (int)
stdv2 (int)
stdv3 (int)
stdv4 (int)
stdv5 (int)
stdv6 (int)
stdv7 (int)
length (simple int)
source (float)
get_bb_volatility(bb_highest, bb_lowest, ma_length, lookback)
Parameters:
bb_highest (float)
bb_lowest (float)
ma_length (simple int)
lookback (int)
pseudorenko█ CALCULATE PSEUDO-RENKO VALUE
Calculates and returns the Pseudo-Renko Stabilized value (or close price) based on a given input value, along with the direction of the current Renko brick. This function adapts the traditional Renko brick size dynamically based on the volatility of the input value using a combination of SMA and EMA calculations. The calculated price represents the closing price of the most recent Pseudo-Renko brick, while the direction indicates the trend ( 1 for uptrend, -1 for downtrend).
Parameters:
* `val` :
* Type: ` float `
* Description: The input value upon which the Pseudo-Renko calculations are performed. You can use any price series or custom value as input.
* `sensitivity` :
* Type: ` float `
* Default Value: ` 1.0 `
* Description: Controls the sensitivity of the brick size to the volatility of the `val`. Higher values lead to larger bricks, resulting in a smoother Renko chart. Lower values produce smaller bricks, leading to a more reactive chart.
* Possible Values: Any positive float.
* `length` :
* Type: ` int `
* Default Value: ` 7 `
* Description: The length used for calculating the EMA and SMA in the dynamic brick size calculation. It influences how quickly the brick size adapts to changing volatility of the `val`.
* Possible Values: Any positive integer.
Return Values:
* `lastRenkoClose` :
* Type: ` float `
* Description: The closing price of the last completed Pseudo-Renko brick based on the `val`.
* `renkoDirection` :
* Type: ` int `
* Description: The direction of the current Pseudo-Renko brick based on the `val`:
* ` 1 `: Uptrend
* ` -1 `: Downtrend
* ` 0 `: No change (initially, or no brick change since the previous bar)
Example Usage:
//@version=5
indicator("Pseudo-Renko Stabilized (Val)", overlay=true)
// Get user inputs
sensitivityInput = input.float(0.1, "Sensitivity",0.01,step=0.01)
lengthInput = input.int(5, "Length",2)
// Example usage with the 'close' price as the input value
= pseudo_renko(math.avg(close,open), sensitivityInput, lengthInput)
// Plot the Renko close price
plot(renkoClose, "Renko Close", renkoDirection>0?color.aqua:color.orange,2)
// You can also use other values as input, such as:
// = pseudo_renko(high, sensitivityInput, lengthInput)
// = pseudo_renko(low, sensitivityInput, lengthInput)
This example demonstrates how to use the `pseudo_renko` function within an indicator. It takes user inputs for `sensitivity` and `length`, then calculates the Pseudo-Renko values using the average of the `close` and `open` prices as the `val`. The resulting `renkoClose` price is plotted on the chart, with a color change based on the `renkoDirection`. It also illustrates how you can use other values, like `high` and `low`, as input to the function.
Note: The Pseudo-Renko algorithm is based on adapting the Renko brick size dynamically based on the input `val`. This provides more flexibility compared to the normal, but is experimental. The `sensitivity` and `length` parameters, along with the choice of the `val`, offer further customization to tune the algorithm's behavior to your preference and trading style.
JordanSwindenLibraryLibrary "JordanSwindenLibrary"
TODO: add library description here
getDecimals()
Calculates how many decimals are on the quote price of the current market
Returns: The current decimal places on the market quote price
getPipSize(multiplier)
Calculates the pip size of the current market
Parameters:
multiplier (int) : The mintick point multiplier (1 by default, 10 for FX/Crypto/CFD but can be used to override when certain markets require)
Returns: The pip size for the current market
truncate(number, decimalPlaces)
Truncates (cuts) excess decimal places
Parameters:
number (float) : The number to truncate
decimalPlaces (simple float) : (default=2) The number of decimal places to truncate to
Returns: The given number truncated to the given decimalPlaces
toWhole(number)
Converts pips into whole numbers
Parameters:
number (float) : The pip number to convert into a whole number
Returns: The converted number
toPips(number)
Converts whole numbers back into pips
Parameters:
number (float) : The whole number to convert into pips
Returns: The converted number
getPctChange(value1, value2, lookback)
Gets the percentage change between 2 float values over a given lookback period
Parameters:
value1 (float) : The first value to reference
value2 (float) : The second value to reference
lookback (int) : The lookback period to analyze
Returns: The percent change over the two values and lookback period
random(minRange, maxRange)
Wichmann–Hill Pseudo-Random Number Generator
Parameters:
minRange (float) : The smallest possible number (default: 0)
maxRange (float) : The largest possible number (default: 1)
Returns: A random number between minRange and maxRange
bullFib(priceLow, priceHigh, fibRatio)
Calculates a bullish fibonacci value
Parameters:
priceLow (float) : The lowest price point
priceHigh (float) : The highest price point
fibRatio (float) : The fibonacci % ratio to calculate
Returns: The fibonacci value of the given ratio between the two price points
bearFib(priceLow, priceHigh, fibRatio)
Calculates a bearish fibonacci value
Parameters:
priceLow (float) : The lowest price point
priceHigh (float) : The highest price point
fibRatio (float) : The fibonacci % ratio to calculate
Returns: The fibonacci value of the given ratio between the two price points
getMA(length, maType)
Gets a Moving Average based on type (! MUST BE CALLED ON EVERY TICK TO BE ACCURATE, don't place in scopes)
Parameters:
length (simple int) : The MA period
maType (string) : The type of MA
Returns: A moving average with the given parameters
barsAboveMA(lookback, ma)
Counts how many candles are above the MA
Parameters:
lookback (int) : The lookback period to look back over
ma (float) : The moving average to check
Returns: The bar count of how many recent bars are above the MA
barsBelowMA(lookback, ma)
Counts how many candles are below the MA
Parameters:
lookback (int) : The lookback period to look back over
ma (float) : The moving average to reference
Returns: The bar count of how many recent bars are below the EMA
barsCrossedMA(lookback, ma)
Counts how many times the EMA was crossed recently (based on closing prices)
Parameters:
lookback (int) : The lookback period to look back over
ma (float) : The moving average to reference
Returns: The bar count of how many times price recently crossed the EMA (based on closing prices)
getPullbackBarCount(lookback, direction)
Counts how many green & red bars have printed recently (ie. pullback count)
Parameters:
lookback (int) : The lookback period to look back over
direction (int) : The color of the bar to count (1 = Green, -1 = Red)
Returns: The bar count of how many candles have retraced over the given lookback & direction
getBodySize()
Gets the current candle's body size (in POINTS, divide by 10 to get pips)
Returns: The current candle's body size in POINTS
getTopWickSize()
Gets the current candle's top wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's top wick size in POINTS
getBottomWickSize()
Gets the current candle's bottom wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's bottom wick size in POINTS
getBodyPercent()
Gets the current candle's body size as a percentage of its entire size including its wicks
Returns: The current candle's body size percentage
isHammer(fib, colorMatch)
Checks if the current bar is a hammer candle based on the given parameters
Parameters:
fib (float) : (default=0.382) The fib to base candle body on
colorMatch (bool) : (default=false) Does the candle need to be green? (true/false)
Returns: A boolean - true if the current bar matches the requirements of a hammer candle
isStar(fib, colorMatch)
Checks if the current bar is a shooting star candle based on the given parameters
Parameters:
fib (float) : (default=0.382) The fib to base candle body on
colorMatch (bool) : (default=false) Does the candle need to be red? (true/false)
Returns: A boolean - true if the current bar matches the requirements of a shooting star candle
isDoji(wickSize, bodySize)
Checks if the current bar is a doji candle based on the given parameters
Parameters:
wickSize (float) : (default=2) The maximum top wick size compared to the bottom (and vice versa)
bodySize (float) : (default=0.05) The maximum body size as a percentage compared to the entire candle size
Returns: A boolean - true if the current bar matches the requirements of a doji candle
isBullishEC(allowance, rejectionWickSize, engulfWick)
Checks if the current bar is a bullish engulfing candle
Parameters:
allowance (float) : (default=0) How many POINTS to allow the open to be off by (useful for markets with micro gaps)
rejectionWickSize (float) : (default=disabled) The maximum rejection wick size compared to the body as a percentage
engulfWick (bool) : (default=false) Does the engulfing candle require the wick to be engulfed as well?
Returns: A boolean - true if the current bar matches the requirements of a bullish engulfing candle
isBearishEC(allowance, rejectionWickSize, engulfWick)
Checks if the current bar is a bearish engulfing candle
Parameters:
allowance (float) : (default=0) How many POINTS to allow the open to be off by (useful for markets with micro gaps)
rejectionWickSize (float) : (default=disabled) The maximum rejection wick size compared to the body as a percentage
engulfWick (bool) : (default=false) Does the engulfing candle require the wick to be engulfed as well?
Returns: A boolean - true if the current bar matches the requirements of a bearish engulfing candle
isInsideBar()
Detects inside bars
Returns: Returns true if the current bar is an inside bar
isOutsideBar()
Detects outside bars
Returns: Returns true if the current bar is an outside bar
barInSession(sess, useFilter)
Determines if the current price bar falls inside the specified session
Parameters:
sess (simple string) : The session to check
useFilter (bool) : (default=true) Whether or not to actually use this filter
Returns: A boolean - true if the current bar falls within the given time session
barOutSession(sess, useFilter)
Determines if the current price bar falls outside the specified session
Parameters:
sess (simple string) : The session to check
useFilter (bool) : (default=true) Whether or not to actually use this filter
Returns: A boolean - true if the current bar falls outside the given time session
dateFilter(startTime, endTime)
Determines if this bar's time falls within date filter range
Parameters:
startTime (int) : The UNIX date timestamp to begin searching from
endTime (int) : the UNIX date timestamp to stop searching from
Returns: A boolean - true if the current bar falls within the given dates
dayFilter(monday, tuesday, wednesday, thursday, friday, saturday, sunday)
Checks if the current bar's day is in the list of given days to analyze
Parameters:
monday (bool) : Should the script analyze this day? (true/false)
tuesday (bool) : Should the script analyze this day? (true/false)
wednesday (bool) : Should the script analyze this day? (true/false)
thursday (bool) : Should the script analyze this day? (true/false)
friday (bool) : Should the script analyze this day? (true/false)
saturday (bool) : Should the script analyze this day? (true/false)
sunday (bool) : Should the script analyze this day? (true/false)
Returns: A boolean - true if the current bar's day is one of the given days
atrFilter(atrValue, maxSize)
Parameters:
atrValue (float)
maxSize (float)
tradeCount()
Calculate total trade count
Returns: Total closed trade count
isLong()
Check if we're currently in a long trade
Returns: True if our position size is positive
isShort()
Check if we're currently in a short trade
Returns: True if our position size is negative
isFlat()
Check if we're currentlyflat
Returns: True if our position size is zero
wonTrade()
Check if this bar falls after a winning trade
Returns: True if we just won a trade
lostTrade()
Check if this bar falls after a losing trade
Returns: True if we just lost a trade
maxDrawdownRealized()
Gets the max drawdown based on closed trades (ie. realized P&L). The strategy tester displays max drawdown as open P&L (unrealized).
Returns: The max drawdown based on closed trades (ie. realized P&L). The strategy tester displays max drawdown as open P&L (unrealized).
totalPipReturn()
Gets the total amount of pips won/lost (as a whole number)
Returns: Total amount of pips won/lost (as a whole number)
longWinCount()
Count how many winning long trades we've had
Returns: Long win count
shortWinCount()
Count how many winning short trades we've had
Returns: Short win count
longLossCount()
Count how many losing long trades we've had
Returns: Long loss count
shortLossCount()
Count how many losing short trades we've had
Returns: Short loss count
breakEvenCount(allowanceTicks)
Count how many break-even trades we've had
Parameters:
allowanceTicks (float) : Optional - how many ticks to allow between entry & exit price (default 0)
Returns: Break-even count
longCount()
Count how many long trades we've taken
Returns: Long trade count
shortCount()
Count how many short trades we've taken
Returns: Short trade count
longWinPercent()
Calculate win rate of long trades
Returns: Long win rate (0-100)
shortWinPercent()
Calculate win rate of short trades
Returns: Short win rate (0-100)
breakEvenPercent(allowanceTicks)
Calculate break even rate of all trades
Parameters:
allowanceTicks (float) : Optional - how many ticks to allow between entry & exit price (default 0)
Returns: Break-even win rate (0-100)
averageRR()
Calculate average risk:reward
Returns: Average winning trade divided by average losing trade
unitsToLots(units)
(Forex) Convert the given unit count to lots (multiples of 100,000)
Parameters:
units (float) : The units to convert into lots
Returns: Units converted to nearest lot size (as float)
getFxPositionSize(balance, risk, stopLossPips, fxRate, lots)
(Forex) Calculate fixed-fractional position size based on given parameters
Parameters:
balance (float) : The account balance
risk (float) : The % risk (whole number)
stopLossPips (float) : Pip distance to base risk on
fxRate (float) : The conversion currency rate (more info below in library documentation)
lots (bool) : Whether or not to return the position size in lots rather than units (true by default)
Returns: Units/lots to enter into "qty=" parameter of strategy entry function
EXAMPLE USAGE:
string conversionCurrencyPair = (strategy.account_currency == syminfo.currency ? syminfo.tickerid : strategy.account_currency + syminfo.currency)
float fx_rate = request.security(conversionCurrencyPair, timeframe.period, close )
if (longCondition)
strategy.entry("Long", strategy.long, qty=zen.getFxPositionSize(strategy.equity, 1, stopLossPipsWholeNumber, fx_rate, true))
skipTradeMonteCarlo(chance, debug)
Checks to see if trade should be skipped to emulate rudimentary Monte Carlo simulation
Parameters:
chance (float) : The chance to skip a trade (0-1 or 0-100, function will normalize to 0-1)
debug (bool) : Whether or not to display a label informing of the trade skip
Returns: True if the trade is skipped, false if it's not skipped (idea being to include this function in entry condition validation checks)
fillCell(tableID, column, row, title, value, bgcolor, txtcolor, tooltip)
This updates the given table's cell with the given values
Parameters:
tableID (table) : The table ID to update
column (int) : The column to update
row (int) : The row to update
title (string) : The title of this cell
value (string) : The value of this cell
bgcolor (color) : The background color of this cell
txtcolor (color) : The text color of this cell
tooltip (string)
Returns: Nothing.
[ALGOA+] Markov Chains Library by @metacamaleoLibrary "MarkovChains"
Markov Chains library by @metacamaleo. Created in 09/08/2024.
This library provides tools to calculate and visualize Markov Chain-based transition matrices and probabilities. This library supports two primary algorithms: a rolling window Markov Chain and a conditional Markov Chain (which operates based on specified conditions). The key concepts used include Markov Chain states, transition matrices, and future state probabilities based on past market conditions or indicators.
Key functions:
- `mc_rw()`: Builds a transition matrix using a rolling window Markov Chain, calculating probabilities based on a fixed length of historical data.
- `mc_cond()`: Builds a conditional Markov Chain transition matrix, calculating probabilities based on the current market condition or indicator state.
Basically, you will just need to use the above functions on your script to default outputs and displays.
Exported UDTs include:
- s_map: An UDT variable used to store a map with dummy states, i.e., if possible states are bullish, bearish, and neutral, and current is bullish, it will be stored
in a map with following keys and values: "bullish", 1; "bearish", 0; and "neutral", 0. You will only use it to customize your own script, otherwise, it´s only for internal use.
- mc_states: This UDT variable stores user inputs, calculations and MC outputs. As the above, you don´t need to use it, but you may get features to customize your own script.
For example, you may use mc.tm to get the transition matrix, or the prob map to customize the display. As you see, functions are all based on mc_states UDT. The s_map UDT is used within mc_states´s s array.
Optional exported functions include:
- `mc_table()`: Displays the transition matrix in a table format on the chart for easy visualization of the probabilities.
- `display_list()`: Displays a map (or array) of string and float/int values in a table format, used for showing transition counts or probabilities.
- `mc_prob()`: Calculates and displays probabilities for a given number of future bars based on the current state in the Markov Chain.
- `mc_all_states_prob()`: Calculates probabilities for all states for future bars, considering all possible transitions.
The above functions may be used to customize your outputs. Use the returned variable mc_states from mc_rw() and mc_cond() to display each of its matrix, maps or arrays using mc_table() (for matrices) and display_list() (for maps and arrays) if you desire to debug or track the calculation process.
See the examples in the end of this script.
Have good trading days!
Best regards,
@metacamaleo
-----------------------------
KEY FUNCTIONS
mc_rw(state, length, states, pred_length, show_table, show_prob, table_position, prob_position, font_size)
Builds the transition matrix for a rolling window Markov Chain.
Parameters:
state (string) : The current state of the market or system.
length (int) : The rolling window size.
states (array) : Array of strings representing the possible states in the Markov Chain.
pred_length (int) : The number of bars to predict into the future.
show_table (bool) : Boolean to show or hide the transition matrix table.
show_prob (bool) : Boolean to show or hide the probability table.
table_position (string) : Position of the transition matrix table on the chart.
prob_position (string) : Position of the probability list on the chart.
font_size (string) : Size of the table font.
Returns: The transition matrix and probabilities for future states.
mc_cond(state, condition, states, pred_length, show_table, show_prob, table_position, prob_position, font_size)
Builds the transition matrix for conditional Markov Chains.
Parameters:
state (string) : The current state of the market or system.
condition (string) : A string representing the condition.
states (array) : Array of strings representing the possible states in the Markov Chain.
pred_length (int) : The number of bars to predict into the future.
show_table (bool) : Boolean to show or hide the transition matrix table.
show_prob (bool) : Boolean to show or hide the probability table.
table_position (string) : Position of the transition matrix table on the chart.
prob_position (string) : Position of the probability list on the chart.
font_size (string) : Size of the table font.
Returns: The transition matrix and probabilities for future states based on the HMM.
Candlestick_patternsLibrary "CandlestickepatternsClase3"
TODO: add library description here
bullish_engulfing()
bearish_engulfing()
LinTrendLibLibrary "LinTrendLib"
TODO: add library description here
ema_trend(twz, ema_length, cross_ratio, multiplier)
Given Bullish / Bearish / side-way market jugement
Parameters:
twz (int)
ema_length (simple int)
cross_ratio (float)
multiplier (float)
Returns: 1 --> bullish trend, -1 --> bearish trend, 0 --> sideway market
Color Library // AlgoFyreAlgoFyre's Color Library is a Pine Script v5 library offering fire-themed palettes with light and dark modes. It helps traders easily integrate consistent, visually appealing color schemes into TradingView indicators. Used in AlgoFyre's Scripts and Indicators.
Color Overview
The AlgoFyreColorLibrary includes a comprehensive set of colors inspired by fire, ranging from light reds and oranges to dark browns and deep reds. The library is divided into two main themes:
Light Theme:
Includes lighter shades of red, orange, and brown, suitable for use on light backgrounds.
Dark Theme:
Includes darker shades of red, orange, and brown, suitable for use on dark backgrounds.
How to Use
To use the AlgoFyreColorLibrary in your Pine Script indicators and strategies, follow these steps:
Import the Library:
Import the AlgoFyreColorLibrary at the beginning of your script.
Call the getColor Function:
Use the getColor function to retrieve the desired color with the specified transparency.
Example
//@version=5
import "AF-L-0001" as af
// Example usage of getColor function
color primaryColor = af.getColor("af_primary1", 50)
color signalColor = af.getColor("af_green", 80)
// Plotting example
plot(close, color=primaryColor, linewidth=2, title="Primary Color Line")
plot(close, color=signalColor, linewidth=2, title="Signal Color Line")
The library AF-L-0001 is imported with the alias af.
The getColor function is used to get colors with specified transparency.
The colors are then used to plot lines on the chart.
StyleLibraryLibrary "StyleLibrary"
A small library of Pine Script functions that return built-in style variables.
method sizeStyle(size)
Takes a `string` that returns the corresponding built-in size style variable.
Namespace types: series string, simple string, input string, const string
Parameters:
size (string) : A `string` representing a built-in size style: `"Tiny"`, `"Small"`, `"Normal"`, `"Large"`,
`"Huge"`, `"Auto"`.
Returns: The respective built-in size style variable.
method sizeStyle(size)
Takes a `sizeStyle` that returns the corresponding built-in size style variable.
Namespace types: series sizeStyle
Parameters:
size (series sizeStyle) : A `sizeStyle` representing a built-in size style variable.
Returns: The respective built-in size style variable.
method lineStyle(style)
Takes a `string` that returns the corresponding built-in line style variable.
Namespace types: series string, simple string, input string, const string
Parameters:
style (string) : A `string` representing a built-in line style: `"Dashed"`, `"Dotted"`, `"Solid"`.
Returns: The respective built-in line style variable.
method lineStyle(style)
Takes a `lineStyle` that returns the corresponding built-in line style variable.
Namespace types: series lineStyle
Parameters:
style (series lineStyle) : A `lineStyle` representing a built-in line style variable.
Returns: The respective built-in line style variable.
method labelStyle(style)
Takes a `string` that returns the corresponding built-in label style variable.
Namespace types: series string, simple string, input string, const string
Parameters:
style (string) : A `string` representing a built-in label style:
`"Arrow Down"`, `"Arrow Up"`, `"Circle"`, `"Cross"`, `"Diamond"`, `"Flag"`,
`"Label Center"`, `"Label Down"`, `"Label Left"`, `"Label Lower Left"`,
`"Label Lower Right"`, `"Label Right"`, `"Label Up"`, `"Label Upper Left"`,
`"Label Upper Right"`, `"None"`, `"Square"`, `"Text Outline"`, `"Triangle Down"`,
`"Triangle Up"`, `"XCross"`.
Returns: The respective built-in label style variable.
method labelStyle(style)
Takes a `labelStyle` that returns the corresponding built-in label style variable.
Namespace types: series labelStyle
Parameters:
style (series labelStyle) : A `labelStyle` representing a built-in label style variable.
Returns: The respective built-in label style variable.
method fontStyle(font)
Takes a `string` that returns the corresponding built-in font style variable.
Namespace types: series string, simple string, input string, const string
Parameters:
font (string) : A `string` representing a built-in font style: `"Default"`, `"Monospace"`.
Returns: The respective built-in font style variable.
method positionStyle(position)
Takes a `string` that returns the corresponding built-in position style variable.
Namespace types: series string, simple string, input string, const string
Parameters:
position (string) : A `string` representing a built-in position style:
`"Bottom Center", `"Bottom Left", `"Bottom Right", `"Middle Center", `"Middle Left",
`"Middle Right", `"Top Center", `"Top Left", `"Top Right".
Returns: The respective built-in position style variable.
method displayStyle(display)
Takes a `simple string` that returns the corresponding built-in display style variable.
Namespace types: simple string, input string, const string
Parameters:
display (simple string) : A `simple string` representing a built-in display style: `"All"`, `"Data Window"`,
`"None"`, `"Pane"`, `"Price Scale"`, `"Status Line"`.
Returns: The respective built-in display style variable.
WavesLibrary "Waves"
Methods for elliot wave detection
method delete(this)
deletes the subwave drawing
Namespace types: Subwave
Parameters:
this (Subwave) : Subwave object to be deleted
Returns: deleted subwave object
method delete(this)
deletes the wave drawing and the corresponding subwaves
Namespace types: Wave
Parameters:
this (Wave) : Wave object to be deleted
Returns: deleted wave object
method createWave(pivot, lineColor, waves, limit)
Create wave object
Namespace types: zg.Pivot
Parameters:
pivot (Pivot type from Trendoscope/Zigzag/7) : pivot object where the wave needs to be created
lineColor (color) : color of the wave to be drawn
waves (array) : array of existing waves
limit (int) : max number of waves to be shown in the chart
Returns: wave object created
method createSubWaves(wave, subwavePivots)
Create sub waves for the wave
Namespace types: Wave
Parameters:
wave (Wave)
subwavePivots (array) : array of sub wave pivots
Returns: wave object created
method draw(subWave)
Draw subwave
Namespace types: Subwave
Parameters:
subWave (Subwave)
Returns: subwsubWave object
method draw(wave, limitSubwaves)
Draw Wave
Namespace types: Wave
Parameters:
wave (Wave) : Wave object to be drawn
limitSubwaves (bool) : limit the number of subwave combinations within the wave
Returns: wave object
method checkMotiveWave(prices)
based on the price array, check if there is motive wave and identify the type
Namespace types: array
Parameters:
prices (array) : float array of prices
Returns: WaveType representing the identified wave type. na otherwise
method scanMotiveWave(pivot, lastPivot, existingWaves, allowedTypes)
Scan for motive wave
Namespace types: zg.Pivot
Parameters:
pivot (Pivot type from Trendoscope/Zigzag/7) : Zigzag pivot that will be checked for motive wave
lastPivot (Pivot type from Trendoscope/Zigzag/7) : previous Zigzag pivot
existingWaves (array) : array of existing waves
allowedTypes (array) : allowed Wave types to filter them
Returns: array of subwave pivots
SubwavePivots
SubwavePivots represents the sub pivots of the main wave
Fields:
waveType (series WaveType) : Type of the Wave
indices (array) : Bar index values of sub waves
subPivots (array type from Trendoscope/Zigzag/7) : sub pivot objects of the wave
Subwave
Subwave represents the drawing of sub waves
Fields:
waves (array type from Trendoscope/Drawing/1) : array of sub wave lines
points (array type from Trendoscope/Drawing/1) : Array of subwave pivot labels
subwavePivots (SubwavePivots) : array of subwave pivots being drawn
Wave
Wave object type
Fields:
pivot (Pivot type from Trendoscope/Zigzag/7) : starting point of the wave
wave (Line type from Trendoscope/Drawing/1) : Line representing the wave
waveLabel (Label type from Trendoscope/Drawing/1) : label containing wave details
subWaves (array) : array of sub waves
DrawingLibrary "Drawing"
User Defined types and methods for basic drawing structure. Consolidated from the earlier libraries - DrawingTypes and DrawingMethods
method get_price(this, bar)
get line price based on bar
Namespace types: Line
Parameters:
this (Line) : (series Line) Line object.
bar (int) : (series/int) bar at which line price need to be calculated
Returns: line price at given bar.
method init(this)
Namespace types: PolyLine
Parameters:
this (PolyLine)
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Point object to string representation
Namespace types: chart.point
Parameters:
this (chart.point) : DrawingTypes/Point object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Point
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/LineProperties object to string representation
Namespace types: LineProperties
Parameters:
this (LineProperties) : DrawingTypes/LineProperties object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/LineProperties
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Line object to string representation
Namespace types: Line
Parameters:
this (Line) : DrawingTypes/Line object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Line
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/LabelProperties object to string representation
Namespace types: LabelProperties
Parameters:
this (LabelProperties) : DrawingTypes/LabelProperties object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/LabelProperties
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Label object to string representation
Namespace types: Label
Parameters:
this (Label) : DrawingTypes/Label object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Label
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Linefill object to string representation
Namespace types: Linefill
Parameters:
this (Linefill) : DrawingTypes/Linefill object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Linefill
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/BoxProperties object to string representation
Namespace types: BoxProperties
Parameters:
this (BoxProperties) : DrawingTypes/BoxProperties object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/BoxProperties
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/BoxText object to string representation
Namespace types: BoxText
Parameters:
this (BoxText) : DrawingTypes/BoxText object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/BoxText
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Box object to string representation
Namespace types: Box
Parameters:
this (Box) : DrawingTypes/Box object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Box
method delete(this)
Deletes line from DrawingTypes/Line object
Namespace types: Line
Parameters:
this (Line) : DrawingTypes/Line object
Returns: Line object deleted
method delete(this)
Deletes label from DrawingTypes/Label object
Namespace types: Label
Parameters:
this (Label) : DrawingTypes/Label object
Returns: Label object deleted
method delete(this)
Deletes Linefill from DrawingTypes/Linefill object
Namespace types: Linefill
Parameters:
this (Linefill) : DrawingTypes/Linefill object
Returns: Linefill object deleted
method delete(this)
Deletes box from DrawingTypes/Box object
Namespace types: Box
Parameters:
this (Box) : DrawingTypes/Box object
Returns: DrawingTypes/Box object deleted
method delete(this)
Deletes lines from array of DrawingTypes/Line objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Line objects
Returns: Array of DrawingTypes/Line objects
method delete(this)
Deletes labels from array of DrawingTypes/Label objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Label objects
Returns: Array of DrawingTypes/Label objects
method delete(this)
Deletes linefill from array of DrawingTypes/Linefill objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Linefill objects
Returns: Array of DrawingTypes/Linefill objects
method delete(this)
Deletes boxes from array of DrawingTypes/Box objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Box objects
Returns: Array of DrawingTypes/Box objects
method clear(this)
clear items from array of DrawingTypes/Line while deleting underlying objects
Namespace types: array
Parameters:
this (array) : array
Returns: void
method clear(this)
clear items from array of DrawingTypes/Label while deleting underlying objects
Namespace types: array
Parameters:
this (array) : array
Returns: void
method clear(this)
clear items from array of DrawingTypes/Linefill while deleting underlying objects
Namespace types: array
Parameters:
this (array) : array
Returns: void
method clear(this)
clear items from array of DrawingTypes/Box while deleting underlying objects
Namespace types: array
Parameters:
this (array) : array
Returns: void
method draw(this)
Creates line from DrawingTypes/Line object
Namespace types: Line
Parameters:
this (Line) : DrawingTypes/Line object
Returns: line created from DrawingTypes/Line object
method draw(this)
Creates lines from array of DrawingTypes/Line objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Line objects
Returns: Array of DrawingTypes/Line objects
method draw(this)
Creates label from DrawingTypes/Label object
Namespace types: Label
Parameters:
this (Label) : DrawingTypes/Label object
Returns: label created from DrawingTypes/Label object
method draw(this)
Creates labels from array of DrawingTypes/Label objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Label objects
Returns: Array of DrawingTypes/Label objects
method draw(this)
Creates linefill object from DrawingTypes/Linefill
Namespace types: Linefill
Parameters:
this (Linefill) : DrawingTypes/Linefill objects
Returns: linefill object created
method draw(this)
Creates linefill objects from array of DrawingTypes/Linefill objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Linefill objects
Returns: Array of DrawingTypes/Linefill used for creating linefills
method draw(this)
Creates box from DrawingTypes/Box object
Namespace types: Box
Parameters:
this (Box) : DrawingTypes/Box object
Returns: box created from DrawingTypes/Box object
method draw(this)
Creates labels from array of DrawingTypes/Label objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Label objects
Returns: Array of DrawingTypes/Label objects
method createLabel(this, lblText, tooltip, properties)
Creates DrawingTypes/Label object from DrawingTypes/Point
Namespace types: chart.point
Parameters:
this (chart.point) : DrawingTypes/Point object
lblText (string) : Label text
tooltip (string) : Tooltip text. Default is na
properties (LabelProperties) : DrawingTypes/LabelProperties object. Default is na - meaning default values are used.
Returns: DrawingTypes/Label object
method createLine(this, other, properties)
Creates DrawingTypes/Line object from one DrawingTypes/Point to other
Namespace types: chart.point
Parameters:
this (chart.point) : First DrawingTypes/Point object
other (chart.point) : Second DrawingTypes/Point object
properties (LineProperties) : DrawingTypes/LineProperties object. Default set to na - meaning default values are used.
Returns: DrawingTypes/Line object
method createLinefill(this, other, fillColor, transparency)
Creates DrawingTypes/Linefill object from DrawingTypes/Line object to other DrawingTypes/Line object
Namespace types: Line
Parameters:
this (Line) : First DrawingTypes/Line object
other (Line) : Other DrawingTypes/Line object
fillColor (color) : fill color of linefill. Default is color.blue
transparency (int) : fill transparency for linefill. Default is 80
Returns: Array of DrawingTypes/Linefill object
method createBox(this, other, properties, textProperties)
Creates DrawingTypes/Box object from one DrawingTypes/Point to other
Namespace types: chart.point
Parameters:
this (chart.point) : First DrawingTypes/Point object
other (chart.point) : Second DrawingTypes/Point object
properties (BoxProperties) : DrawingTypes/BoxProperties object. Default set to na - meaning default values are used.
textProperties (BoxText) : DrawingTypes/BoxText object. Default is na - meaning no text will be drawn
Returns: DrawingTypes/Box object
method createBox(this, properties, textProperties)
Creates DrawingTypes/Box object from DrawingTypes/Line as diagonal line
Namespace types: Line
Parameters:
this (Line) : Diagonal DrawingTypes/PoLineint object
properties (BoxProperties) : DrawingTypes/BoxProperties object. Default set to na - meaning default values are used.
textProperties (BoxText) : DrawingTypes/BoxText object. Default is na - meaning no text will be drawn
Returns: DrawingTypes/Box object
LineProperties
Properties of line object
Fields:
xloc (series string) : X Reference - can be either xloc.bar_index or xloc.bar_time. Default is xloc.bar_index
extend (series string) : Property which sets line to extend towards either right or left or both. Valid values are extend.right, extend.left, extend.both, extend.none. Default is extend.none
color (series color) : Line color
style (series string) : Line style, valid values are line.style_solid, line.style_dashed, line.style_dotted, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both. Default is line.style_solid
width (series int) : Line width. Default is 1
Line
Line object created from points
Fields:
start (chart.point) : Starting point of the line
end (chart.point) : Ending point of the line
properties (LineProperties) : LineProperties object which defines the style of line
object (series line) : Derived line object
LabelProperties
Properties of label object
Fields:
xloc (series string) : X Reference - can be either xloc.bar_index or xloc.bar_time. Default is xloc.bar_index
yloc (series string) : Y reference - can be yloc.price, yloc.abovebar, yloc.belowbar. Default is yloc.price
color (series color) : Label fill color
style (series string) : Label style as defined in Tradingview Documentation. Default is label.style_none
textcolor (series color) : text color. Default is color.black
size (series string) : Label text size. Default is size.normal. Other values are size.auto, size.tiny, size.small, size.normal, size.large, size.huge
textalign (series string) : Label text alignment. Default if text.align_center. Other allowed values - text.align_right, text.align_left, text.align_top, text.align_bottom
text_font_family (series string) : The font family of the text. Default value is font.family_default. Other available option is font.family_monospace
Label
Label object
Fields:
point (chart.point) : Point where label is drawn
lblText (series string) : label text
tooltip (series string) : Tooltip text. Default is na
properties (LabelProperties) : LabelProperties object
object (series label) : Pine label object
Linefill
Linefill object
Fields:
line1 (Line) : First line to create linefill
line2 (Line) : Second line to create linefill
fillColor (series color) : Fill color
transparency (series int) : Fill transparency range from 0 to 100
object (series linefill) : linefill object created from wrapper
BoxProperties
BoxProperties object
Fields:
border_color (series color) : Box border color. Default is color.blue
bgcolor (series color) : box background color
border_width (series int) : Box border width. Default is 1
border_style (series string) : Box border style. Default is line.style_solid
extend (series string) : Extend property of box. default is extend.none
xloc (series string) : defines if drawing needs to be done based on bar index or time. default is xloc.bar_index
BoxText
Box Text properties.
Fields:
boxText (series string) : Text to be printed on the box
text_size (series string) : Text size. Default is size.auto
text_color (series color) : Box text color. Default is color.yellow.
text_halign (series string) : horizontal align style - default is text.align_center
text_valign (series string) : vertical align style - default is text.align_center
text_wrap (series string) : text wrap style - default is text.wrap_auto
text_font_family (series string) : Text font. Default is
Box
Box object
Fields:
p1 (chart.point) : Diagonal point one
p2 (chart.point) : Diagonal point two
properties (BoxProperties) : Box properties
textProperties (BoxText) : Box text properties
object (series box) : Box object created
PolyLineProperties
Fields:
curved (series bool)
closed (series bool)
xloc (series string)
lineColor (series color)
fillColor (series color)
lineStyle (series string)
lineWidth (series int)
PolyLine
Fields:
points (array)
properties (PolyLineProperties)
object (series polyline)
lib_no_delayLibrary "lib_no_delay"
This library contains modifications to standard functions that return na before reaching the bar of their 'length' parameter.
That is because they do not compromise speed at current time for correct results in the past. This is good for live trading in short timeframes but killing applications on Monthly / Weekly timeframes if instruments, like in crypto, do not have extensive history (why would you even trade the monthly on a meme coin ... not my decision).
Also, some functions rely on source (value at previous bar), which is not available on bar 1 and therefore cascading to a na value up to the last bar ... which in turn leads to a non displaying indicator and waste of time debugging this)
Anyway ... there you go, let me know if I should add more functions.
sma(source, length)
Parameters:
source (float) : Series of values to process.
length (simple int) : Number of bars (length).
Returns: Simple moving average of source for length bars back.
ema(source, length)
Parameters:
source (float) : Series of values to process.
length (simple int) : Number of bars (length).
Returns: (float) The exponentially weighted moving average of the source.
rma(source, length)
Parameters:
source (float) : Series of values to process.
length (simple int) : Number of bars (length).
Returns: Exponential moving average of source with alpha = 1 / length.
atr(length)
Function atr (average true range) returns the RMA of true range. True range is max(high - low, abs(high - close ), abs(low - close )). This adapted version extends ta.atr to start without delay at first bar and deliver usable data instead of na by averaging ta.tr(true) via manual SMA.
Parameters:
length (simple int) : Number of bars back (length).
Returns: Average true range.
rsi(source, length)
Relative strength index. It is calculated using the ta.rma() of upward and downward changes of source over the last length bars. This adapted version extends ta.rsi to start without delay at first bar and deliver usable data instead of na.
Parameters:
source (float) : Series of values to process.
length (simple int) : Number of bars back (length).
Returns: Relative Strength Index.
ToClrToStrContains functions for conversion of color to string and vice versa:
method toClr( string this ) - converts string reperesentation of color (in hex format) to color
method toHex( color this ) - converts color to string (hex form)
method toRgb( color this ) - converts color to string ("rgb(11,11,11,0)" form)
Thanks to @ImmortalFreedom for his `color_tostring()` function from "RGB Color Fiddler"
Time Zone CorrectorThe Time Zone Corrector library provides a utility function designed to adjust time based on the user's current time zone. This library supports a wide range of time zones across the Americas, Europe, Asia, and Oceania, making it highly versatile for traders around the world. It simulates a switch-case structure using ternary operators to output the appropriate time offset relative to UTC.
Whether you're dealing with market sessions in New York, Tokyo, London, or other major trading hubs, this library helps ensure your trading algorithms can accurately account for time differences. The library is particularly useful for strategies that rely on precise timing, as it dynamically adjusts the time zone offset depending on the symbol being traded.
SessionLibrary "Session"
Helper functions for trading sessions. TradingView doesn't provide correct data when
calling some of the convenience methods like session.ismarket when you are looking at futures charts. This library corrects those mistakes by providing functions with the same names as the TradingView default properties. that reference a custom defined set of session hours for futures. It also provides a way for consumers to customize the map values by calling getSessionMap() and then overwriting (or adding) custom session definitions.
getSessionMap()
Returns a map of the futures rth & eth session hours. The map is keyed with symbol:session format (eg. ES:market or ES:overnight).
Returns: A map of futures symbols and their associated session hours.
getSessionString(session, symbol, sessionMap)
Returns a session string representing the session hours (and days) for the requested symbol (or the chart's symbol if the symbol value is not provided). If the session string is not found in the collection, it will return a blank string.
Parameters:
session (string) : A string representing the session hour being requested. One of: market (regular trading hours), overnight (extended/electronic trading hours), postmarket (after-hours), premarket
symbol (string) : The symbol to check. Optional. Defaults to chart symbol.
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
inSession(session, sessionMap, barsBack)
Returns true if the current symbol is currently in the session parameters defined by sessionString.
Parameters:
session (string) : A string representing the session hour being requested. One of: market (regular trading hours), overnight (extended/electronic trading hours), postmarket (after-hours), premarket
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
barsBack (int) : Private. Only used by futures to check islastbar. Optional. The default is 0.
ismarket(sessionMap)
Returns true if the current bar is a part of the regular trading hours (i.e. market hours), false otherwise. Works for futures (TradingView's methods do not).
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
isfirstbar()
Returns true if the current bar is the first bar of the day's session, false otherwise. If extended session information is used, only returns true on the first bar of the pre-market bars. Works for futures (TradingView's methods do not).
Returns: bool
islastbar()
Returns true if the current bar is the last bar of the day's session, false otherwise. If extended session information is used, only returns true on the last bar of the post-market bars. Works for futures (TradingView's methods do not).
Returns: bool
ispremarket(sessionMap)
Returns true if the current bar is a part of the pre-market, false otherwise. On non-intraday charts always returns false. Works for futures (TradingView's methods do not).
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
ispostmarket(sessionMap)
Returns true if the current bar is a part of the post-market, false otherwise. On non-intraday charts always returns false. Works for futures (TradingView's methods do not).
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
isfirstbar_regular(sessionMap)
Returns true on the first regular session bar of the day, false otherwise. The result is the same whether extended session information is used or not. Works for futures (TradingView's methods do not).
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
islastbar_regular(sessionMap)
Returns true on the last regular session bar of the day, false otherwise. The result is the same whether extended session information is used or not. Works for futures (TradingView's methods do not).
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
isovernight(sessionMap)
Returns true if the current bar is a part of the pre-market or post-market, false otherwise. On non-intraday charts always returns false.
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
getSessionHighAndLow(session, sessionMap)
Returns a tuple containing the high and low print during the specified session.
Parameters:
session (string) : The session for which to get the high & low prints. Defaults to market.
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: A tuple containing
TradingHook_LibraryLibrary "TradingHook_Library"
This library is a client script for making a webhook signal formatted string to TradingHook webhook server.
buy_message(password, amount, order_name)
Make a buy Message for TradingHook.
Parameters:
password (string) : (string) password that you set in .env file.
amount (float) : (float) amount. If not set, your strategy qty will be sent.
order_name (string) : (string) order_name. The default name is "Order".
Returns: (string) A string containing the formatted webhook message.
sell_message(password, percent, order_name)
Make a sell message for TradingHook.
Parameters:
password (string) : (string) password that you set in .env file.
percent (string) : (string) what percentage of your quantity you want to sell.
order_name (string) : (string) order_name. The default name is "Order".
Returns: (string) A string containing the formatted webhook message.
entry_message(password, amount, leverage, order_name)
Make a Entry Message for TradingHook.
Parameters:
password (string) : (string) password that you set in .env file.
amount (float) : (float) amount. If not set, your strategy qty will be sent.
leverage (int) : (int) leverage. If not set, your leverage doesn't change.
order_name (string) : (string) order_name. The default name is "Order".
Returns: (string) A string containing the formatted webhook message.
close_message(password, percent, amount, order_name)
Make a close message for TradingHook.
Parameters:
password (string) : (string) password that you set in .env file.
percent (string) : (string) what percentage of your quantity you want to close.
amount (float) : (float) quantity you want to close.
order_name (string) : (string) order_name. The default name is "Order".
Returns: (string) A string containing the formatted webhook message.