ChartPatternSetupsLibrary "ChartPatternSetups"
detectSymmetricalTriangle(lookback)
Detects a Symmetrical Triangle (Bullish or Bearish) and provides trade levels.
Parameters:
lookback (int) : Number of bars to look back for pivots.
Returns: Tuple of (isBullish, isBearish, entry, sl, tp).
detectAscendingTriangle(lookback)
Detects an Ascending Triangle (Bullish) and provides trade levels.
Parameters:
lookback (int) : Number of bars to look back for pivots.
Returns: Tuple of (isDetected, entry, sl, tp).
detectDescendingTriangle(lookback)
Detects a Descending Triangle (Bearish) and provides trade levels.
Parameters:
lookback (int) : Number of bars to look back for pivots.
Returns: Tuple of (isDetected, entry, sl, tp).
detectFallingWedge(lookback)
Detects a Falling Wedge (Bullish) and provides trade levels.
Parameters:
lookback (int) : Number of bars to look back for pivots.
Returns: Tuple of (isDetected, entry, sl, tp).
detectRisingWedge(lookback)
Detects a Rising Wedge (Bearish) and provides trade levels.
Parameters:
lookback (int) : Number of bars to look back for pivots.
Returns: Tuple of (isDetected, entry, sl, tp).
Indikatoren und Strategien
SCoLibraryAmsterdamLibrary "SCoLibraryAmsterdam"
This library contains functions to check Amsterdam strategy price events
calcTrendMom(FilterTrendWithMa50, FilterTrendWithMa200)
This function define the current trend and momentum force according to 4wma, 12wma, 21ema and 200sma
Parameters:
FilterTrendWithMa50 (bool) : is set to true will filter trend result with 50sma
FilterTrendWithMa200 (bool) : is set to true will filter trend result with 200sma
Returns: Return a positive value if trend is up (2 : strong momentum, 1 : weak momentum) and a negative value if trend is negative (-2 : strong momentum, -1 : weak momentum)
calcPriceAmstNodeMa01(close, AtrPeriod, AtrMultiplier)
This function checks if close, 4wma and 12wma are in contraction within a multiple of the average true range
Parameters:
close (float)
AtrPeriod (simple int) : is the period used to calculate the average true range (ATR)
AtrMultiplier (float) : is the multiplier of the average true range
Returns: Return true or false
calcPriceAmstNodeMa123(close, AtrPeriod, AtrMultiplier)
This function checks if close, 12wma, 21ema and 50sma are in contraction within a multiple of the average true range
Parameters:
close (float)
AtrPeriod (simple int) : is the period used to calculate the average true range (ATR)
AtrMultiplier (float) : is the multiplier of the average true range
Returns: Return true or false
calcPriceInsidebar()
This function checks inside bar candle configuration
Returns: true or false
calcPrice12wmaExtended(close, PeriodNormalization, ExtensionPercent)
This function checks if close is over extended from the 12wma by a multiple of the average true range
Parameters:
close (float)
PeriodNormalization (int)
ExtensionPercent (float)
Returns: Return true or false
calcPrice21emaExtended(close, PeriodNormalization, ExtensionPercent)
This function checks if close is over extended from the 21ema by a multiple of the average true range
Parameters:
close (float)
PeriodNormalization (int)
ExtensionPercent (float)
Returns: Return true or false
calcPrice50smaExtended(close, PeriodNormalization, ExtensionPercent)
This function checks if close is over extended from the 50sma by a multiple of the average true range
Parameters:
close (float)
PeriodNormalization (int)
ExtensionPercent (float)
Returns: Return true or false
calcPrice200smaExtended(close, PeriodNormalization, ExtensionPercent)
This function checks if close is over extended from the 200sma by a multiple of the average true range
Parameters:
close (float)
PeriodNormalization (int)
ExtensionPercent (float)
Returns: Return true or false
calcPriceClimax(close, AtrPeriod, MovingAvgAtrMulti, VolAtrMulti)
This function checks if price is in climax evolution by comparing the extension between 4wma and 12wma, and a multiple of the average true range
Parameters:
close (float)
AtrPeriod (simple int) : is the average true range period
MovingAvgAtrMulti (float) : is the extension ratio
VolAtrMulti (float) : is the volume extension relative to the 21sma volume
Returns: Return true or false
LinearRegressionLibrary "LinearRegression"
Calculates a variety of linear regression and deviation types, with optional emphasis weighting. Additionally, multiple of slope and Pearson’s R calculations.
calcSlope(_src, _len, _condition)
Calculates the slope of a linear regression over the specified length.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The length of the lookback period for the linear regression.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast for efficiency.
Returns: (float) The slope of the linear regression.
calcReg(_src, _len, _condition)
Calculates a basic linear regression, returning y1, y2, slope, and average.
Parameters:
_src (float) : (float) The source data series.
_len (int) : (int) The length of the lookback period.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) An array of 4 values: .
calcRegStandard(_src, _len, _emphasis, _condition)
Calculates an Standard linear regression with optional emphasis.
Parameters:
_src (float) : (series float) The source data series.
_len (int) : (int) The length of the lookback period.
_emphasis (float) : (float) The emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) .
calcRegRidge(_src, _len, lambda, _emphasis, _condition)
Calculates a ridge regression with optional emphasis.
Parameters:
_src (float) : (float) The source data series.
_len (int) : (int) The length of the lookback period.
lambda (float) : (float) The ridge regularization parameter.
_emphasis (float) : (float) The emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) .
calcRegLasso(_src, _len, lambda, _emphasis, _condition)
Calculates a Lasso regression with optional emphasis.
Parameters:
_src (float) : (float) The source data series.
_len (int) : (int) The length of the lookback period.
lambda (float) : (float) The Lasso regularization parameter.
_emphasis (float) : (float) The emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) .
calcElasticNetLinReg(_src, _len, lambda1, lambda2, _emphasis, _condition)
Calculates an Elastic Net regression with optional emphasis.
Parameters:
_src (float) : (float) The source data series.
_len (int) : (int) The length of the lookback period.
lambda1 (float) : (float) L1 regularization parameter (Lasso).
lambda2 (float) : (float) L2 regularization parameter (Ridge).
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) .
calcRegHuber(_src, _len, delta, iterations, _emphasis, _condition)
Calculates a Huber regression using Iteratively Reweighted Least Squares (IRLS).
Parameters:
_src (float) : (float) The source data series.
_len (int) : (int) The length of the lookback period.
delta (float) : (float) Huber threshold parameter.
iterations (int) : (int) Number of IRLS iterations.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) .
calcRegLAD(_src, _len, iterations, _emphasis, _condition)
Calculates a Least Absolute Deviations (LAD) regression via IRLS.
Parameters:
_src (float) : (float) The source data series.
_len (int) : (int) The length of the lookback period.
iterations (int) : (int) Number of IRLS iterations for LAD.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) .
calcRegBayesian(_src, _len, priorMean, priorSpan, sigma, _emphasis, _condition)
Calculates a Bayesian linear regression with optional emphasis.
Parameters:
_src (float) : (float) The source data series.
_len (int) : (int) The length of the lookback period.
priorMean (float) : (float) The prior mean for the slope.
priorSpan (float) : (float) The prior variance (or span) for the slope.
sigma (float) : (float) The assumed standard deviation of residuals.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) .
calcRFromLinReg(_src, _len, _slope, _average, _y1, _condition)
Calculates the Pearson correlation coefficient (R) based on linear regression parameters.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_average (float) : (float) The average value of the source data series.
_y1 (float) : (float) The starting point (y-intercept of the oldest bar) for the linear regression.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast for efficiency.
Returns: (float) The Pearson correlation coefficient (R) adjusted for the direction of the slope.
calcRFromSource(_src, _len, _condition)
Calculates the correlation coefficient (R) using a specified length and source data.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The length of the lookback period.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast for efficiency.
Returns: (float) The correlation coefficient (R).
calcSlopeLengthZero(_src, _len, _minLen, _step, _condition)
Identifies the length at which the slope is flattest (closest to zero).
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length to consider (minimum of 2).
_minLen (int) : (int) The minimum length to start from (cannot exceed the max length).
_step (int) : (int) The increment step for lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length at which the slope is flattest.
calcSlopeLengthHighest(_src, _len, _minLen, _step, _condition)
Identifies the length at which the slope is highest.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length (minimum of 2).
_minLen (int) : (int) The minimum length to start from.
_step (int) : (int) The step for incrementing lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length at which the slope is highest.
calcSlopeLengthLowest(_src, _len, _minLen, _step, _condition)
Identifies the length at which the slope is lowest.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length (minimum of 2).
_minLen (int) : (int) The minimum length to start from.
_step (int) : (int) The step for incrementing lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length at which the slope is lowest.
calcSlopeLengthAbsolute(_src, _len, _minLen, _step, _condition)
Identifies the length at which the absolute slope value is highest.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length (minimum of 2).
_minLen (int) : (int) The minimum length to start from.
_step (int) : (int) The step for incrementing lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length at which the absolute slope value is highest.
calcRLengthZero(_src, _len, _minLen, _step, _condition)
Identifies the length with the lowest absolute R value.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length (minimum of 2).
_minLen (int) : (int) The minimum length to start from.
_step (int) : (int) The step for incrementing lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length with the lowest absolute R value.
calcRLengthHighest(_src, _len, _minLen, _step, _condition)
Identifies the length with the highest R value.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length (minimum of 2).
_minLen (int) : (int) The minimum length to start from.
_step (int) : (int) The step for incrementing lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length with the highest R value.
calcRLengthLowest(_src, _len, _minLen, _step, _condition)
Identifies the length with the lowest R value.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length (minimum of 2).
_minLen (int) : (int) The minimum length to start from.
_step (int) : (int) The step for incrementing lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length with the lowest R value.
calcRLengthAbsolute(_src, _len, _minLen, _step, _condition)
Identifies the length with the highest absolute R value.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length (minimum of 2).
_minLen (int) : (int) The minimum length to start from.
_step (int) : (int) The step for incrementing lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length with the highest absolute R value.
calcDevReverse(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
Calculates the regressive linear deviation in reverse order, with optional emphasis on recent data.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_y1 (float) : (float) The y-intercept (oldest bar) of the linear regression.
_inputDev (float) : (float) The input deviation multiplier.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: A 2-element tuple: .
calcDevForward(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
Calculates the progressive linear deviation in forward order (oldest to most recent bar), with optional emphasis.
Parameters:
_src (float) : (float) The source data array, where _src is oldest and _src is most recent.
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_y1 (float) : (float) The y-intercept of the linear regression (value at the most recent bar, adjusted by slope).
_inputDev (float) : (float) The input deviation multiplier.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: A 2-element tuple: .
calcDevBalanced(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
Calculates the balanced linear deviation with optional emphasis on recent or older data.
Parameters:
_src (float) : (float) Source data array, where _src is the most recent and _src is the oldest.
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_y1 (float) : (float) The y-intercept of the linear regression (value at the oldest bar).
_inputDev (float) : (float) The input deviation multiplier.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: A 2-element tuple: .
calcDevMean(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
Calculates the mean absolute deviation from a forward-applied linear trend (oldest to most recent), with optional emphasis.
Parameters:
_src (float) : (float) The source data array, where _src is the most recent and _src is the oldest.
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_y1 (float) : (float) The y-intercept (oldest bar) of the linear regression.
_inputDev (float) : (float) The input deviation multiplier.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: A 2-element tuple: .
calcDevMedian(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
Calculates the median absolute deviation with optional emphasis on recent data.
Parameters:
_src (float) : (float) The source data array (index 0 = oldest, index _len - 1 = most recent).
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_y1 (float) : (float) The y-intercept (oldest bar) of the linear regression.
_inputDev (float) : (float) The deviation multiplier.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns:
calcDevPercent(_y1, _inputDev, _condition)
Calculates the percent deviation from a given value and a specified percentage.
Parameters:
_y1 (float) : (float) The base value from which to calculate deviation.
_inputDev (float) : (float) The deviation percentage.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: A 2-element tuple: .
calcDevFitted(_len, _slope, _y1, _emphasis, _condition)
Calculates the weighted fitted deviation based on high and low series data, showing max deviation, with optional emphasis.
Parameters:
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_y1 (float) : (float) The Y-intercept (oldest bar) of the linear regression.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: A 2-element tuple: .
calcDevATR(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
Calculates an ATR-style deviation with optional emphasis on recent data.
Parameters:
_src (float) : (float) The source data (typically close).
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_y1 (float) : (float) The Y-intercept (oldest bar) of the linear regression.
_inputDev (float) : (float) The input deviation multiplier.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: A 2-element tuple: .
calcPricePositionPercent(_top, _bot, _src)
Calculates the percent position of a price within a linear regression channel. Top=100%, Bottom=0%.
Parameters:
_top (float) : (float) The top (positive) deviation, corresponding to 100%.
_bot (float) : (float) The bottom (negative) deviation, corresponding to 0%.
_src (float) : (float) The source price.
Returns: (float) The percent position within the channel.
plotLinReg(_len, _y1, _y2, _slope, _devTop, _devBot, _scaleTypeLog, _lineWidth, _extendLines, _channelStyle, _colorFill, _colUpLine, _colDnLine, _colUpFill, _colDnFill)
Plots the linear regression line and its deviations, with configurable styles and fill.
Parameters:
_len (int) : (int) The lookback period for the linear regression.
_y1 (float) : (float) The starting y-value of the regression line.
_y2 (float) : (float) The ending y-value of the regression line.
_slope (float) : (float) The slope of the regression line (used to determine line color).
_devTop (float) : (float) The top deviation to add to the line.
_devBot (float) : (float) The bottom deviation to subtract from the line.
_scaleTypeLog (bool) : (bool) Use a log scale if true; otherwise, linear scale.
_lineWidth (int) : (int) The width of the plotted lines.
_extendLines (string) : (string) How lines should extend (none, left, right, both).
_channelStyle (string) : (string) The style of the channel lines (solid, dashed, dotted).
_colorFill (bool) : (bool) Whether to fill the space between the top and bottom deviation lines.
_colUpLine (color) : (color) Line color when slope is positive.
_colDnLine (color) : (color) Line color when slope is negative.
_colUpFill (color) : (color) Fill color when slope is positive.
_colDnFill (color) : (color) Fill color when slope is negative.
JsonAlertJsonAlert Library – Convert TradingView Alerts to JSON for Server Processing! 📡
🚀 The JsonAlert library makes it easy to send TradingView alerts as structured JSON to your server, allowing seamless integration with automated trading systems, databases, or webhook-based services.
📌 Features:
✅ Converts TradingView alert data into JSON format
✅ Supports custom key-value pairs for flexibility
✅ Allows frequency control (once per bar, once per bar close, every update)
✅ Easy to integrate with server-side PHP or other languages
Note that you have to pass one string array for keys and one string array for values , also you should pass alert frequency .
📖 Example Usage in Pine Script:
//@version=6
indicator("My script" , overlay = true)
import Penhan/JsonAlert/1 as alrt
if high > low
var array keys = array.from("ticker", "timeframe", "pattern")
var array values = array.from( syminfo.ticker , timeframe.period , str.tostring(123.45) )
alrt.alarm (keys, values , alert.freq_once_per_bar)
📡 Json Output Example:
{"ticker": "BTCUSDT","timeframe": "1","pattern": "123.45"}
🖥️ Server-Side PHP Example:
There you can integrate JsonAlert with your server in seconds! :)
Casa_SessionsLibrary "Casa_Sessions"
Advanced trading session management library that enhances TradingView's default functionality:
Key Features:
- Accurate session detection for futures markets
- Custom session hour definitions
- Drop-in replacements for standard TradingView session functions
- Flexible session map customization
- Full control over trading windows and market hours
Perfect for traders who need precise session timing, especially when working
with futures markets or custom trading schedules.
SetSessionTimes(session_type_input, custom_session_times_input, syminfo_type, syminfo_root, syminfo_timezone)
Parameters:
session_type_input (simple string) : Input string for session selection:
- 'Custom': User-defined session times
- 'FX-Tokyo': Tokyo forex session
- 'FX-London': London forex session
- 'FX-New York': NY forex session
- 'Overnight Session (ON)': After-hours trading
- 'Day Session (RTH)': Regular trading hours
custom_session_times_input (simple string) : Session parameter for custom time windows
Only used when session_type_input is 'Custom'
syminfo_type (simple string)
syminfo_root (simple string)
syminfo_timezone (simple string)
Returns:
session_times: Trading hours for selected session
session_timezone: Market timezone (relevant for forex)
getSessionMap()
Get futures trading session hours map
Keys are formatted as 'symbol:session', examples:
- 'ES:market' - Regular trading hours (RTH)
- 'ES:overnight' - Extended trading hours (ETH)
- 'NQ:market' - NASDAQ futures RTH
- 'CL:overnight' - Crude Oil futures ETH
Returns: Map
Key: Symbol:session identifier
Value: Session hours in format "HH:MM-HH:MM"
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
getSessionHigh(session, sessionMap)
Convenience function to return the session high. Necessary if you want to call this function from within a request.security expression where you can't return a tuple.
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: The high of the session
getSessionLow(session, sessionMap)
Convenience function to return the session low. Necessary if you want to call this function from within a request.security expression where you can't return a tuple.
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: The low of the session
DateTimeLibrary with enums that can be used as script inputs to allow users to set their preferred date and/or time formats. The user-selected formats can be passed to the library functions (which use 𝚜𝚝𝚛.𝚏𝚘𝚛𝚖𝚊𝚝_𝚝𝚒𝚖𝚎() under the hood) to get formatted date and time strings from a UNIX time.
PREFACE
The target audience of this publication is users creating their own indicators/strategies.
Sometimes a date and/or time needs to be displayed to the user. As a Pine Coder, it is natural to focus our initial attention on the primary calculations or functions of a script, which can lead to the display format of dates and times being an afterthought. While it may not be crucial for the main use case of a script, increased customizability can help push indicators/strategies to the next level in the eyes of the user.
The purpose of this library is to provide an easy-to-use mechanism for allowing script users to choose the formats of dates and times that are displayed to them. Not only is this helpful for users from around the world who may be accustomed to different date/time formats, but it also makes it easier for the script author because it offloads the date/time formatting decision from the author to the user.
HOW TO USE
Step 1
Import the library. Replace with the latest available version number for this library.
//@version=6
indicator("Example")
import n00btraders/DateTime/ as dt
Step 2
Select a date format and/or time format enum to be used as an input.
dateFormatInput = input.enum(dt.DateFormat.FORMAT_3, "Date format")
timeFormatInput = input.enum(dt.TimeFormat.TWENTY_FOUR_HOURS, "Time hours format")
Step 3
Pass the user's selection as the `format` parameter in the formatting functions from this library. The `timestamp` & `timezone` parameters can be any value that would otherwise be used in 𝚜𝚝𝚛.𝚏𝚘𝚛𝚖𝚊𝚝_𝚝𝚒𝚖𝚎(𝚝𝚒𝚖𝚎, 𝚏𝚘𝚛𝚖𝚊𝚝, 𝚝𝚒𝚖𝚎𝚣𝚘𝚗𝚎).
string formattedDate = dt.formatDate(timestamp, dateFormatInput, timezone)
string formattedTime = dt.formatTime(timestamp, timeFormatInput, timezone)
LIMITATIONS
The library's ease-of-use comes at a few costs:
Fixed date/time formats.
Using the library's pre-defined date & time formats means that additional custom formats cannot be utilized. For example, this library does not include seconds or fractional seconds in formatted time strings. If a script's use case requires displaying the 'seconds' from a time of day, then 𝚜𝚝𝚛.𝚏𝚘𝚛𝚖𝚊𝚝_𝚝𝚒𝚖𝚎() must be used directly.
Fixed time zone offset format.
The `formatTime()` function of this library can optionally add the time zone offset at the end of the time string, but the format of the offset cannot be specified. Note: if the default format for time zone offset is not sufficient, the Timezone library can be imported directly to get the time zone offset string in a preferred format.
ADVANTAGES
There are benefits to utilizing this library instead of directly using 𝚜𝚝𝚛.𝚏𝚘𝚛𝚖𝚊𝚝_𝚝𝚒𝚖𝚎():
Easy to use from the user's perspective.
The date & time format enums provide a similar look and feel to the "Date format" and "Time hours format" options that already exist in the TradingView chart settings.
Easy to use from the author's perspective.
The exported functions from this library are modeled to behave similarly to the 𝚜𝚝𝚛.𝚏𝚘𝚛𝚖𝚊𝚝_𝚝𝚒𝚖𝚎(𝚝𝚒𝚖𝚎, 𝚏𝚘𝚛𝚖𝚊𝚝, 𝚝𝚒𝚖𝚎𝚣𝚘𝚗𝚎) built-in function from Pine Script.
Format quarter of the year.
The date formatting function from this library can display a fiscal quarter if it's included in the user-selected format. This is currently not possible with the built-in 𝚜𝚝𝚛.𝚏𝚘𝚛𝚖𝚊𝚝_𝚝𝚒𝚖𝚎().
EXPORTED ENUM TYPES
This section will list the available date/time formats that can be used as a script input. Each enum type has a detailed //@𝚏𝚞𝚗𝚌𝚝𝚒𝚘𝚗 description in the source code to help determine the best choice for your scripts.
Date Format Enums:
𝙳𝚊𝚝𝚎𝙵𝚘𝚛𝚖𝚊𝚝
𝙳𝚊𝚝𝚎𝙵𝚘𝚛𝚖𝚊𝚝𝙳𝚊𝚢𝙾𝚏𝚆𝚎𝚎𝚔𝙰𝚋𝚋𝚛
𝙳𝚊𝚝𝚎𝙵𝚘𝚛𝚖𝚊𝚝𝙳𝚊𝚢𝙾𝚏𝚆𝚎𝚎𝚔𝙵𝚞𝚕𝚕
𝙲𝚞𝚜𝚝𝚘𝚖𝙳𝚊𝚝𝚎𝙵𝚘𝚛𝚖𝚊𝚝
Supporting Date Enums:
𝙳𝚊𝚝𝚎𝙿𝚛𝚎𝚏𝚒𝚡
Time Format Enums:
𝚃𝚒𝚖𝚎𝙵𝚘𝚛𝚖𝚊𝚝
Supporting Time Enums:
𝚃𝚒𝚖𝚎𝙰𝚋𝚋𝚛𝚎𝚟𝚒𝚊𝚝𝚒𝚘𝚗
𝚃𝚒𝚖𝚎𝚂𝚎𝚙𝚊𝚛𝚊𝚝𝚘𝚛
𝚃𝚒𝚖𝚎𝙿𝚘𝚜𝚝𝚏𝚒𝚡
Note: all exported enums have custom titles for each field. This means that the supporting enums could also be exposed to the end-user as script inputs if necessary. The supporting enums are used as optional parameters in this library's formatting functions to allow further customizability.
EXPORTED FUNCTIONS
formatDate(timestamp, format, timezone, prefix, trim)
Converts a UNIX time into a date string formatted according to the selected `format`.
Parameters:
timestamp (series int) : A UNIX time.
format (series DateFormat) : A date format.
timezone (series string) : A UTC/GMT offset or IANA time zone identifier.
prefix (series DatePrefix) : Optional day of week prefix.
trim (series bool) : Optional truncation of numeric month / day.
Returns: Calendar date string using the selected format.
⸻⸻⸻⸻⸻⸻⸻⸻
Required parameters: `timestamp`, `format`.
Note: there is a version of this function for each Date Format enum type. The only difference is the type of the `format` parameter.
Tip: hover over the `formatDate()` function in the Pine Editor to display useful details:
Function description
Parameter descriptions + default values
Example function usage
formatTime(timestamp, format, timezone, trim, separator, postfix, space, offset)
Converts a UNIX time into a formatted time string using the 24-hour clock or 12-hour clock.
Parameters:
timestamp (series int) : A UNIX time.
format (series TimeFormat) : A time format.
timezone (series string) : A UTC/GMT offset or IANA time zone identifier.
trim (series TimeAbbreviation) : Optional truncation of the hour and minute portion.
separator (series TimeSeparator) : Optional time separator.
postfix (series TimePostfix) : Optional format for the AM/PM postfix.
space (series bool) : Optional space between the time and the postfix.
offset (series bool) : Optional UTC offset as a suffix.
Returns: Time of day string using the selected format.
⸻⸻⸻⸻⸻⸻⸻⸻
Required parameters: `timestamp`, `format`.
Note: the `trim`, `postfix`, and `space` optional parameters are not applicable and will be ignored when using the 24-hour clock (`format` = TimeFormat.TWENTY_FOUR_HOURS).
Tip: hover over the `formatTime()` function in the Pine Editor to display useful details:
Function description
Parameter descriptions + default values
Example function usage
Example outputs for combinations of TimeFormat.* enum values & optional parameters
NOTES
This library can be used in conjunction with the Timezone library to increase the usability of scripts that can benefit from allowing the user to input their preferred time zone.
Credits to HoanGhetti for publishing an informative Markdown resource which I referenced to create the formatted function descriptions that pop up when hovering over `formatDate()` and `formatTime()` function calls in the Pine Editor.
dataTableUtilitiesLibrary "dataTableUtilities"
generate_dataTable(dataTable_map, title, tableYpos, tableXpos, textSize, includes_multiple_maps, include_comments)
: 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
textSize (string) : (string): Text size
includes_multiple_maps (bool)
include_comments (bool)
Returns: : None
generate_dataTable_multiple_columns(dataTable_map, title, tableYpos, tableXpos, textSize, includes_multiple_maps, total_columns)
: 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
textSize (string) : (string): Text size
includes_multiple_maps (bool)
total_columns (int)
Returns: : None
ootaLibrary "oota"
Collection of all custom and enhanced TA indicators - Object oriented methods implementation
method tr(c, useTrueRange)
returns true range of the candle
Namespace types: Candle
Parameters:
c (Candle) : Candle object containing ohlc data
useTrueRange (bool) : Use true range for atr calculation instead of just high/low difference
method ma(maType, length, source)
returns custom moving averages
Namespace types: simple CustomSeries
Parameters:
maType (simple CustomSeries) : Custom series type
length (simple int) : Moving Average Length
source (float) : Moving Average Source
Returns: moving average for the given type and length
method atr(maType, length, useTrueRange, c)
returns ATR with custom moving average
Namespace types: simple CustomSeries
Parameters:
maType (simple CustomSeries) : Custom series type
length (simple int) : Moving Average Length
useTrueRange (bool) : Use true range for atr calculation instead of just high/low difference
c (Candle) : Candle object containing ohlc
Returns: ATR for the given moving average type and length
method atrpercent(maType, length, useTrueRange, c)
returns ATR as percentage of close price
Namespace types: simple CustomSeries
Parameters:
maType (simple CustomSeries) : Custom series type
length (simple int) : Moving Average Length
useTrueRange (bool) : Use true range for atr calculation instead of just high/low difference
c (Candle) : Candle object containing ohlc
Returns: ATR as percentage of close price for the given moving average type and length
method bb(maType, length, multiplier, sticky, c)
returns Bollinger band for custom moving average
Namespace types: simple CustomSeries
Parameters:
maType (simple CustomSeries) : Custom series type
length (simple int) : Moving Average Length
multiplier (float) : Standard Deviation multiplier
sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
c (Candle) : Candle object containing ohlc
Returns: Bollinger band with custom moving average for given source, length and multiplier
method bbw(maType, length, multiplier, sticky, c)
returns Bollinger bandwidth for custom moving average
Namespace types: simple CustomSeries
Parameters:
maType (simple CustomSeries) : Custom series type
length (simple int) : Moving Average Length
multiplier (float) : Standard Deviation multiplier
sticky (simple bool) : sticky boundaries which will only change when value is outside boundary.
c (Candle) : Candle object containing ohlc
Returns: Bollinger Bandwidth for custom moving average for given source, length and multiplier
method bpercentb(maType, length, multiplier, sticky, c)
returns Bollinger Percent B for custom moving average
Namespace types: simple CustomSeries
Parameters:
maType (simple CustomSeries) : Custom series type
length (simple int) : Moving Average Length
multiplier (float) : Standard Deviation multiplier
sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
c (Candle) : Candle object containing ohlc
Returns: Bollinger Percent B for custom moving average for given source, length and multiplier
method kc(maType, length, multiplier, useTrueRange, sticky, c)
returns Keltner Channel for custom moving average
Namespace types: simple CustomSeries
Parameters:
maType (simple CustomSeries) : Custom series type
length (simple int) : Moving Average Length
multiplier (float) : Standard Deviation multiplier
useTrueRange (simple bool) : - if set to false, uses high-low.
sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
c (Candle) : Candle object containing ohlc
Returns: Keltner Channel for custom moving average for given souce, length and multiplier
method kcw(maType, length, multiplier, useTrueRange, sticky, c)
returns Keltner Channel Width with custom moving average
Namespace types: simple CustomSeries
Parameters:
maType (simple CustomSeries) : Custom series type
length (simple int) : Moving Average Length
multiplier (float) : Standard Deviation multiplier
useTrueRange (simple bool) : - if set to false, uses high-low.
sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
c (Candle) : Candle object containing ohlc
Returns: Keltner Channel Width for custom moving average
method kpercentk(maType, length, multiplier, useTrueRange, sticky, c)
returns Keltner Channel Percent K Width with custom moving average
Namespace types: simple CustomSeries
Parameters:
maType (simple CustomSeries) : Custom series type
length (simple int) : Moving Average Length
multiplier (float) : Standard Deviation multiplier
useTrueRange (simple bool) : - if set to false, uses high-low.
sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
c (Candle) : Candle object containing ohlc
Returns: Keltner Percent K for given moving average, source, length and multiplier
method dc(c, length, sticky)
returns Custom Donchian Channel
Namespace types: Candle
Parameters:
c (Candle) : Candle object containing ohlc
length (simple int) : - donchian channel length
sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
Returns: Donchian channel
method dcw(c, length, sticky)
returns Donchian Channel Width
Namespace types: Candle
Parameters:
c (Candle) : Candle object containing ohlc
length (simple int) : - donchian channel length
sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
Returns: Donchian channel width
method dpercentd(c, length, sticky)
returns Donchian Channel Percent of price
Namespace types: Candle
Parameters:
c (Candle) : Candle object containing ohlc
length (simple int) : - donchian channel length
sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
Returns: Donchian channel Percent D
method supertrend(maType, length, multiplier, useTrueRange, waitForClose, delayed, c)
supertrend Simple supertrend based on atr but also takes into consideration of custom MA Type, sources
Namespace types: simple CustomSeries
Parameters:
maType (simple CustomSeries) : Custom Series
length (simple int) : ATR Length
multiplier (simple float) : ATR Multiplier
useTrueRange (simple bool) : - if set to false, uses high-low.
waitForClose (simple bool) : : Considers source for direction change crossover if checked. Else, uses highSource and lowSource.
delayed (simple bool) : : if set to true lags supertrend atr stop based on target levels.
c (Candle) : Candle object containing ohlc
Returns: dir : Supertrend direction
supertrend : BuyStop if direction is 1 else SellStop
method oscillatorRange(seriesType, source, highlowLength, rangeLength, sticky)
oscillatorRange - returns Custom overbought/oversold areas for an oscillator input
Namespace types: simple CustomSeries
Parameters:
seriesType (simple CustomSeries) : - Custom series type
source (float) : - Osillator source such as RSI, COG etc.
highlowLength (simple int) : - length on which highlow of the oscillator is calculated
rangeLength (simple int) : - length used for calculating oversold/overbought range - usually same as oscillator length
sticky (simple bool) : - overbought, oversold levels won't change unless crossed
Returns: Dynamic overbought and oversold range for oscillator input
method oscillator(oscillatorType, length, shortLength, longLength, c)
oscillator - returns Choice of oscillator with custom overbought/oversold range
Namespace types: simple OscillatorType
Parameters:
oscillatorType (simple OscillatorType) : OscillatorType object
length (simple int) : - Oscillator length - not used for TSI
shortLength (simple int) : - shortLength only used for TSI
longLength (simple int) : - longLength only used for TSI
c (Candle) : Candle object containing ohlc
Returns: Oscillator value
method oscillatorWithRange(oscillatorType, length, shortLength, longLength, seriesType, highlowLength, sticky, c)
oscillatorWithRange - returns Choice of oscillator with custom overbought/oversold range
Namespace types: simple OscillatorType
Parameters:
oscillatorType (simple OscillatorType) : OscillatorType object
length (simple int) : - Oscillator length - not used for TSI
shortLength (simple int) : - shortLength only used for TSI
longLength (simple int) : - longLength only used for TSI
seriesType (simple CustomSeries) : - CustomSeries enum type
highlowLength (simple int) : - length on which highlow of the oscillator is calculated
sticky (simple bool) : - overbought, oversold levels won't change unless crossed
c (Candle) : Candle object containing ohlc
Returns: Oscillator value along with dynamic overbought and oversold range for oscillator input
Candle
Custom candle object
Fields:
o (series float) : open
h (series float) : high
l (series float) : low
c (series float) : close
barindex (series int) : bar_index
bartime (series int) : time
bartimeclose (series int) : time_close
v (series float) : volume
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, show_data_table, tableYpos, tableXpos, table_textSize, barsToRight, plot_labels, include_levels)
: 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
show_data_table (bool) : (bool): Activates and shows the data table
tableYpos (string)
tableXpos (string)
table_textSize (string)
barsToRight (int)
plot_labels (bool)
include_levels (bool)
Returns: : Returns three line objects that conform the regression channel, plus the optimal length and maximum r2
get_regressionChannel_data(max_length, min_length, source, stdDev_mult, plot_linearRegression, plot_labels, include_levels, barsToRight)
: Gets data for the linear regression channel
Parameters:
max_length (int) : (int): Maximum length for the linear regression.
min_length (int) : (int): Minimum length for the linear regression.
source (float) : (float): Source for the linear regression
stdDev_mult (float) : (float): Multiple for the standar deviations for the linear regression channel.
plot_linearRegression (bool)
plot_labels (bool)
include_levels (bool)
barsToRight (int)
Returns: : Returns a maps with the regression levels, the direction flag and the datatable map.
get_regressionChannel_data_v2(max_length, min_length, source, stdDev_mult, plot_linearRegression, plot_labels, include_levels, barsToRight)
Parameters:
max_length (int)
min_length (int)
source (float)
stdDev_mult (float)
plot_linearRegression (bool)
plot_labels (bool)
include_levels (bool)
barsToRight (int)
get_cuadratic_regression(x_array, y_array, bars_to_project, max_length)
: 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
max_length (int)
Returns: : Returns three line objects
rate_of_changeLibrary "rate_of_change"
// @description: Applies ROC algorithm to any pair of values.
// This library function is used to scale change of value (price, volume) to a percentage value, just as the ROC indicator would do. It is good practice to scale arbitrary ranges to set boundaries when you try to train statistical model.
rateOfChange(value, base, hardlimit)
This function is a helper to scale a value change to its percentage value.
Parameters:
value (float)
base (float)
hardlimit (int)
Returns: per: A float comprised between 0 and 100
real_time_candlesIntroduction
The Real-Time Candles Library provides comprehensive tools for creating, manipulating, and visualizing custom timeframe candles in Pine Script. Unlike standard indicators that only update at bar close, this library enables real-time visualization of price action and indicators within the current bar, offering traders unprecedented insight into market dynamics as they unfold.
This library addresses a fundamental limitation in traditional technical analysis: the inability to see how indicators evolve between bar closes. By implementing sophisticated real-time data processing techniques, traders can now observe indicator movements, divergences, and trend changes as they develop, potentially identifying trading opportunities much earlier than with conventional approaches.
Key Features
The library supports two primary candle generation approaches:
Chart-Time Candles: Generate real-time OHLC data for any variable (like RSI, MACD, etc.) while maintaining synchronization with chart bars.
Custom Timeframe (CTF) Candles: Create candles with custom time intervals or tick counts completely independent of the chart's native timeframe.
Both approaches support traditional candlestick and Heikin-Ashi visualization styles, with options for moving average overlays to smooth the data.
Configuration Requirements
For optimal performance with this library:
Set max_bars_back = 5000 in your script settings
When using CTF drawing functions, set max_lines_count = 500, max_boxes_count = 500, and max_labels_count = 500
These settings ensure that you will be able to draw correctly and will avoid any runtime errors.
Usage Examples
Basic Chart-Time Candle Visualization
// Create real-time candles for RSI
float rsi = ta.rsi(close, 14)
Candle rsi_candle = candle_series(rsi, CandleType.candlestick)
// Plot the candles using Pine's built-in function
plotcandle(rsi_candle.Open, rsi_candle.High, rsi_candle.Low, rsi_candle.Close,
"RSI Candles", rsi_candle.candle_color, rsi_candle.candle_color)
Multiple Access Patterns
The library provides three ways to access candle data, accommodating different programming styles:
// 1. Array-based access for collection operations
Candle candles = candle_array(source)
// 2. Object-oriented access for single entity manipulation
Candle candle = candle_series(source)
float value = candle.source(Source.HLC3)
// 3. Tuple-based access for functional programming styles
= candle_tuple(source)
Custom Timeframe Examples
// Create 20-second candles with EMA overlay
plot_ctf_candles(
source = close,
candle_type = CandleType.candlestick,
sample_type = SampleType.Time,
number_of_seconds = 20,
timezone = -5,
tied_open = true,
ema_period = 9,
enable_ema = true
)
// Create tick-based candles (new candle every 15 ticks)
plot_ctf_tick_candles(
source = close,
candle_type = CandleType.heikin_ashi,
number_of_ticks = 15,
timezone = -5,
tied_open = true
)
Advanced Usage with Custom Visualization
// Get custom timeframe candles without automatic plotting
CandleCTF my_candles = ctf_candles_array(
source = close,
candle_type = CandleType.candlestick,
sample_type = SampleType.Time,
number_of_seconds = 30
)
// Apply custom logic to the candles
float ema_values = my_candles.ctf_ema(14)
// Draw candles and EMA using time-based coordinates
my_candles.draw_ctf_candles_time()
ema_values.draw_ctf_line_time(line_color = #FF6D00)
Library Components
Data Types
Candle: Structure representing chart-time candles with OHLC, polarity, and visualization properties
CandleCTF: Extended candle structure with additional time metadata for custom timeframes
TickData: Structure for individual price updates with time deltas
Enumerations
CandleType: Specifies visualization style (candlestick or Heikin-Ashi)
Source: Defines price components for calculations (Open, High, Low, Close, HL2, etc.)
SampleType: Sets sampling method (Time-based or Tick-based)
Core Functions
get_tick(): Captures current price as a tick data point
candle_array(): Creates an array of candles from price updates
candle_series(): Provides a single candle based on latest data
candle_tuple(): Returns OHLC values as a tuple
ctf_candles_array(): Creates custom timeframe candles without rendering
Visualization Functions
source(): Extracts specific price components from candles
candle_ctf_to_float(): Converts candle data to float arrays
ctf_ema(): Calculates exponential moving averages for candle arrays
draw_ctf_candles_time(): Renders candles using time coordinates
draw_ctf_candles_index(): Renders candles using bar index coordinates
draw_ctf_line_time(): Renders lines using time coordinates
draw_ctf_line_index(): Renders lines using bar index coordinates
Technical Implementation Notes
This library leverages Pine Script's varip variables for state management, creating a sophisticated real-time data processing system. The implementation includes:
Efficient tick capturing: Samples price at every execution, maintaining temporal tracking with time deltas
Smart state management: Uses a hybrid approach with mutable updates at index 0 and historical preservation at index 1+
Temporal synchronization: Manages two time domains (chart time and custom timeframe)
The tooltip implementation provides crucial temporal context for custom timeframe visualizations, allowing users to understand exactly when each candle formed regardless of chart timeframe.
Limitations
Custom timeframe candles cannot be backtested due to Pine Script's limitations with historical tick data
Real-time visualization is only available during live chart updates
Maximum history is constrained by Pine Script's array size limits
Applications
Indicator visualization: See how RSI, MACD, or other indicators evolve in real-time
Volume analysis: Create custom volume profiles independent of chart timeframe
Scalping strategies: Identify short-term patterns with precisely defined time windows
Volatility measurement: Track price movement characteristics within bars
Custom signal generation: Create entry/exit signals based on custom timeframe patterns
Conclusion
The Real-Time Candles Library bridges the gap between traditional technical analysis (based on discrete OHLC bars) and the continuous nature of market movement. By making indicators more responsive to real-time price action, it gives traders a significant edge in timing and decision-making, particularly in fast-moving markets where waiting for bar close could mean missing important opportunities.
Whether you're building custom indicators, researching price patterns, or developing trading strategies, this library provides the foundation for sophisticated real-time analysis in Pine Script.
Implementation Details & Advanced Guide
Core Implementation Concepts
The Real-Time Candles Library implements a sophisticated event-driven architecture within Pine Script's constraints. At its heart, the library creates what's essentially a reactive programming framework handling continuous data streams.
Tick Processing System
The foundation of the library is the get_tick() function, which captures price updates as they occur:
export get_tick(series float source = close, series float na_replace = na)=>
varip float price = na
varip int series_index = -1
varip int old_time = 0
varip int new_time = na
varip float time_delta = 0
// ...
This function:
Samples the current price
Calculates time elapsed since last update
Maintains a sequential index to track updates
The resulting TickData structure serves as the fundamental building block for all candle generation.
State Management Architecture
The library employs a sophisticated state management system using varip variables, which persist across executions within the same bar. This creates a hybrid programming paradigm that's different from standard Pine Script's bar-by-bar model.
For chart-time candles, the core state transition logic is:
// Real-time update of current candle
candle_data := Candle.new(Open, High, Low, Close, polarity, series_index, candle_color)
candles.set(0, candle_data)
// When a new bar starts, preserve the previous candle
if clear_state
candles.insert(1, candle_data)
price.clear()
// Reset state for new candle
Open := Close
price.push(Open)
series_index += 1
This pattern of updating index 0 in real-time while inserting completed candles at index 1 creates an elegant solution for maintaining both current state and historical data.
Custom Timeframe Implementation
The custom timeframe system manages its own time boundaries independent of chart bars:
bool clear_state = switch settings.sample_type
SampleType.Ticks => cumulative_series_idx >= settings.number_of_ticks
SampleType.Time => cumulative_time_delta >= settings.number_of_seconds
This dual-clock system synchronizes two time domains:
Pine's execution clock (bar-by-bar processing)
The custom timeframe clock (tick or time-based)
The library carefully handles temporal discontinuities, ensuring candle formation remains accurate despite irregular tick arrival or market gaps.
Advanced Usage Techniques
1. Creating Custom Indicators with Real-Time Candles
To develop indicators that process real-time data within the current bar:
// Get real-time candles for your data
Candle rsi_candles = candle_array(ta.rsi(close, 14))
// Calculate indicator values based on candle properties
float signal = ta.ema(rsi_candles.first().source(Source.Close), 9)
// Detect patterns that occur within the bar
bool divergence = close > close and rsi_candles.first().Close < rsi_candles.get(1).Close
2. Working with Custom Timeframes and Plotting
For maximum flexibility when visualizing custom timeframe data:
// Create custom timeframe candles
CandleCTF volume_candles = ctf_candles_array(
source = volume,
candle_type = CandleType.candlestick,
sample_type = SampleType.Time,
number_of_seconds = 60
)
// Convert specific candle properties to float arrays
float volume_closes = volume_candles.candle_ctf_to_float(Source.Close)
// Calculate derived values
float volume_ema = volume_candles.ctf_ema(14)
// Create custom visualization
volume_candles.draw_ctf_candles_time()
volume_ema.draw_ctf_line_time(line_color = color.orange)
3. Creating Hybrid Timeframe Analysis
One powerful application is comparing indicators across multiple timeframes:
// Standard chart timeframe RSI
float chart_rsi = ta.rsi(close, 14)
// Custom 5-second timeframe RSI
CandleCTF ctf_candles = ctf_candles_array(
source = close,
candle_type = CandleType.candlestick,
sample_type = SampleType.Time,
number_of_seconds = 5
)
float fast_rsi_array = ctf_candles.candle_ctf_to_float(Source.Close)
float fast_rsi = fast_rsi_array.first()
// Generate signals based on divergence between timeframes
bool entry_signal = chart_rsi < 30 and fast_rsi > fast_rsi_array.get(1)
Final Notes
This library represents an advanced implementation of real-time data processing within Pine Script's constraints. By creating a reactive programming framework for handling continuous data streams, it enables sophisticated analysis typically only available in dedicated trading platforms.
The design principles employed—including state management, temporal processing, and object-oriented architecture—can serve as patterns for other advanced Pine Script development beyond this specific application.
------------------------
Library "real_time_candles"
A comprehensive library for creating real-time candles with customizable timeframes and sampling methods.
Supports both chart-time and custom-time candles with options for candlestick and Heikin-Ashi visualization.
Allows for tick-based or time-based sampling with moving average overlay capabilities.
get_tick(source, na_replace)
Captures the current price as a tick data point
Parameters:
source (float) : Optional - Price source to sample (defaults to close)
na_replace (float) : Optional - Value to use when source is na
Returns: TickData structure containing price, time since last update, and sequential index
candle_array(source, candle_type, sync_start, bullish_color, bearish_color)
Creates an array of candles based on price updates
Parameters:
source (float) : Optional - Price source to sample (defaults to close)
candle_type (simple CandleType) : Optional - Type of candle chart to create (candlestick or Heikin-Ashi)
sync_start (simple bool) : Optional - Whether to synchronize with the start of a new bar
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
Returns: Array of Candle objects ordered with most recent at index 0
candle_series(source, candle_type, wait_for_sync, bullish_color, bearish_color)
Provides a single candle based on the latest price data
Parameters:
source (float) : Optional - Price source to sample (defaults to close)
candle_type (simple CandleType) : Optional - Type of candle chart to create (candlestick or Heikin-Ashi)
wait_for_sync (simple bool) : Optional - Whether to wait for a new bar before starting
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
Returns: A single Candle object representing the current state
candle_tuple(source, candle_type, wait_for_sync, bullish_color, bearish_color)
Provides candle data as a tuple of OHLC values
Parameters:
source (float) : Optional - Price source to sample (defaults to close)
candle_type (simple CandleType) : Optional - Type of candle chart to create (candlestick or Heikin-Ashi)
wait_for_sync (simple bool) : Optional - Whether to wait for a new bar before starting
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
Returns: Tuple representing current candle values
method source(self, source, na_replace)
Extracts a specific price component from a Candle
Namespace types: Candle
Parameters:
self (Candle)
source (series Source) : Type of price data to extract (Open, High, Low, Close, or composite values)
na_replace (float) : Optional - Value to use when source value is na
Returns: The requested price value from the candle
method source(self, source)
Extracts a specific price component from a CandleCTF
Namespace types: CandleCTF
Parameters:
self (CandleCTF)
source (simple Source) : Type of price data to extract (Open, High, Low, Close, or composite values)
Returns: The requested price value from the candle as a varip
method candle_ctf_to_float(self, source)
Converts a specific price component from each CandleCTF to a float array
Namespace types: array
Parameters:
self (array)
source (simple Source) : Optional - Type of price data to extract (defaults to Close)
Returns: Array of float values extracted from the candles, ordered with most recent at index 0
method ctf_ema(self, ema_period)
Calculates an Exponential Moving Average for a CandleCTF array
Namespace types: array
Parameters:
self (array)
ema_period (simple float) : Period for the EMA calculation
Returns: Array of float values representing the EMA of the candle data, ordered with most recent at index 0
method draw_ctf_candles_time(self, sample_type, number_of_ticks, number_of_seconds, timezone)
Renders custom timeframe candles using bar time coordinates
Namespace types: array
Parameters:
self (array)
sample_type (simple SampleType) : Optional - Method for sampling data (Time or Ticks), used for tooltips
number_of_ticks (simple int) : Optional - Number of ticks per candle (used when sample_type is Ticks), used for tooltips
number_of_seconds (simple float) : Optional - Time duration per candle in seconds (used when sample_type is Time), used for tooltips
timezone (simple int) : Optional - Timezone offset from UTC (-12 to +12), used for tooltips
Returns: void - Renders candles on the chart using time-based x-coordinates
method draw_ctf_candles_index(self, sample_type, number_of_ticks, number_of_seconds, timezone)
Renders custom timeframe candles using bar index coordinates
Namespace types: array
Parameters:
self (array)
sample_type (simple SampleType) : Optional - Method for sampling data (Time or Ticks), used for tooltips
number_of_ticks (simple int) : Optional - Number of ticks per candle (used when sample_type is Ticks), used for tooltips
number_of_seconds (simple float) : Optional - Time duration per candle in seconds (used when sample_type is Time), used for tooltips
timezone (simple int) : Optional - Timezone offset from UTC (-12 to +12), used for tooltips
Returns: void - Renders candles on the chart using index-based x-coordinates
method draw_ctf_line_time(self, source, line_size, line_color)
Renders a line representing a price component from the candles using time coordinates
Namespace types: array
Parameters:
self (array)
source (simple Source) : Optional - Type of price data to extract (defaults to Close)
line_size (simple int) : Optional - Width of the line
line_color (simple color) : Optional - Color of the line
Returns: void - Renders a connected line on the chart using time-based x-coordinates
method draw_ctf_line_time(self, line_size, line_color)
Renders a line from a varip float array using time coordinates
Namespace types: array
Parameters:
self (array)
line_size (simple int) : Optional - Width of the line, defaults to 2
line_color (simple color) : Optional - Color of the line
Returns: void - Renders a connected line on the chart using time-based x-coordinates
method draw_ctf_line_index(self, source, line_size, line_color)
Renders a line representing a price component from the candles using index coordinates
Namespace types: array
Parameters:
self (array)
source (simple Source) : Optional - Type of price data to extract (defaults to Close)
line_size (simple int) : Optional - Width of the line
line_color (simple color) : Optional - Color of the line
Returns: void - Renders a connected line on the chart using index-based x-coordinates
method draw_ctf_line_index(self, line_size, line_color)
Renders a line from a varip float array using index coordinates
Namespace types: array
Parameters:
self (array)
line_size (simple int) : Optional - Width of the line, defaults to 2
line_color (simple color) : Optional - Color of the line
Returns: void - Renders a connected line on the chart using index-based x-coordinates
plot_ctf_tick_candles(source, candle_type, number_of_ticks, timezone, tied_open, ema_period, bullish_color, bearish_color, line_width, ema_color, use_time_indexing)
Plots tick-based candles with moving average
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Type of candle chart to display
number_of_ticks (simple int) : Number of ticks per candle
timezone (simple int) : Timezone offset from UTC (-12 to +12)
tied_open (simple bool) : Whether to tie open price to close of previous candle
ema_period (simple float) : Period for the exponential moving average
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
line_width (simple int) : Optional - Width of the moving average line, defaults to 2
ema_color (color) : Optional - Color of the moving average line
use_time_indexing (simple bool) : Optional - When true the function will plot with xloc.time, when false it will plot using xloc.bar_index
Returns: void - Creates visual candle chart with EMA overlay
plot_ctf_tick_candles(source, candle_type, number_of_ticks, timezone, tied_open, bullish_color, bearish_color, use_time_indexing)
Plots tick-based candles without moving average
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Type of candle chart to display
number_of_ticks (simple int) : Number of ticks per candle
timezone (simple int) : Timezone offset from UTC (-12 to +12)
tied_open (simple bool) : Whether to tie open price to close of previous candle
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
use_time_indexing (simple bool) : Optional - When true the function will plot with xloc.time, when false it will plot using xloc.bar_index
Returns: void - Creates visual candle chart without moving average
plot_ctf_time_candles(source, candle_type, number_of_seconds, timezone, tied_open, ema_period, bullish_color, bearish_color, line_width, ema_color, use_time_indexing)
Plots time-based candles with moving average
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Type of candle chart to display
number_of_seconds (simple float) : Time duration per candle in seconds
timezone (simple int) : Timezone offset from UTC (-12 to +12)
tied_open (simple bool) : Whether to tie open price to close of previous candle
ema_period (simple float) : Period for the exponential moving average
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
line_width (simple int) : Optional - Width of the moving average line, defaults to 2
ema_color (color) : Optional - Color of the moving average line
use_time_indexing (simple bool) : Optional - When true the function will plot with xloc.time, when false it will plot using xloc.bar_index
Returns: void - Creates visual candle chart with EMA overlay
plot_ctf_time_candles(source, candle_type, number_of_seconds, timezone, tied_open, bullish_color, bearish_color, use_time_indexing)
Plots time-based candles without moving average
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Type of candle chart to display
number_of_seconds (simple float) : Time duration per candle in seconds
timezone (simple int) : Timezone offset from UTC (-12 to +12)
tied_open (simple bool) : Whether to tie open price to close of previous candle
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
use_time_indexing (simple bool) : Optional - When true the function will plot with xloc.time, when false it will plot using xloc.bar_index
Returns: void - Creates visual candle chart without moving average
plot_ctf_candles(source, candle_type, sample_type, number_of_ticks, number_of_seconds, timezone, tied_open, ema_period, bullish_color, bearish_color, enable_ema, line_width, ema_color, use_time_indexing)
Unified function for plotting candles with comprehensive options
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Optional - Type of candle chart to display
sample_type (simple SampleType) : Optional - Method for sampling data (Time or Ticks)
number_of_ticks (simple int) : Optional - Number of ticks per candle (used when sample_type is Ticks)
number_of_seconds (simple float) : Optional - Time duration per candle in seconds (used when sample_type is Time)
timezone (simple int) : Optional - Timezone offset from UTC (-12 to +12)
tied_open (simple bool) : Optional - Whether to tie open price to close of previous candle
ema_period (simple float) : Optional - Period for the exponential moving average
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
enable_ema (bool) : Optional - Whether to display the EMA overlay
line_width (simple int) : Optional - Width of the moving average line, defaults to 2
ema_color (color) : Optional - Color of the moving average line
use_time_indexing (simple bool) : Optional - When true the function will plot with xloc.time, when false it will plot using xloc.bar_index
Returns: void - Creates visual candle chart with optional EMA overlay
ctf_candles_array(source, candle_type, sample_type, number_of_ticks, number_of_seconds, tied_open, bullish_color, bearish_color)
Creates an array of custom timeframe candles without rendering them
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Type of candle chart to create (candlestick or Heikin-Ashi)
sample_type (simple SampleType) : Method for sampling data (Time or Ticks)
number_of_ticks (simple int) : Optional - Number of ticks per candle (used when sample_type is Ticks)
number_of_seconds (simple float) : Optional - Time duration per candle in seconds (used when sample_type is Time)
tied_open (simple bool) : Optional - Whether to tie open price to close of previous candle
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
Returns: Array of CandleCTF objects ordered with most recent at index 0
Candle
Structure representing a complete candle with price data and display properties
Fields:
Open (series float) : Opening price of the candle
High (series float) : Highest price of the candle
Low (series float) : Lowest price of the candle
Close (series float) : Closing price of the candle
polarity (series bool) : Boolean indicating if candle is bullish (true) or bearish (false)
series_index (series int) : Sequential index identifying the candle in the series
candle_color (series color) : Color to use when rendering the candle
ready (series bool) : Boolean indicating if candle data is valid and ready for use
TickData
Structure for storing individual price updates
Fields:
price (series float) : The price value at this tick
time_delta (series float) : Time elapsed since the previous tick in milliseconds
series_index (series int) : Sequential index identifying this tick
CandleCTF
Structure representing a custom timeframe candle with additional time metadata
Fields:
Open (series float) : Opening price of the candle
High (series float) : Highest price of the candle
Low (series float) : Lowest price of the candle
Close (series float) : Closing price of the candle
polarity (series bool) : Boolean indicating if candle is bullish (true) or bearish (false)
series_index (series int) : Sequential index identifying the candle in the series
open_time (series int) : Timestamp marking when the candle was opened (in Unix time)
time_delta (series float) : Duration of the candle in milliseconds
candle_color (series color) : Color to use when rendering the candle
MonthlyReturnTableLibrary "MonthlyReturnTable"
TODO: The table displays monthly returns, profits, MDD, and number of trades.
get_table(mode, tablePosition, precision, textSize, marginTop, marginBottom, marginLeft, marginRight, colorHead, colorBull, colorBear, colorZero)
: get_table
Parameters:
mode (string)
tablePosition (string)
precision (int)
textSize (int)
marginTop (int)
marginBottom (int)
marginLeft (int)
marginRight (int)
colorHead (color)
colorBull (color)
colorBear (color)
colorZero (color)
Returns: : null, plot perfTable
UtilLibrary "Util"
defines commonly used utility functions and constants
calc_shares(entry_price, stop, fund, riskPerc)
Calculate number of shares for a trade
Parameters:
entry_price (float)
stop (float) : stop loss price
fund (float) : amount of fund to put in this trade
riskPerc (float) : percentage of fund to be risked in this trade. Default is 5%
Returns: number of shares
trade_exist(trade_id)
Returns if a trade with the specific ID is already open
Parameters:
trade_id (string)
Returns: true/false
trade
Fields:
id (series string)
direction (series TradeDir)
entry_price (series float)
shares (series float)
bars_open (series int)
TimezoneLibrary with pre-defined timezone enums that can be used to request a timezone input from the user. The library provides a `tostring()` function to convert enum values to a valid string that can be used as a `timezone` parameter in pine script built-in functions. The library also includes a bonus function to get a formatted UTC offset from a UNIX timestamp.
The timezone enums in this library were compiled by referencing the available timezone options from TradingView chart settings as well as multiple Wikipedia articles relating to lists of time zones.
Some enums from this library are used to retrieve an IANA time zone identifier, while other enums only use UTC/GMT offset notation. It is important to note that the Pine Script User Manual recommends using IANA notation in most cases.
HOW TO USE
This library is intended to be used by Pine Coders who wish to provide their users with a simple way to input a timezone. Using this library is as easy as 1, 2, 3:
Step 1
Import the library into your script. Replace with the latest available version number for this library.
//@version=6
indicator("Example")
import n00btraders/Timezone/ as tz
Step 2
Select one of the available enums from the library and use it as an input. Tip: view the library source code and scroll through the enums at the top to find the best choice for your script.
timezoneInput = input.enum(tz.TimezoneID.EXCHANGE, "Timezone")
Step 3
Convert the user-selected input into a valid string that can be used in one of the pine script built-in functions that have a `timezone` parameter.
string timezone = tz.tostring(timezoneInput)
EXPORTED FUNCTIONS
There are multiple 𝚝𝚘𝚜𝚝𝚛𝚒𝚗𝚐() functions in this library: one for each timezone enum. The function takes a single parameter: any enum field from one of the available timezone enums that are exported by this library. Depending on the selected enum, the function will return a time zone string in either UTC/GMT notation or IANA notation.
Note: to avoid confusion with the built-in `str.tostring()` function, it is recommended to use this library's `tostring()` as a method rather than a function:
string timezone = timezoneInput.tostring()
offset(timestamp, format, timezone, prefix, colon)
Formats the time offset from a UNIX timestamp represented in a specified timezone.
Namespace types: series OffsetFormat
Parameters:
timestamp (int) : (series int) A UNIX time.
format (series OffsetFormat) : (series OffsetFormat) A time offset format.
timezone (string) : (series string) A UTC/GMT offset or IANA time zone identifier.
prefix (string) : (series string) Optional 'UTC' or 'GMT' prefix for the result.
colon (bool) : (series bool) Optional usage of colon separator.
Returns: Time zone offset using the selected format.
The 𝚘𝚏𝚏𝚜𝚎𝚝() function is provided as a convenient alternative to manually using `str.format_time()` and then manipulating the result.
The OffsetFormat enum is used to decide the format of the result from the `offset()` function. The library source code contains comments above this enum declaration that describe how each enum field will modify a time offset.
Tip: hover over the `offset()` function call in the Pine Editor to display a pop-up containing:
Function description
Detailed parameter list, including default values
Example function calls
Example outputs for different OffsetFormat.* enum values
NOTES
At the time of this publication, Pine cannot be used to access a chart's selected time zone. Therefore, the main benefit of this library is to provide a quick and easy way to create a pine script input for a time zone (most commonly, the same time zone selected in the user's chart settings).
At the time of the creation of this library, there are 95 Time Zones made available in the TradingView chart settings. If any changes are made to the time zone settings, this library will be updated to match the new changes.
All time zone enums (and their individual fields) in this library were manually verified and tested to ensure correctness.
An example usage of this library is included at the bottom of the source code.
Credits to HoanGhetti for providing a nice Markdown resource which I referenced to be able to create a formatted informational pop-up for this library's `offset()` function.
merge_pinbar_babyblueLibrary "merge_pinbar_babyblue"
merge_pinbar: merge bars and check whether the bar is a pinbar
merge_pinbar_babyblue(period, max_bars)
merge_pinbar: merge bars and check whether the bar is a pinbar
Parameters:
period (simple int)
max_bars (simple int)
Returns: array:
TimeframeUtilsLibrary "TimeframeUtils"
Timeframe Utilities Library – Provides functions to convert timeframe resolutions to minutes and generate human‐readable timeframe text.
tfResInMinutes(_res)
tfResInMinutes
Parameters:
_res (string)
Returns: float - The specified timeframe's resolution in minutes.
getTimeFrameText(_tf)
getTimeFrameText
Parameters:
_tf (string)
Returns: string - A human-readable representation of the specified timeframe.
TickerLibLibrary "TickerLib"
Ticker Library
exists(tickerId)
Test if a tickerId exists
Parameters:
tickerId (string)
Returns: (bool)
notExist(tickerId)
Test if a tickerId do not exists
Parameters:
tickerId (string)
Returns: (bool)
getExchange(tickerId)
Pass a tickerId return the exchange
Parameters:
tickerId (string)
Returns: (string) exchange
isPerp(tickerId)
Test if tickerId is a perps pair
Parameters:
tickerId (string)
Returns: (bool)
isNotPerp(tickerId)
Test if tickerId is not a perps pair
Parameters:
tickerId (string)
Returns: (bool)
getPair(tickerId)
Pass a tickerId return the pair without exchange
Parameters:
tickerId (string)
Returns: (string) the pair
getSpotPair(tickerId)
Pass a tickerId return the pair without exchange and perps
Parameters:
tickerId (string)
Returns: (string) the pair
rzigzagLibrary "rzigzag"
Recursive Zigzag Using Matrix allows to create zigzags recursively on multiple levels. This is an old library converted to V6
zigzag(length, ohlc, numberOfPivots, offset)
calculates plain zigzag based on input
Parameters:
length (int) : Zigzag Length
ohlc (array) : Array containing ohlc values. Can also contain custom series
numberOfPivots (simple int) : Number of max pivots to be returned
offset (simple int) : Offset from current bar. Can be used for calculations based on confirmed bars
Returns: [matrix zigzagmatrix, bool flags]
iZigzag(length, h, l, numberOfPivots)
calculates plain zigzag based on input array
Parameters:
length (int) : Zigzag Length
h (array) : array containing high values of a series
l (array) : array containing low values of a series
numberOfPivots (simple int) : Number of max pivots to be returned
Returns: matrix zigzagmatrix
nextlevel(zigzagmatrix, numberOfPivots)
calculates next level zigzag based on present zigzag coordinates
Parameters:
zigzagmatrix (matrix) : Matrix containing zigzag pivots, bars, bar time, direction and level
numberOfPivots (simple int) : Number of max pivots to be returned
Returns: matrix zigzagmatrix
draw(zigzagmatrix, flags, lineColor, lineWidth, lineStyle, showLabel, xloc)
draws zigzag based on the zigzagmatrix input
Parameters:
zigzagmatrix (matrix) : Matrix containing zigzag pivots, bars, bar time, direction and level
flags (array) : Zigzag pivot flags
lineColor (color) : Zigzag line color
lineWidth (int) : Zigzag line width
lineStyle (string) : Zigzag line style
showLabel (bool) : Flag to indicate display pivot labels
xloc (string) : xloc preference for drawing lines/labels
Returns:
draw(length, ohlc, numberOfPivots, offset, lineColor, lineWidth, lineStyle, showLabel, xloc)
calculates and draws zigzag based on zigzag length and source input
Parameters:
length (int) : Zigzag Length
ohlc (array) : Array containing ohlc values. Can also contain custom series
numberOfPivots (simple int) : Number of max pivots to be returned
offset (simple int) : Offset from current bar. Can be used for calculations based on confirmed bars
lineColor (color) : Zigzag line color
lineWidth (int) : Zigzag line width
lineStyle (string) : Zigzag line style
showLabel (bool) : Flag to indicate display pivot labels
xloc (string) : xloc preference for drawing lines/labels
Returns: [matrix zigzagmatrix, array zigzaglines, array zigzaglabels, bool flags]
drawfresh(zigzagmatrix, zigzaglines, zigzaglabels, lineColor, lineWidth, lineStyle, showLabel, xloc)
draws fresh zigzag for all pivots in the input matrix.
Parameters:
zigzagmatrix (matrix) : Matrix containing zigzag pivots, bars, bar time, direction and level
zigzaglines (array) : array to which all newly created lines will be added
zigzaglabels (array) : array to which all newly created lables will be added
lineColor (color) : Zigzag line color
lineWidth (int) : Zigzag line width
lineStyle (string) : Zigzag line style
showLabel (bool) : Flag to indicate display pivot labels
xloc (string) : xloc preference for drawing lines/labels
Returns:
_matrixLibrary "_matrix"
Library helps visualize matrix as array of arrays and enables users to use array methods such as push, pop, shift, unshift etc along with cleanup activities on drawing objects wherever required
method delete(mtx, rowNumber)
deletes row from a matrix
Namespace types: matrix
Parameters:
mtx (matrix) : matrix of objects
rowNumber (int) : row index to be deleted
Returns: void
method delete(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method delete(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method delete(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method delete(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method delete(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method delete(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method delete(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method delete(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method delete(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method remove(mtx, rowNumber)
remove row from a matrix and returns them to caller
Namespace types: matrix
Parameters:
mtx (matrix) : matrix of objects
rowNumber (int) : row index to be deleted
Returns: type
method remove(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method remove(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method remove(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method remove(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method remove(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method remove(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method remove(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method remove(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method remove(mtx, rowNumber)
Namespace types: matrix
Parameters:
mtx (matrix)
rowNumber (int)
method unshift(mtx, row, maxItems)
unshift array of lines to first row of the matrix
Namespace types: matrix
Parameters:
mtx (matrix) : matrix of lines
row (array) : array of lines to be inserted in row
maxItems (simple int)
Returns: resulting matrix of type
method unshift(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method unshift(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method unshift(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method unshift(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method unshift(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method unshift(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method unshift(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method unshift(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method unshift(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method push(mtx, row, maxItems)
push array of lines to end of the matrix row
Namespace types: matrix
Parameters:
mtx (matrix) : matrix of lines
row (array) : array of lines to be inserted in row
maxItems (simple int)
Returns: resulting matrix of lines
method push(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method push(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method push(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method push(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method push(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method push(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method push(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method push(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method push(mtx, row, maxItems)
Namespace types: matrix
Parameters:
mtx (matrix)
row (array)
maxItems (simple int)
method shift(mtx)
shift removes first row from matrix of lines
Namespace types: matrix
Parameters:
mtx (matrix) : matrix of lines from which the shift operation need to be performed
Returns: void
method shift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method shift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method shift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method shift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method shift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method shift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method shift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method shift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method shift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rshift(mtx)
rshift removes first row from matrix of lines and returns them as array
Namespace types: matrix
Parameters:
mtx (matrix) : matrix of lines from which the rshift operation need to be performed
Returns: type
method rshift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rshift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rshift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rshift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rshift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rshift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rshift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rshift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rshift(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method pop(mtx)
pop removes last row from matrix of lines
Namespace types: matrix
Parameters:
mtx (matrix) : matrix of lines from which the pop operation need to be performed
Returns: void
method pop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method pop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method pop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method pop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method pop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method pop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method pop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method pop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method pop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rpop(mtx)
rpop removes last row from matrix of lines and reutnrs the array to caller
Namespace types: matrix
Parameters:
mtx (matrix) : matrix of lines from which the rpop operation need to be performed
Returns: void
method rpop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rpop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rpop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rpop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rpop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rpop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rpop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rpop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method rpop(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method clear(mtx)
clear clears the matrix
Namespace types: matrix
Parameters:
mtx (matrix) : matrix of lines which needs to be cleared
Returns: void
method clear(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method clear(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method clear(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method clear(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method clear(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method clear(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method clear(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method clear(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method clear(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method flush(mtx)
clear clears the matrix but retains the drawing objects
Namespace types: matrix
Parameters:
mtx (matrix) : matrix of lines which needs to be cleared
Returns: void
method flush(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method flush(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method flush(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method flush(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method flush(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method flush(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method flush(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method flush(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
method flush(mtx)
Namespace types: matrix
Parameters:
mtx (matrix)
TALibrary "TA"
Technical analysis library that provides convenience functions and overrides for tradingview's own ta.* functions in order to work around various limitations.
sma(src, length)
Override for ta.sma that allows you to provide series values
Parameters:
src (float) : The source values to process
length (int) : The length of the source to evaluate for the moving average
Returns: float The moving average
ema(src, length)
Override for ta.ema that allows you to provide series values
Parameters:
src (float) : The source values to process
length (int) : The length of the source to evaluate for the moving average
Returns: float The moving average
rma(src, length)
Override for ta.rma that allows you to provide series values
Parameters:
src (float) : The source values to process
length (int) : The length of the source to evaluate for the moving average
Returns: float The moving average
wma(src, length)
Override for ta.wma that allows you to provide series values
Parameters:
src (float) : The source values to process
length (int) : The length of the source to evaluate for the moving average
Returns: float The moving average
vwma(src, length)
Override for ta.vwma that allows you to provide series values
Parameters:
src (float) : The source values to process
length (int) : The length of the source to evaluate for the moving average
Returns: float The moving average
ma(src, length, maType)
Provide the requested moving average
Parameters:
src (float) : The source values to process
length (int) : The length of the source to evaluate for the moving average
maType (string) : The type of moving average to return: SMA (default), EMA, SMMA (RMA), WMA, VWMA
Returns: float The moving average
alert_formatLibrary "alert_format"
library to call alert with parameters specified
alert_format(message, param_names, param_values, params_format, freq)
alert with named parameters message
Parameters:
message (string) : message header that prefixes named parameters
param_names (array) : names for parameters specified in param_values
param_values (array) : values for parameters specified in param_names
params_format (string) : format for all param values, 2 decimals by default
freq (string) : Determines the allowed frequency of the alert trigger (see alert). alert.freq_once_per_bar_close by default
Cometreon_Public📚 Cometreon Public Library – Advanced Functions for Pine Script
This library contains advanced functions used in my public indicators on TradingView. The goal is to make the code more modular and efficient, allowing users to call pre-built functions for complex calculations without rewriting them from scratch.
🔹 Currently Available Functions:
1️⃣ Moving Average Function – Provides multiple types of moving averages to choose from, including:
SMA (Simple Moving Average)
EMA (Exponential Moving Average)
WMA (Weighted Moving Average)
RMA (Smoothed Moving Average)
HMA (Hull Moving Average)
JMA (Jurik Moving Average)
DEMA (Double Exponential Moving Average)
TEMA (Triple Exponential Moving Average)
LSMA (Least Squares Moving Average)
VWMA (Volume-Weighted Moving Average)
SMMA (Smoothed Moving Average)
KAMA (Kaufman’s Adaptive Moving Average)
ALMA (Arnaud Legoux Moving Average)
FRAMA (Fractal Adaptive Moving Average)
VIDYA (Variable Index Dynamic Average)
2️⃣ Custom RSI – Uses the Moving Average function to modify the calculation method, with an additional option for a dynamic version.
3️⃣ Custom MACD – Uses the Moving Average function to modify the calculation method, with an additional option for a dynamic version.
4️⃣ Custom Alligator – Uses the Moving Average function to modify generic calculations, allowing users to change the calculation method.
TCTDailyBiasLibraryLibrary "TCTDailyBiasLibrary"
Provides a simple function to return a daily bias based on the break of the morning range
getDailyBias()
Returns the daily bias based on the break of the morning range
Returns: bias
Casa_VolumeProfileSessionLibrary "Casa_VolumeProfileSession"
Analyzes price and volume during regular trading hours to provide a session volume profile,
including Point of Control (POC), Value Area High (VAH), and Value Area Low (VAL).
Calculates and displays these levels historically and for the developing session.
Offers customizable visualization options for the Value Area, POC, histogram, and labels.
Uses lower timeframe data for increased accuracy and supports futures sessions.
The number of rows used for the volume profile can be fixed or dynamically calculated based on the session's price range and the instrument's minimum tick increment, providing optimal resolution.
calculateEffectiveRows(configuredRows, dayHigh, dayLow)
Determines the optimal number of rows for the volume profile, either using the configured value or calculating dynamically based on price range and tick size
Parameters:
configuredRows (int) : User-specified number of rows (0 means auto-calculate)
dayHigh (float) : Highest price of the session
dayLow (float) : Lowest price of the session
Returns: The number of rows to use for the volume profile
debug(vp, position)
Helper function to write some information about the supplied SVP object to the screen in a table.
Parameters:
vp (Object) : The SVP object to debug
position (string) : The position.* to place the table. Defaults to position.bottom_center
getLowerTimeframe()
Depending on the timeframe of the chart, determines a lower timeframe to grab volume data from for the analysis
Returns: The timeframe string to fetch volume for
get(volumeProfile, lowerTimeframeHigh, lowerTimeframeLow, lowerTimeframeVolume, lowerTimeframeTime, lowerTimeframeSessionIsMarket)
Populated the provided SessionVolumeProfile object with vp data on the session.
Parameters:
volumeProfile (Object) : The SessionVolumeProfile object to populate
lowerTimeframeHigh (array) : The lower timeframe high values
lowerTimeframeLow (array) : The lower timeframe low values
lowerTimeframeVolume (array) : The lower timeframe volume values
lowerTimeframeTime (array) : The lower timeframe time values
lowerTimeframeSessionIsMarket (array) : The lower timeframe session.ismarket values (that are futures-friendly)
drawPriorValueAreas(todaySessionVolumeProfile, extendYesterdayOverToday, showLabels, labelSize, pocColor, pocStyle, pocWidth, vahlColor, vahlStyle, vahlWidth, vaColor)
Given a SessionVolumeProfile Object, will render the historical value areas for that object.
Parameters:
todaySessionVolumeProfile (Object) : The SessionVolumeProfile Object to draw
extendYesterdayOverToday (bool) : Defaults to true
showLabels (bool) : Defaults to true
labelSize (string) : Defaults to size.small
pocColor (color) : Defaults to #e500a4
pocStyle (string) : Defaults to line.style_solid
pocWidth (int) : Defaults to 1
vahlColor (color) : The color of the value area high/low lines. Defaults to #1592e6
vahlStyle (string) : The style of the value area high/low lines. Defaults to line.style_solid
vahlWidth (int) : The width of the value area high/low lines. Defaults to 1
vaColor (color) : The color of the value area background. Defaults to #00bbf911)
drawHistogram(volumeProfile, bgColor, showVolumeOnHistogram)
Given a SessionVolumeProfile object, will render the histogram for that object.
Parameters:
volumeProfile (Object) : The SessionVolumeProfile object to draw
bgColor (color) : The baseline color to use for the histogram. Defaults to #00bbf9
showVolumeOnHistogram (bool) : Show the volume amount on the histogram bars. Defaults to false.
Object
Object Contains all settings and calculated values for a Volume Profile Session analysis
Fields:
numberOfRows (series int) : Number of price levels to divide the range into. If set to 0, auto-calculates based on price range and tick size
valueAreaCoverage (series int) : Percentage of total volume to include in the Value Area (default 70%)
trackDevelopingVa (series bool) : Whether to calculate and display the Value Area as it develops during the session
valueAreaHigh (series float) : Upper boundary of the Value Area - price level containing specified % of volume
pointOfControl (series float) : Price level with the highest volume concentration
valueAreaLow (series float) : Lower boundary of the Value Area
startTime (series int) : Session start time in Unix timestamp format
endTime (series int) : Session end time in Unix timestamp format
dayHigh (series float) : Highest price of the session
dayLow (series float) : Lowest price of the session
step (series float) : Size of each price row (calculated as price range divided by number of rows)
pointOfControlLevel (series int) : Index of the row containing the Point of Control
valueAreaHighLevel (series int) : Index of the row containing the Value Area High
valueAreaLowLevel (series int) : Index of the row containing the Value Area Low
lastTime (series int) : Tracks the most recent timestamp processed
volumeRows (map) : Stores volume data for each price level row (key=row number, value=volume)
ltfSessionHighs (array) : Stores high prices from lower timeframe data
ltfSessionLows (array) : Stores low prices from lower timeframe data
ltfSessionVols (array) : Stores volume data from lower timeframe data