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.
iteratorThe "Iterator" library is designed to provide a flexible way to work with sequences of values. This library offers a set of functions to create and manage iterators for various data types, including integers, floats, and more. Whether you need to generate an array of values with specific increments or iterate over elements in reverse order, this library has you covered.
Key Features:
Array Creation: Easily generate arrays of integers or floats with customizable steps, both inclusive and exclusive of the end values.
Flexible Iteration: Includes methods to iterate over arrays of different types, such as booleans, integers, floats, strings, colors, and drawing objects like lines and labels.
Reverse Iteration: Support for reverse iteration, giving you control over the order in which elements are processed.
Automatic Loop Control: One of the key advantages of this library is that when using the .iterate() method, it only loops over the array when there are values present. This means you don’t have to manually check if the array is populated before iterating, simplifying your code and reducing potential errors.
Versatile Use Cases: Ideal for scenarios where you need to loop over an array without worrying about empty arrays or checking conditions manually.
This library is particularly useful in cases where you need to perform operations on each element in an array, ensuring that your loops are efficient and free from unnecessary checks.
Library "iterator"
The "iterator" library provides a versatile and efficient set of functions for creating and managing iterators.
It allows you to generate arrays of integers or floats with customizable steps, both inclusive and exclusive of the end values.
The library also includes methods for iterating over various types, including booleans, integers, floats, strings, colors,
and drawing objects like lines and labels. With support for reverse iteration and flexible customization options.
iterator(stop, start, step)
Creates an array of integers from start to stop with a specified step, excluding the stop value.
Parameters:
stop (int) : The end value of the iterator, exclusive.
start (int) : The starting value of the iterator. Default is 0.
step (int) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of integers incremented by the step value from start to stop. Will return and empty array if start = stop.
iterator(stop, start, step)
Creates an array of floats from start to stop with a specified step, excluding the stop value.
Parameters:
stop (float) : The end value of the iterator, exclusive.
start (float) : The starting value of the iterator. Default is 0.
step (float) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of floats incremented by the step value from start to stop. Will return and empty array if start = stop.
iterator_inclusive(stop, start, step)
Creates an array of integers from start to stop with a specified step, including the stop value.
Parameters:
stop (int) : The end value of the iterator, inclusive.
start (int) : The starting value of the iterator. Default is 0.
step (int) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of integers incremented by the step value from start to stop, including the stop value.
iterator_inclusive(stop, start, step)
Creates an array of floats from start to stop with a specified step, including the stop value.
Parameters:
stop (float) : The end value of the iterator, inclusive.
start (float) : The starting value of the iterator. Default is 0.
step (float) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of floats incremented by the step value from start to stop, including the stop value.
itr(stop, start, step)
Creates an array of integers from start to stop with a specified step, excluding the stop value.
Parameters:
stop (int) : The end value of the iterator, exclusive.
start (int) : The starting value of the iterator. Default is 0.
step (int) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of integers incremented by the step value from start to stop.
itr(stop, start, step)
Creates an array of floats from start to stop with a specified step, excluding the stop value.
Parameters:
stop (float) : The end value of the iterator, exclusive.
start (float) : The starting value of the iterator. Default is 0.
step (float) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of floats incremented by the step value from start to stop.
itr_in(stop, start, step)
Creates an array of integers from start to stop with a specified step, including the stop value.
Parameters:
stop (int) : The end value of the iterator, inclusive.
start (int) : The starting value of the iterator. Default is 0.
step (int) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of integers incremented by the step value from start to stop, including the stop value.
itr_in(stop, start, step)
Creates an array of floats from start to stop with a specified step, including the stop value.
Parameters:
stop (float) : The end value of the iterator, inclusive.
start (float) : The starting value of the iterator. Default is 0.
step (float) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of floats incremented by the step value from start to stop, including the stop value.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
whookLibrary "whook"
This library provides functions for generating trading alerts for `whook`
check this -> github.com
Currently supported exchanges:
Kucoin futures
Bitget futures
Coinex futures
Bingx
OKX futures ( also its demo mode )
Bybit futures ( also Bybit testnet )
Binance futures ( also Binance futures testnet )
Phemex futures ( also Phemex testnet )
Kraken futures ( also Kraken futures testnet )
# --- Test Cases ---
Note: These test cases are for demonstration purposes only and may not cover all scenarios.
// buy(string account, float amount, string unit = "units", float leverage = 1)
buy("MyAccount", 100, "units", 1)
buy("MyAccount", 1000, "USDT", 5)
buy("MyAccount", 50, "percent", 2)
// sell(string account, float amount, string unit = "units", float leverage = 1)
sell("MyAccount", 50, "units", 1)
sell("MyAccount", 500, "USDT", 3)
sell("MyAccount", 25, "percent", 2)
// set_position(string account, float amount, string unit = "units", float leverage = 1)
set_position("MyAccount", 100, "units", 1)
set_position("MyAccount", 1000, "USDT", 5)
set_position("MyAccount", 50, "percent", 2)
// limit_buy(string account, float amount, float price, string unit = "units", float leverage = 1, string id = "")
limit_buy("MyAccount", 100, 10000, "units", 1, "MyBuyOrder")
limit_buy("MyAccount", 1000, 10500, "USDT", 5)
limit_buy("MyAccount", 50, 11000, "percent", 2)
// limit_sell(string account, float amount, float price, string unit = "units", float leverage = 1, string id = "")
limit_sell("MyAccount", 50, 10000, "units", 1, "MySellOrder")
limit_sell("MyAccount", 500, 9500, "USDT", 3)
limit_sell("MyAccount", 25, 9000, "percent", 2)
// close_percent(string account, float pct = 100)
close_percent("MyAccount", 100)
close_percent("MyAccount", 50)
buy(account, amount, unit, leverage)
Sends a trading alert to execute a market buy order.
Parameters:
account (string) : The account ID.
amount (float) : The amount to buy (can be in USD, units, or percentage).
unit (string) : The unit of the amount (optional, defaults to "units").
leverage (float) : The leverage to use (optional, defaults to 1x).
sell(account, amount, unit, leverage)
Sends a trading alert to execute a market sell order.
Parameters:
account (string) : The account ID.
amount (float) : The amount to sell (can be in USD, units, or percentage).
unit (string) : The unit of the amount (optional, defaults to "units").
leverage (float) : The leverage to use (optional, defaults to 1x).
set_position(account, amount, unit, leverage)
Sends a trading alert to set a position.
Parameters:
account (string) : The account ID.
amount (float) : The amount to set the position to (can be in USD, units, or percentage).
unit (string) : The unit of the amount (optional, defaults to "units").
leverage (float) : The leverage to use (optional, defaults to 1x).
limit_buy(account, amount, price, unit, leverage, id)
Sends a trading alert to place a limit buy order.
Parameters:
account (string) : The account ID.
amount (float) : The amount to buy (can be in USD, units, or percentage).
price (float) : The limit price.
unit (string) : The unit of the amount (optional, defaults to "units").
leverage (float) : The leverage to use (optional, defaults to 1x).
id (string) : An optional custom ID for the limit order.
limit_sell(account, amount, price, unit, leverage, id)
Sends a trading alert to place a limit sell order.
Parameters:
account (string) : The account ID.
amount (float) : The amount to sell (can be in USD, units, or percentage).
price (float) : The limit price.
unit (string) : The unit of the amount (optional, defaults to "units").
leverage (float) : The leverage to use (optional, defaults to 1x).
id (string) : An optional custom ID for the limit order.
close_percent(account, pct)
Sends an alert to close a position on Phemex.
Parameters:
account (string) : The account ID.
pct (float) : The percentage of the position to close (optional, defaults to 100%).
csv_series_libraryThe CSV Series Library is an innovative tool designed for Pine Script developers to efficiently parse and handle CSV data for series generation. This library seamlessly integrates with TradingView, enabling the storage and manipulation of large CSV datasets across multiple Pine Script libraries. It's optimized for performance and scalability, ensuring smooth operation even with extensive data.
Features:
Multi-library Support: Allows for distribution of large CSV datasets across several libraries, ensuring efficient data management and retrieval.
Dynamic CSV Parsing: Provides robust Python scripts for reading, formatting, and partitioning CSV data, tailored specifically for Pine Script requirements.
Extensive Data Handling: Supports parsing CSV strings into Pine Script-readable series, facilitating complex financial data analysis.
Automated Function Generation: Automatically wraps CSV blocks into distinct Pine Script functions, streamlining the process of integrating CSV data into Pine Script logic.
Usage:
Ideal for traders and developers who require extensive data analysis capabilities within Pine Script, especially when dealing with large datasets that need to be partitioned into manageable blocks. The library includes a set of predefined functions for parsing CSV data into usable series, making it indispensable for advanced trading strategy development.
Example Implementation:
CSV data is transformed into Pine Script series using generated functions.
Multiple CSV blocks can be managed and parsed, allowing for flexible data series creation.
The library includes comprehensive examples demonstrating the conversion of standard CSV files into functional Pine Script code.
To effectively utilize the CSV Series Library in Pine Script, it is imperative to initially generate the correct data format using the accompanying Python program. Here is a detailed explanation of the necessary steps:
1. Preparing the CSV Data:
The Python script provided with the CSV Series Library is designed to handle CSV files that strictly contain no-space, comma-separated single values. It is crucial that your CSV file adheres to this format to ensure compatibility and correctness of the data processing.
2. Using the Python Program to Generate Data:
Once your CSV file is prepared, you need to use the Python program to convert this file into a format that Pine Script can interpret. The Python script performs several key functions:
Reads the CSV file, ensuring that it matches the required format of no-space, comma-separated values.
Formats the data into blocks, where each block is a string of data that does not exceed a specified character limit (default is 4,000 characters). This helps manage large datasets by breaking them down into manageable chunks.
Wraps these blocks into Pine Script functions, each block being encapsulated in its own function to maintain organization and ease of access.
3. Generating and Managing Multiple Libraries:
If the data from your CSV file exceeds the Pine Script or platform limits (e.g., too many characters for a single script), the Python script can split this data into multiple blocks across several files.
4. Creating a Pine Script Library:
After generating the formatted data blocks, you must create a Pine Script library where these blocks are integrated. Each block of data is contained within its function, like my_csv_0(), my_csv_1(), etc. The full_csv() function in Pine Script then dynamically loads and concatenates these blocks to reconstruct the full data series.
5. Exporting the full_csv() Function:
Once your Pine Script library is set up with all the CSV data blocks and the full_csv() function, you export this function from the library. This exported function can then be used in your actual trading projects. It allows Pine Script to access and utilize the entire dataset as if it were a single, continuous series, despite potentially being segmented across multiple library files.
6. Reconstructing the Full Series Using vec :
When your dataset is particularly large, necessitating division into multiple parts, the vec type is instrumental in managing this complexity. Here’s how you can effectively reconstruct and utilize your segmented data:
Definition of vec Type: The vec type in Pine Script is specifically designed to hold a dataset as an array of floats, allowing you to manage chunks of CSV data efficiently.
Creating an Array of vec Instances: Once you have your data split into multiple blocks and each block is wrapped into its own function within Pine Script libraries, you will need to construct an array of vec instances. Each instance corresponds to a segment of your complete dataset.
Using array.from(): To create this array, you utilize the array.from() function in Pine Script. This function takes multiple arguments, each being a vec instance that encapsulates a data block. Here’s a generic example:
vec series_vector = array.from(vec.new(data_block_1), vec.new(data_block_2), ..., vec.new(data_block_n))
In this example, data_block_1, data_block_2, ..., data_block_n represent the different segments of your dataset, each returned from their respective functions like my_csv_0(), my_csv_1(), etc.
Accessing and Utilizing the Data: Once you have your vec array set up, you can access and manipulate the full series through Pine Script functions designed to handle such structures. You can traverse through each vec instance, processing or analyzing the data as required by your trading strategy.
This approach allows Pine Script users to handle very large datasets that exceed single-script limits by segmenting them and then methodically reconstructing the dataset for comprehensive analysis. The vec structure ensures that even with segmentation, the data can be accessed and utilized as if it were contiguous, thus enabling powerful and flexible data manipulation within Pine Script.
Library "csv_series_library"
A library for parsing and handling CSV data to generate series in Pine Script. Generally you will store the csv strings generated from the python code in libraries. It is set up so you can have multiple libraries to store large chunks of data. Just export the full_csv() function for use with this library.
method csv_parse(data)
Namespace types: array
Parameters:
data (array)
method make_series(series_container, start_index)
Namespace types: array
Parameters:
series_container (array)
start_index (int)
Returns: A tuple containing the current value of the series and a boolean indicating if the data is valid.
method make_series(series_vector, start_index)
Namespace types: array
Parameters:
series_vector (array)
start_index (int)
Returns: A tuple containing the current value of the series and a boolean indicating if the data is valid.
vec
A type that holds a dataset as an array of float arrays.
Fields:
data_set (array) : A chunk of csv data. (A float array)
DynamicRSILibrary "DynamicRSI"
The "DynamicRSI" library provides a method to calculate a Dynamic Relative Strength Index (RSI) that adjusts its sensitivity based on market volatility. By combining short and long RSI periods with a weighted average influenced by the market's volatility, this library allows users to obtain a more responsive RSI tailored to changing market conditions.
"DynamicRSI" 라이브러리는 시장 변동성에 따라 감도를 조정하는 동적 상대 강도 지수(RSI)를 계산하는 방법을 제공합니다. 짧은 RSI와 긴 RSI 기간을 시장 변동성에 따라 가중 평균하여 결합함으로써, 이 라이브러리는 시장 상황에 맞게 보다 유연하게 반응하는 RSI를 제공합니다.
Function: drsi(src, minLength, maxLength, volatilityPeriod)
함수: drsi(src, minLength, maxLength, volatilityPeriod)
Parameters:
src (float)
The source data to calculate the RSI (e.g., close price). This is the price data that the RSI is calculated on.
RSI를 계산하기 위한 입력 데이터입니다(예: 종가(close) ). 이 값은 RSI를 계산하는 기준이 되는 가격 데이터입니다.
minLength (simple int)
The period for the shorter RSI. This parameter controls the sensitivity of the RSI, with a shorter period making the RSI more reactive to price changes.
짧은 RSI 기간입니다. 이 매개변수는 RSI의 감도를 제어하며, 더 짧은 기간은 RSI가 가격 변화에 더 민감하게 반응하게 합니다.
maxLength (simple int)
The period for the longer RSI. This parameter provides a smoother RSI, which is less sensitive to short-term price fluctuations.
긴 RSI 기간입니다. 이 매개변수는 더 부드러운 RSI를 제공하며, 단기적인 가격 변동에 덜 민감하게 반응합니다.
volatilityPeriod (simple int)
The period used for calculating the Average True Range (ATR) to measure market volatility. This volatility is then used to adjust the weighting between the short and long RSI, making the final Dynamic RSI more adaptive to market conditions.
시장 변동성을 측정하기 위해 평균 진정 범위(ATR)를 계산하는 기간입니다. 이 변동성을 기반으로 짧은 RSI와 긴 RSI 간의 가중치를 조정하여 최종 Dynamic RSI가 시장 상황에 더 잘 적응할 수 있도록 합니다.
Description:
The drsi function calculates a Dynamic RSI by weighting the short-term and long-term RSI values according to the current market volatility. The function uses the ATR to determine the market's volatility, applying more weight to the short-term RSI when volatility is high and more weight to the long-term RSI when volatility is low. This approach ensures that the RSI is more responsive during volatile periods and smoother during stable periods, providing traders with a more effective tool for identifying overbought and oversold conditions in varying market environments.
drsi 함수는 현재 시장 변동성에 따라 단기와 장기의 RSI 값을 가중치로 조정하여 Dynamic RSI를 계산합니다. 이 함수는 시장의 변동성을 판단하기 위해 ATR을 사용하며, 변동성이 높을 때는 단기 RSI에 더 많은 가중치를 적용하고, 변동성이 낮을 때는 장기 RSI에 더 많은 가중치를 적용합니다. 이 접근 방식은 변동성이 큰 기간 동안 RSI가 더 민감하게 반응하고, 안정적인 기간 동안 더 부드럽게 반응하도록 하여, 다양한 시장 환경에서 과매수 및 과매도 상태를 식별하는 데 보다 효과적인 도구를 제공합니다.