utilsLibrary "utils"
Few essentials captured together (subset of arrayutils)
timer(timeStart, timeEnd)
finds difference between two timestamps
Parameters:
timeStart (int) : start timestamp
timeEnd (int)
Returns:
check_overflow(pivots, barArray, dir)
finds difference between two timestamps
Parameters:
pivots (array) : pivots array
barArray (array) : pivot bar array
dir (int) : direction for which overflow need to be checked
Returns: bool overflow
get_trend_series(pivots, length, highLow, trend)
finds series of pivots in particular trend
Parameters:
pivots (array) : pivots array
length (int) : length for which trend series need to be checked
highLow (int) : filter pivot high or low
trend (int) : Uptrend or Downtrend
Returns: int trendIndexes
get_trend_series(pivots, firstIndex, lastIndex)
finds series of pivots in particular trend
Parameters:
pivots (array) : pivots array
firstIndex (int) : First index of the series
lastIndex (int) : Last index of the series
Returns: int trendIndexes
getConsolidatedLabel(include, labels, separator)
Consolidates labels into single string by concatenating it with given separator
Parameters:
include (array) : array of conditions to include label or not
labels (array) : string array of labels
separator (simple string) : Separator for concatenating labels
Returns: string labelText
getColors(theme)
gets array of colors based on theme
Parameters:
theme (simple string) : dark or light theme
Returns: color themeColors
Penunjuk dan strategi
pandas_taLibrary "pandas_ta" (converted to pineScript version 6)
All credit goes to blackcat1402
www.tradingview.com
PINE v6 Counterpart of Pandas TA - A Technical Analysis Library in Python 3 at github.com/twopirllc/pandas-ta
The Original Pandas Technical Analysis (Pandas TA) is an easy to use library that leverages the Pandas package with more than 130 Indicators and Utility functions and more than 60 TA Lib Candlestick Patterns.
Function Brief Descriptions (Pls find details in script comments)
bton --> Binary to number
wcp --> Weighted Closing Price (WCP)
counter --> Condition counter
xbt --> Between
ebsw --> Even Better SineWave (EBSW)
ao --> Awesome Oscillator (AO)
apo --> Absolute Price Oscillator (APO)
xrf --> Dynamic shifted values
bias --> Bias (BIAS)
bop --> Balance of Power (BOP)
brar --> BRAR (BRAR)
cci --> Commodity Channel Index (CCI)
cfo --> Chande Forcast Oscillator (CFO)
cg --> Center of Gravity (CG)
cmo --> Chande Momentum Oscillator (CMO)
coppock --> Coppock Curve (COPC)
cti --> Correlation Trend Indicator (CTI)
dmi --> Directional Movement Index(DMI)
er --> Efficiency Ratio (ER)
eri --> Elder Ray Index (ERI)
fisher --> Fisher Transform (FISHT)
inertia --> Inertia (INERTIA)
kdj --> KDJ (KDJ)
kst --> 'Know Sure Thing' (KST)
macd --> Moving Average Convergence Divergence (MACD)
mom --> Momentum (MOM)
pgo --> Pretty Good Oscillator (PGO)
ppo --> Percentage Price Oscillator (PPO)
psl --> Psychological Line (PSL)
pvo --> Percentage Volume Oscillator (PVO)
qqe --> Quantitative Qualitative Estimation (QQE)
roc --> Rate of Change (ROC)
rsi --> Relative Strength Index (RSI)
rsx --> Relative Strength Xtra (rsx)
rvgi --> Relative Vigor Index (RVGI)
slope --> Slope
smi --> SMI Ergodic Indicator (SMI)
sqz* --> Squeeze (SQZ) *
sqz_pro --> Squeeze PRO(SQZPRO)
xfl --> Condition filter
stc --> Schaff Trend Cycle (STC)
stoch --> Stochastic (STOCH)
stochrsi --> Stochastic RSI (STOCH RSI)
trix --> Trix (TRIX)
tsi --> True Strength Index (TSI)
uo --> Ultimate Oscillator (UO)
willr --> William's Percent R (WILLR)
alma --> Arnaud Legoux Moving Average (ALMA)
xll --> Dynamic rolling lowest values
dema --> Double Exponential Moving Average (DEMA)
ema --> Exponential Moving Average (EMA)
fwma --> Fibonacci's Weighted Moving Average (FWMA)
hilo --> Gann HiLo Activator(HiLo)
hma --> Hull Moving Average (HMA)
hwma --> HWMA (Holt-Winter Moving Average)
ichimoku --> Ichimoku Kinkō Hyō (ichimoku)
jma --> Jurik Moving Average Average (JMA)
kama --> Kaufman's Adaptive Moving Average (KAMA)
linreg --> Linear Regression Moving Average (linreg)
mgcd --> McGinley Dynamic Indicator
rma --> wildeR's Moving Average (RMA)
sinwma --> Sine Weighted Moving Average (SWMA)
ssf --> Ehler's Super Smoother Filter (SSF) © 2013
supertrend --> Supertrend (supertrend)
xsa --> X simple moving average
swma --> Symmetric Weighted Moving Average (SWMA)
t3 --> Tim Tillson's T3 Moving Average (T3)
tema --> Triple Exponential Moving Average (TEMA)
trima --> Triangular Moving Average (TRIMA)
vidya --> Variable Index Dynamic Average (VIDYA)
vwap --> Volume Weighted Average Price (VWAP)
vwma --> Volume Weighted Moving Average (VWMA)
wma --> Weighted Moving Average (WMA)
zlma --> Zero Lag Moving Average (ZLMA)
entropy --> Entropy (ENTP)
kurtosis --> Rolling Kurtosis
skew --> Rolling Skew
xev --> Condition all
zscore --> Rolling Z Score
adx --> Average Directional Movement (ADX)
aroon --> Aroon & Aroon Oscillator (AROON)
chop --> Choppiness Index (CHOP)
xex --> Condition any
cksp --> Chande Kroll Stop (CKSP)
dpo --> Detrend Price Oscillator (DPO)
long_run --> Long Run
psar --> Parabolic Stop and Reverse (psar)
short_run --> Short Run
vhf --> Vertical Horizontal Filter (VHF)
vortex --> Vortex
accbands --> Acceleration Bands (ACCBANDS)
atr --> Average True Range (ATR)
bbands --> Bollinger Bands (BBANDS)
donchian --> Donchian Channels (DC)
kc --> Keltner Channels (KC)
massi --> Mass Index (MASSI)
natr --> Normalized Average True Range (NATR)
pdist --> Price Distance (PDIST)
rvi --> Relative Volatility Index (RVI)
thermo --> Elders Thermometer (THERMO)
ui --> Ulcer Index (UI)
ad --> Accumulation/Distribution (AD)
cmf --> Chaikin Money Flow (CMF)
efi --> Elder's Force Index (EFI)
ecm --> Ease of Movement (EOM)
kvo --> Klinger Volume Oscillator (KVO)
mfi --> Money Flow Index (MFI)
nvi --> Negative Volume Index (NVI)
obv --> On Balance Volume (OBV)
pvi --> Positive Volume Index (PVI)
dvdi --> Dual Volume Divergence Index (DVDI)
xhh --> Dynamic rolling highest values
pvt --> Price-Volume Trend (PVT)
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.
abstractchartpatternsLibrary "abstractchartpatterns"
Library having abstract types and methods for chart pattern implementations
method checkSize(filters, points)
checks if the series of pivots are within the size filter
Namespace types: SizeFilters
Parameters:
filters (SizeFilters) : SizeFilters object containing size criteria to be matched
points (array) : list of pivot points
Returns: true if matches the size filter, false otherwise
checkBarRatio(p1, p2, p3, properties)
checks if three zigzag pivot points are having uniform bar ratios
Parameters:
p1 (chart.point) : First pivot point
p2 (chart.point) : Second pivot point
p3 (chart.point) : Third pivot point
properties (ScanProperties)
Returns: true if points are having uniform bar ratio
getRatioDiff(p1, p2, p3)
gets ratio difference between 3 pivot combinations
Parameters:
p1 (chart.point)
p2 (chart.point)
p3 (chart.point)
Returns: returns the ratio difference between pivot2/pivot1 ratio and pivot3/pivot2 ratio
method inspect(points, stratingBar, endingBar, direction, ohlcArray)
Creates a trend line between 2 or 3 points and validates and selects best combination
Namespace types: array
Parameters:
points (array) : Array of chart.point objects used for drawing trend line
stratingBar (int) : starting bar of the trend line
endingBar (int) : ending bar of the trend line
direction (float) : direction of the last pivot. Tells whether the line is joining upper pivots or the lower pivots
ohlcArray (array type from Trendoscope/ohlc/3) : Array of OHLC values
Returns: boolean flag indicating if the trend line is valid and the trend line object as tuple
method draw(this)
draws pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be drawn
Returns: Current Pattern object
method erase(this)
erase the given pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be erased
Returns: Current Pattern object
method push(this, p, maxItems)
push Pattern object to the array by keeping maxItems limit
Namespace types: array
Parameters:
this (array) : array of Pattern objects
p (Pattern) : Pattern object to be added to array
@oaram maxItems Max number of items the array can hold
maxItems (int)
Returns: Current Pattern array
method deepcopy(this)
Perform deep copy of a chart point array
Namespace types: array
Parameters:
this (array) : array of chart.point objects
Returns: deep copy array
DrawingProperties
Object containing properties for pattern drawing
Fields:
patternLineWidth (series int) : Line width of the pattern trend lines
showZigzag (series bool) : show zigzag associated with pattern
zigzagLineWidth (series int) : line width of the zigzag lines. Used only when showZigzag is set to true
zigzagLineColor (series color) : color of the zigzag lines. Used only when showZigzag is set to true
showPatternLabel (series bool) : display pattern label containing the name
patternLabelSize (series string) : size of the pattern label. Used only when showPatternLabel is set to true
showPivotLabels (series bool) : Display pivot labels of the patterns marking 1-6
pivotLabelSize (series string) : size of the pivot label. Used only when showPivotLabels is set to true
pivotLabelColor (series color) : color of the pivot label outline. chart.bg_color or chart.fg_color are the appropriate values.
deleteOnPop (series bool) : delete the pattern when popping out from the array of Patterns.
Pattern
Object containing Individual Pattern data
Fields:
dir (series int) : direction of the last pivot
points (array) : array of Zigzag Pivot points
trendLine1 (Line type from Trendoscope/LineWrapper/2) : First trend line joining pivots 1, 3, 5
trendLine2 (Line type from Trendoscope/LineWrapper/2) : Second trend line joining pivots 2, 4 (, 6)
properties (DrawingProperties) : DrawingProperties Object carrying common properties
patternColor (series color) : Individual pattern color. Lines and labels will be using this color.
ratioDiff (series float) : Difference between trendLine1 and trendLine2 ratios
zigzagLine (series polyline) : Internal zigzag line drawing Object
pivotLabels (array) : array containning Pivot labels
patternLabel (series label) : pattern label Object
patternType (series int) : integer representing the pattern type
patternName (series string) : Type of pattern in string
SizeFilters
Object containing properties for pattern size filters
Fields:
filterByBar (series bool) : If set filter the patterns by the bar range
minPatternBars (series int) : Used only when filterByBar is set to true. Minimum bars range for pattern size
maxPatternBars (series int) : Used only when filterByBar is set to true. Maximum bars range for pattern size
filterByPercent (series bool) : Filters patterns by percent of price if set
minPatternPercent (series int) : Used only when filterByPercent is set. Minimum pattern size in terms of percent of price
maxPatternPercent (series int) : Used only when filterByPercent is set. Maximum pattern size in terms of percent of price
ScanProperties
Object containing properties for pattern scanning
Fields:
offset (series int) : Zigzag pivot offset. Set it to 1 for non repainting scan.
numberOfPivots (series int) : Number of pivots to be used in pattern search. Can be either 5 or 6
errorRatio (series float) : Error Threshold to be considered for comparing the slope of lines
flatRatio (series float) : Retracement ratio threshold used to determine if the lines are flat
checkBarRatio (series bool) : Also check bar ratio are within the limits while scanning the patterns
barRatioLimit (series float) : Bar ratio limit used for checking the bars. Used only when checkBarRatio is set to true
avoidOverlap (series bool) : avoid overlapping patterns.
ignoreIfEntryCrossed (series bool) : Ignore the trade if close price does not fall within the price entry price range
allowedPatterns (array) : array of bool encoding the allowed pattern types.
allowedLastPivotDirections (array) : array of int representing allowed last pivot direction for each pattern types
themeColors (array) : color array of themes to be used.
filters (SizeFilters)
MonthlyStatsLibLibrary "MonthlyStatsLib"
trackMonthlyStats(monthlyInvestment, currentTime, netProfit, closedTrades, lastNetProfit, lastClosedTrades)
Parameters:
monthlyInvestment (float)
currentTime (int)
netProfit (float)
closedTrades (int)
lastNetProfit (float)
lastClosedTrades (int)
displayMonthlyTable(showTable, monthsToShow, monthLabels, monthProfits, monthReturns, monthWinCounts, monthTradeCounts, monthGrossProfits, monthGrossLosses, monthTheoreticalEnds)
Parameters:
showTable (bool)
monthsToShow (int)
monthLabels (array)
monthProfits (array)
monthReturns (array)
monthWinCounts (array)
monthTradeCounts (array)
monthGrossProfits (array)
monthGrossLosses (array)
monthTheoreticalEnds (array)
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
AltsMetricsPrivate Library
Library "AltsMetrics"
curve(disp_ind)
Call function to get a certain curve of your strategy.
Parameters:
disp_ind (string)
Returns: Returns type of curve plot.
cleaner(disp_ind, plot)
Call function to filter out your Strategy plots
Parameters:
disp_ind (string)
plot (float)
cobraTable(option, position)
Assign this function to a random variable to get the "Performance Table"
Parameters:
option (simple string)
position (simple string)
MajorMetricsPrivate Library
Library "MajorMetrics"
curve(disp_ind)
Call function to get a certain curve of your strategy.
Parameters:
disp_ind (string)
Returns: Returns type of curve plot.
cleaner(disp_ind, plot)
Call function to filter out your Strategy plots
Parameters:
disp_ind (string)
plot (float)
cobraTable(option, position)
Assign this function to a random variable to get the "Performance Table"
Parameters:
option (simple string)
position (simple string)
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
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
Casa_TableLibrary "Casa_Table"
A powerful library for creating customizable tables from data arrays and matrices.
Features flexible formatting options including:
- Multiple function implementations for different levels of control
- Consistent column counts required across matrix rows
- Matching dimensions needed for color arrays/matrices
- Cell spanning capabilities across rows/columns
- Rich examples demonstrating proper data structure setup
The library makes it easy to transform your data into professional-looking
tables while maintaining full control over their visual appearance.
floatArrayToCellArray(floatArray)
Helper function that converts a float array to a Cell array so it can be rendered with the fromArray function
Parameters:
floatArray (array) : (array) the float array to convert to a Cell array.
Returns: array The Cell array to return.
stringArrayToCellArray(stringArray)
Helper function that converts a string array to a Cell array so it can be rendered with the fromArray function
Parameters:
stringArray (array) : (array) the array to convert to a Cell array.
Returns: array The Cell array to return.
floatMatrixToCellMatrix(floatMatrix)
Helper function that converts a float matrix to a Cell matrix so it can be rendered with the fromMatrix function
Parameters:
floatMatrix (matrix) : (matrix) the float matrix to convert to a string matrix.
Returns: matrix The Cell matrix to render.
stringMatrixToCellMatrix(stringMatrix)
Helper function that converts a string matrix to a Cell matrix so it can be rendered with the fromMatrix function
Parameters:
stringMatrix (matrix) : (matrix) the string matrix to convert to a Cell matrix.
Returns: matrix The Cell matrix to return.
fromMatrix(CellMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText)
Takes a CellMatrix and renders it as a table.
Parameters:
CellMatrix (matrix) : (matrix) The Cells to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
tableNumRows (int) : (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromMatrix(dataMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText)
Renders a float matrix as a table.
Parameters:
dataMatrix (matrix) : (matrix_float) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
tableNumRows (int) : (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromMatrix(dataMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText)
Renders a string matrix as a table.
Parameters:
dataMatrix (matrix) : (matrix_string) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
tableNumRows (int) : (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromArray(dataArray, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText)
Renders a Cell array as a table.
Parameters:
dataArray (array) : (array) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromArray(dataArray, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText)
Renders a string array as a table.
Parameters:
dataArray (array) : (array_string) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromArray(dataArray, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText)
Renders a float array as a table.
Parameters:
dataArray (array) : (array_float) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
debug(message, position)
Renders a debug message in a table at the desired location on screen.
Parameters:
message (string) : (string) The message to render.
position (string) : (string) Optional. The position of the debug message. Defaults to position.middle_right.
Cell
Type for each cell's content and appearance
Fields:
content (series string)
bgColor (series color)
textColor (series color)
align (series string)
colspan (series int)
rowspan (series int)
Casa_UtilsLibrary "Casa_Utils"
A collection of convenience and helper functions for indicator and library authors on TradingView
formatNumber(num)
My version of format number that doesn't have so many decimal places...
Parameters:
num (float) : The number to be formatted
Returns: The formatted number
getDateString(timestamp)
Convenience function returns timestamp in yyyy/MM/dd format.
Parameters:
timestamp (int) : The timestamp to stringify
Returns: The date string
getDateTimeString(timestamp)
Convenience function returns timestamp in yyyy/MM/dd hh:mm format.
Parameters:
timestamp (int) : The timestamp to stringify
Returns: The date string
getInsideBarCount()
Gets the number of inside bars for the current chart. Can also be passed to request.security to get the same for different timeframes.
Returns: The # of inside bars on the chart right now.
getLabelStyleFromString(styleString, acceptGivenIfNoMatch)
Tradingview doesn't give you a nice way to put the label styles into a dropdown for configuration settings. So, I specify them in the following format: "Center", "Left", "Lower Left", "Lower Right", "Right", "Up", "Upper Left", "Upper Right", "Plain Text", "No Labels". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
styleString (string)
acceptGivenIfNoMatch (bool) : If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
Returns: The string expected by tradingview functions
getTime(hourNumber, minuteNumber)
Given an hour number and minute number, adds them together and returns the sum. To be used by getLevelBetweenTimes when fetching specific price levels during a time window on the day.
Parameters:
hourNumber (int) : The hour number
minuteNumber (int) : The minute number
Returns: The sum of all the minutes
getHighAndLowBetweenTimes(start, end)
Given a start and end time, returns the high or low price during that time window.
Parameters:
start (int) : The timestamp to start with (# of seconds)
end (int) : The timestamp to end with (# of seconds)
Returns: The high or low value
getPremarketHighsAndLows()
Returns an expression that can be used by request.security to fetch the premarket high & low levels in a tuple.
Returns: (tuple)
getAfterHoursHighsAndLows()
Returns an expression that can be used by request.security to fetch the after hours high & low levels in a tuple.
Returns: (tuple)
getOvernightHighsAndLows()
Returns an expression that can be used by request.security to fetch the overnight high & low levels in a tuple.
Returns: (tuple)
getNonRthHighsAndLows()
Returns an expression that can be used by request.security to fetch the high & low levels for premarket, after hours and overnight in a tuple.
Returns: (tuple)
getLineStyleFromString(styleString, acceptGivenIfNoMatch)
Tradingview doesn't give you a nice way to put the line styles into a dropdown for configuration settings. So, I specify them in the following format: "Solid", "Dashed", "Dotted", "None/Hidden". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
styleString (string) : Plain english (or TV Standard) version of the style string
acceptGivenIfNoMatch (bool) : If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
Returns: The string expected by tradingview functions
getPercentFromPrice(price)
Get the % the current price is away from the given price.
Parameters:
price (float)
Returns: The % the current price is away from the given price.
getPositionFromString(position)
Tradingview doesn't give you a nice way to put the positions into a dropdown for configuration settings. So, I specify them in the following format: "Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
position (string) : Plain english position string
Returns: The string expected by tradingview functions
getRsiAvgsExpression(rsiLength)
Call request.security with this as the expression to get the average up/down values that can be used with getRsiPrice (below) to calculate the price level where the supplied RSI level would be reached.
Parameters:
rsiLength (simple int) : The length of the RSI requested.
Returns: A tuple containing the avgUp and avgDown values required by the getRsiPrice function.
getRsiPrice(rsiLevel, rsiLength, avgUp, avgDown)
use the values returned by getRsiAvgsExpression() to calculate the price level when the provided RSI level would be reached.
Parameters:
rsiLevel (float) : The RSI level to find price at.
rsiLength (int) : The length of the RSI to calculate.
avgUp (float) : The average move up of RSI.
avgDown (float) : The average move down of RSI.
Returns: The price level where the provided RSI level would be met.
getSizeFromString(sizeString)
Tradingview doesn't give you a nice way to put the sizes into a dropdown for configuration settings. So, I specify them in the following format: "Auto", "Huge", "Large", "Normal", "Small", "Tiny". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
sizeString (string) : Plain english size string
Returns: The string expected by tradingview functions
getTimeframeOfChart()
Get the timeframe of the current chart for display
Returns: The string of the current chart timeframe
getTimeNowPlusOffset(candleOffset)
Helper function for drawings that use xloc.bar_time to help you know the time offset if you want to place the end of the drawing out into the future. This determines the time-size of one candle and then returns a time n candleOffsets into the future.
Parameters:
candleOffset (int) : The number of items to find singular/plural for.
Returns: The future time
getVolumeBetweenTimes(start, end)
Given a start and end time, returns the sum of all volume across bars during that time window.
Parameters:
start (int) : The timestamp to start with (# of seconds)
end (int) : The timestamp to end with (# of seconds)
Returns: The volume
isToday()
Returns true if the current bar occurs on today's date.
Returns: True if current bar is today
padLabelString(labelText, labelStyle)
Pads a label string so that it appears properly in or not in a label. When label.style_none is used, this will make sure it is left-aligned instead of center-aligned. When any other type is used, it adds a single space to the right so there is padding against the right end of the label.
Parameters:
labelText (string) : The string to be padded
labelStyle (string) : The style of the label being padded for.
Returns: The padded string
plural(num, singular, plural)
Helps format a string for plural/singular. By default, if you only provide num, it will just return "s" for plural and nothing for singular (eg. plural(numberOfCats)). But you can optionally specify the full singular/plural words for more complicated nomenclature (eg. plural(numberOfBenches, 'bench', 'benches'))
Parameters:
num (int) : The number of items to find singular/plural for.
singular (string) : The string to return if num is singular. Defaults to an empty string.
plural (string) : The string to return if num is plural. Defaults to 's' so you can just add 's' to the end of a word.
Returns: The singular or plural provided strings depending on the num provided.
timeframeInSeconds(timeframe)
Get the # of seconds in a given timeframe. Tradingview's timeframe.in_seconds() expects a simple string, and we often need to use series string, so this is an alternative to get you the value you need.
Parameters:
timeframe (string)
Returns: The number of secondsof that timeframe
timeframeOfChart()
Convert a timeframe string to a consistent standard.
Returns: The standard format for the string, or the unchanged value if it is unknown.
timeframeToString(timeframe)
Convert a timeframe string to a consistent standard.
Parameters:
timeframe (string)
Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
stringToTimeframe(strTimeframe)
Convert an english-friendly timeframe string to a value that can be used by request.security. Specifically, this corrects hour strings (eg. 4h) to their numeric "minute" equivalent (eg. 240)
Parameters:
strTimeframe (string)
Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
getPriceLabel(price, labelOffset, labelStyle, labelSize, labelColor, textColor)
Defines a label for the end of a price level line.
Parameters:
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
labelStyle (string) : A plain english string as defined in getLabelStyleFromString.
labelSize (string) : The size of the label.
labelColor (color) : The color of the label.
textColor (color) : The color of the label text (defaults to #ffffff)
Returns: The label that was created.
setPriceLabel(label, labelName, price, labelOffset, labelTemplate, labelStyle, labelColor, textColor)
Updates the label position & text based on price changes.
Parameters:
label (label) : The label to update.
labelName (string) : The name of the price level to be placed on the label.
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
labelTemplate (string) : The str.format template to use for the label. Defaults to: '{0}: {1} {2}{3,number,#.##}%' which means '{price}: {labelName} {+/-}{percentFromPrice}%'
labelStyle (string)
labelColor (color)
textColor (color)
getPriceLabelLine(price, labelOffset, labelColor, lineWidth)
Defines a line that will stretch from the plot line to the label.
Parameters:
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
labelColor (color)
lineWidth (int) : The width of the line. Defaults to 1.
setPriceLabelLine(line, price, labelOffset, lastTime, lineColor)
Updates the price label line based on price changes.
Parameters:
line (line) : The line to update.
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
lastTime (int) : The last time that the line should stretch from. Defaults to time.
lineColor (color)
lib_input_enumLibrary "lib_input_enum"
some enum wrappers for style identifiers, that can be used in input.enum calls to have nicer dropdown names
to_size(select)
converts Size enum to builtin size.tiny / size.small / etc., ideally used around input: to_size(input.enum(Size.SMALL, ....))
Parameters:
select (series Size)
to_size(select)
converts a string key to builtin size.tiny / size.small / etc., ideally used around input: to_size(input.string('small', ...., ))
Parameters:
select (string)
reduce_size(select)
converting a builtin size identifier to one instance smaller (except tiny and auto)
Parameters:
select (string)
to_linestyle(select)
converts LineStyle enum to builtin line.style_solid / line.style_dashed / line.style_dotted, ideally used around input: to_linestyle(input.enum(LineStyle.SOLID, ....))
Parameters:
select (series LineStyle)
to_linestyle(select)
converts a string key to builtin line.style_solid / line.style_dashed / line.style_dotted, ideally used around input: to_linestyle(input.string('solid', ...., ))
Parameters:
select (string)
to_labelstyle(select)
converts LineStyle enum to builtin line.style_solid / line.style_dashed / line.style_dotted, ideally used around input: to_linestyle(input.enum(LineStyle.SOLID, ....))
Parameters:
select (series LabelStyle)
to_labelstyle(select)
converts a string key to builtin line.style_solid / line.style_dashed / line.style_dotted, ideally used around input: to_linestyle(input.string('solid', ...., ))
Parameters:
select (string)
DynamicMALibrary "DynamicMA"
Dynamic Moving Averages Library
Introduction
The Dynamic Moving Averages Library is a specialized collection of custom built functions designed to calculate moving averages dynamically, beginning from the first available bar. Unlike standard moving averages, which rely on fixed length lookbacks, this library ensures that indicators remain fully functional from the very first data point, making it an essential tool for analysing assets with short time series or limited historical data.
This approach allows traders and developers to build robust indicators that do not require a preset amount of historical data before generating meaningful outputs. It is particularly advantageous for:
Newly listed assets with minimal price history.
High-timeframe trading, where large lookback periods can lead to delayed or missing data.
By eliminating the constraints of fixed lookback periods, this library enables the seamless construction of trend indicators, smoothing functions, and hybrid models that adapt instantly to market conditions.
Comprehensive Set of Custom Moving Averages
The library includes a wide range of custom dynamic moving averages, each designed for specific analytical use cases:
SMA (Simple Moving Average) – The fundamental moving average, dynamically computed.
EMA (Exponential Moving Average) – Adaptive smoothing for better trend tracking.
DEMA (Double Exponential Moving Average) – Faster trend detection with reduced lag.
TEMA (Triple Exponential Moving Average) – Even more responsive than DEMA.
WMA (Weighted Moving Average) – Emphasizes recent price action while reducing noise.
VWMA (Volume Weighted Moving Average) – Accounts for volume to give more weight to high-volume periods.
HMA (Hull Moving Average) – A superior smoothing method with low lag.
SMMA (Smoothed Moving Average) – A hybrid approach between SMA and EMA.
LSMA (Least Squares Moving Average) – Uses linear regression for trend detection.
RMA (Relative Moving Average) – Used in RSI-based calculations for smooth momentum readings.
ALMA (Arnaud Legoux Moving Average) – A Gaussian-weighted MA for superior signal clarity.
Hyperbolic MA (HyperMA) – A mathematically optimized averaging method with dynamic weighting.
Each function dynamically adjusts its calculation length to match the available bar count, ensuring instant functionality on all assets.
Fully Optimized for Pine Script v6
This library is built on Pine Script v6, ensuring compatibility with modern TradingView indicators and scripts. It includes exportable functions for seamless integration into custom indicators, making it easy to develop trend-following models, volatility filters, and adaptive risk-management systems.
Why Use Dynamic Moving Averages?
Traditional moving averages suffer from a common limitation: they require a fixed historical window to generate meaningful values. This poses several problems:
New Assets Have No Historical Data - If an asset has only been trading for a short period, traditional moving averages may not be able to generate valid signals.
High Timeframes Require Massive Lookbacks - On 1W or 1M charts, a 200-period SMA would require 200 weeks or months of data, making it unusable on newer assets.
Delayed Signal Initialization - Standard indicators often take dozens of bars to stabilize, reducing effectiveness when trading new trends.
The Dynamic Moving Averages Library eliminates these issues by ensuring that every function:
Starts calculation from bar one, using available data instead of waiting for a lookback period.
Adapts dynamically across timeframes, making it equally effective on low or high timeframes.
Allows smoother, more responsive trend tracking, particularly useful for volatile or low-liquidity assets.
This flexibility makes it indispensable for custom script developers, quantitative analysts, and discretionary traders looking to build more adaptive and resilient indicators.
Final Summary
The Dynamic Moving Averages Library is a versatile and powerful set of functions designed to overcome the limitations of fixed-lookback indicators. By dynamically adjusting the calculation length from the first bar, this library ensures that moving averages remain fully functional across all timeframes and asset types, making it an essential tool for traders and developers alike.
With built-in adaptability, low-lag smoothing, and support for multiple moving average types, this library unlocks new possibilities for quantitative trading and strategy development - especially for assets with short price histories or those traded on higher timeframes.
For traders looking to enhance signal reliability, minimize lag, and build adaptable trading systems, the Dynamic Moving Averages Library provides an efficient and flexible solution.
SMA(sourceData, maxLength)
Dynamic SMA
Parameters:
sourceData (float)
maxLength (int)
EMA(src, length)
Dynamic EMA
Parameters:
src (float)
length (int)
DEMA(src, length)
Dynamic DEMA
Parameters:
src (float)
length (int)
TEMA(src, length)
Dynamic TEMA
Parameters:
src (float)
length (int)
WMA(src, length)
Dynamic WMA
Parameters:
src (float)
length (int)
HMA(src, length)
Dynamic HMA
Parameters:
src (float)
length (int)
VWMA(src, volsrc, length)
Dynamic VWMA
Parameters:
src (float)
volsrc (float)
length (int)
SMMA(src, length)
Dynamic SMMA
Parameters:
src (float)
length (int)
LSMA(src, length, offset)
Dynamic LSMA
Parameters:
src (float)
length (int)
offset (int)
RMA(src, length)
Dynamic RMA
Parameters:
src (float)
length (int)
ALMA(src, length, offset_sigma, sigma)
Dynamic ALMA
Parameters:
src (float)
length (int)
offset_sigma (float)
sigma (float)
HyperMA(src, length)
Dynamic HyperbolicMA
Parameters:
src (float)
length (int)
[GYTS] FiltersToolkit LibraryFiltersToolkit Library
🌸 Part of GoemonYae Trading System (GYTS) 🌸
🌸 --------- 1. INTRODUCTION --------- 🌸
💮 What Does This Library Contain?
This library is a curated collection of high-performance digital signal processing (DSP) filters and auxiliary functions designed specifically for financial time series analysis. It includes a shortlist of our favourite and best performing filters — each rigorously tested and selected for their responsiveness, minimal lag and robustness in diverse market conditions. These tools form an integral part of the GoemonYae Trading System (GYTS), chosen for their unique characteristics in handling market data.
The library contains two main categories:
1. Smoothing filters (low-pass filters and moving averages) for e.g. denoising, trend following
2. Detrending tools (high-pass and band-pass filters, known as "oscillators") for e.g. mean reversion
This collection is finely tuned for practical trading applications and is therefore not meant to be exhaustive. However, will continue to expand as we discover and validate new filtering techniques. I welcome collaboration and suggestions for novel approaches.
🌸 ——— 2. ADDED VALUE ——— 🌸
💮 Unified syntax and comprehensive documentation
The FiltersToolkit Library brings together a wide array of valuable filters under a unified, intuitive syntax. Each function is thoroughly documented, with clear explanations and academic sources that underline the mathematical rigour behind the methods. This level of documentation not only facilitates integration into trading strategies but also helps underlying the underlying concepts and rationale.
💮 Optimised performance and readability
The code prioritizes computational efficiency while maintaining readability. Key optimizations include:
- Minimizing redundant calculations in recursive filters
- Smart coefficient caching
- Efficient state management
- Vectorized operations where applicable
💮 Enhanced functionality and flexibility
Some filters in this library introduce extended functionality beyond the original publications. For instance, the MESA Adaptive Moving Average (MAMA) and Ehlers’ Combined Bandpass Filter incorporate multiple variations found in the literature, thereby providing traders with flexible tools that can be fine-tuned to different market conditions.
🌸 ——— 3. THE FILTERS ——— 🌸
💮 Hilbert Transform Function
This function implements the Hilbert Transform as utilised by John Ehlers. It converts a real-valued time series into its analytic signal, enabling the extraction of instantaneous phase and frequency information—an essential step in adaptive filtering.
Source: John Ehlers - "Rocket Science for Traders" (2001), "TASC 2001 V. 19:9", "Cybernetic Analysis for Stocks and Futures" (2004)
💮 Homodyne Discriminator
By leveraging the Hilbert Transform, this function computes the dominant cycle period through a Homodyne Discriminator. It extracts the in-phase and quadrature components of the signal, facilitating a robust estimation of the underlying cycle characteristics.
Source: John Ehlers - "Rocket Science for Traders" (2001), "TASC 2001 V. 19:9", "Cybernetic Analysis for Stocks and Futures" (2004)
💮 MESA Adaptive Moving Average (MAMA)
An advanced dual-stage adaptive moving average, this function outputs both the MAMA and its companion FAMA. It combines adaptive alpha computation with elements from Kaufman’s Adaptive Moving Average (KAMA) to provide a responsive and reliable trend indicator.
Source: John Ehlers - "Rocket Science for Traders" (2001), "TASC 2001 V. 19:9", "Cybernetic Analysis for Stocks and Futures" (2004)
💮 BiQuad Filters
A family of second-order recursive filters offering exceptional control over frequency response:
- High-pass filter for detrending
- Low-pass filter for smooth trend following
- Band-pass filter for cycle isolation
The quality factor (Q) parameter allows fine-tuning of the resonance characteristics, making these filters highly adaptable to different market conditions.
Source: Robert Bristow-Johnson's Audio EQ Cookbook, implemented by @The_Peaceful_Lizard
💮 Relative Vigor Index (RVI)
This filter evaluates the strength of a trend by comparing the closing price to the trading range. Operating similarly to a band-pass filter, the RVI provides insights into market momentum and potential reversals.
Source: John Ehlers – “Cybernetic Analysis for Stocks and Futures” (2004)
💮 Cyber Cycle
The Cyber Cycle filter emphasises market cycles by smoothing out noise and highlighting the dominant cyclical behaviour. It is particularly useful for detecting trend reversals and cyclical patterns in the price data.
Source: John Ehlers – “Cybernetic Analysis for Stocks and Futures” (2004)
💮 Butterworth High Pass Filter
Inspired by the classical Butterworth design, this filter achieves a maximally flat magnitude response in the passband while effectively removing low-frequency trends. Its design minimises phase distortion, which is vital for accurate signal interpretation.
Source: John Ehlers – “Cybernetic Analysis for Stocks and Futures” (2004)
💮 2-Pole SuperSmoother
Employing a two-pole design, the SuperSmoother filter reduces high-frequency noise with minimal lag. It is engineered to preserve trend integrity while offering a smooth output even in noisy market conditions.
Source: John Ehlers – “Cybernetic Analysis for Stocks and Futures” (2004)
💮 3-Pole SuperSmoother
An extension of the 2-pole design, the 3-pole SuperSmoother further attenuates high-frequency noise. Its additional pole delivers enhanced smoothing at the cost of slightly increased lag.
Source: John Ehlers – “Cybernetic Analysis for Stocks and Futures” (2004)
💮 Adaptive Directional Volatility Moving Average (ADXVma)
This adaptive moving average adjusts its smoothing factor based on directional volatility. By combining true range and directional movement measurements, it remains exceptionally flat during ranging markets and responsive during directional moves.
Source: Various implementations across platforms, unified and optimized
💮 Ehlers Combined Bandpass Filter with Automated Gain Control (AGC)
This sophisticated filter merges a highpass pre-processing stage with a bandpass filter. An integrated Automated Gain Control normalises the output to a consistent range, while offering both regular and truncated recursive formulations to manage lag.
Source: John F. Ehlers – “Truncated Indicators” (2020), “Cycle Analytics for Traders” (2013)
💮 Voss Predictive Filter
A forward-looking filter that predicts future values of a band-limited signal in real time. By utilising multiple time-delayed feedback terms, it provides anticipatory coupling and delivers a short-term predictive signal.
Source: John Ehlers - "A Peek Into The Future" (TASC 2019-08)
💮 Adaptive Autonomous Recursive Moving Average (A2RMA)
This filter dynamically adjusts its smoothing through an adaptive mechanism based on an efficiency ratio and a dynamic threshold. A double application of an adaptive moving average ensures both responsiveness and stability in volatile and ranging markets alike. Very flat response when properly tuned.
Source: @alexgrover (2019)
💮 Ultimate Smoother (2-Pole)
The Ultimate Smoother filter is engineered to achieve near-zero lag in its passband by subtracting a high-pass response from an all-pass response. This creates a filter that maintains signal fidelity at low frequencies while effectively filtering higher frequencies at the expense of slight overshooting.
Source: John Ehlers - TASC 2024-04 "The Ultimate Smoother"
Note: This library is actively maintained and enhanced. Suggestions for additional filters or improvements are welcome through the usual channels. The source code contains a list of tested filters that did not make it into the curated collection.
ValueAtTime█ OVERVIEW
This library is a Pine Script® programming tool for accessing historical values in a time series using UNIX timestamps . Its data structure and functions index values by time, allowing scripts to retrieve past values based on absolute timestamps or relative time offsets instead of relying on bar index offsets.
█ CONCEPTS
UNIX timestamps
In Pine Script®, a UNIX timestamp is an integer representing the number of milliseconds elapsed since January 1, 1970, at 00:00:00 UTC (the UNIX Epoch ). The timestamp is a unique, absolute representation of a specific point in time. Unlike a calendar date and time, a UNIX timestamp's meaning does not change relative to any time zone .
This library's functions process series values and corresponding UNIX timestamps in pairs , offering a simplified way to identify values that occur at or near distinct points in time instead of on specific bars.
Storing and retrieving time-value pairs
This library's `Data` type defines the structure for collecting time and value information in pairs. Objects of the `Data` type contain the following two fields:
• `times` – An array of "int" UNIX timestamps for each recorded value.
• `values` – An array of "float" values for each saved timestamp.
Each index in both arrays refers to a specific time-value pair. For instance, the `times` and `values` elements at index 0 represent the first saved timestamp and corresponding value. The library functions that maintain `Data` objects queue up to one time-value pair per bar into the object's arrays, where the saved timestamp represents the bar's opening time .
Because the `times` array contains a distinct UNIX timestamp for each item in the `values` array, it serves as a custom mapping for retrieving saved values. All the library functions that return information from a `Data` object use this simple two-step process to identify a value based on time:
1. Perform a binary search on the `times` array to find the earliest saved timestamp closest to the specified time or offset and get the element's index.
2. Access the element from the `values` array at the retrieved index, returning the stored value corresponding to the found timestamp.
Value search methods
There are several techniques programmers can use to identify historical values from corresponding timestamps. This library's functions include three different search methods to locate and retrieve values based on absolute times or relative time offsets:
Timestamp search
Find the value with the earliest saved timestamp closest to a specified timestamp.
Millisecond offset search
Find the value with the earliest saved timestamp closest to a specified number of milliseconds behind the current bar's opening time. This search method provides a time-based alternative to retrieving historical values at specific bar offsets.
Period offset search
Locate the value with the earliest saved timestamp closest to a defined period offset behind the current bar's opening time. The function calculates the span of the offset based on a period string . The "string" must contain one of the following unit tokens:
• "D" for days
• "W" for weeks
• "M" for months
• "Y" for years
• "YTD" for year-to-date, meaning the time elapsed since the beginning of the bar's opening year in the exchange time zone.
The period string can include a multiplier prefix for all supported units except "YTD" (e.g., "2W" for two weeks).
Note that the precise span covered by the "M", "Y", and "YTD" units varies across time. The "1M" period can cover 28, 29, 30, or 31 days, depending on the bar's opening month and year in the exchange time zone. The "1Y" period covers 365 or 366 days, depending on leap years. The "YTD" period's span changes with each new bar, because it always measures the time from the start of the current bar's opening year.
█ CALCULATIONS AND USE
This library's functions offer a flexible, structured approach to retrieving historical values at or near specific timestamps, millisecond offsets, or period offsets for different analytical needs.
See below for explanations of the exported functions and how to use them.
Retrieving single values
The library includes three functions that retrieve a single stored value using timestamp, millisecond offset, or period offset search methods:
• `valueAtTime()` – Locates the saved value with the earliest timestamp closest to a specified timestamp.
• `valueAtTimeOffset()` – Finds the saved value with the earliest timestamp closest to the specified number of milliseconds behind the current bar's opening time.
• `valueAtPeriodOffset()` – Finds the saved value with the earliest timestamp closest to the period-based offset behind the current bar's opening time.
Each function has two overloads for advanced and simple use cases. The first overload searches for a value in a user-specified `Data` object created by the `collectData()` function (see below). It returns a tuple containing the found value and the corresponding timestamp.
The second overload maintains a `Data` object internally to store and retrieve values for a specified `source` series. This overload returns a tuple containing the historical `source` value, the corresponding timestamp, and the current bar's `source` value, making it helpful for comparing past and present values from requested contexts.
Retrieving multiple values
The library includes the following functions to retrieve values from multiple historical points in time, facilitating calculations and comparisons with values retrieved across several intervals:
• `getDataAtTimes()` – Locates a past `source` value for each item in a `timestamps` array. Each retrieved value's timestamp represents the earliest time closest to one of the specified timestamps.
• `getDataAtTimeOffsets()` – Finds a past `source` value for each item in a `timeOffsets` array. Each retrieved value's timestamp represents the earliest time closest to one of the specified millisecond offsets behind the current bar's opening time.
• `getDataAtPeriodOffsets()` – Finds a past value for each item in a `periods` array. Each retrieved value's timestamp represents the earliest time closest to one of the specified period offsets behind the current bar's opening time.
Each function returns a tuple with arrays containing the found `source` values and their corresponding timestamps. In addition, the tuple includes the current `source` value and the symbol's description, which also makes these functions helpful for multi-interval comparisons using data from requested contexts.
Processing period inputs
When writing scripts that retrieve historical values based on several user-specified period offsets, the most concise approach is to create a single text input that allows users to list each period, then process the "string" list into an array for use in the `getDataAtPeriodOffsets()` function.
This library includes a `getArrayFromString()` function to provide a simple way to process strings containing comma-separated lists of periods. The function splits the specified `str` by its commas and returns an array containing every non-empty item in the list with surrounding whitespaces removed. View the example code to see how we use this function to process the value of a text area input .
Calculating period offset times
Because the exact amount of time covered by a specified period offset can vary, it is often helpful to verify the resulting times when using the `valueAtPeriodOffset()` or `getDataAtPeriodOffsets()` functions to ensure the calculations work as intended for your use case.
The library's `periodToTimestamp()` function calculates an offset timestamp from a given period and reference time. With this function, programmers can verify the time offsets in a period-based data search and use the calculated offset times in additional operations.
For periods with "D" or "W" units, the function calculates the time offset based on the absolute number of milliseconds the period covers (e.g., `86400000` for "1D"). For periods with "M", "Y", or "YTD" units, the function calculates an offset time based on the reference time's calendar date in the exchange time zone.
Collecting data
All the `getDataAt*()` functions, and the second overloads of the `valueAt*()` functions, collect and maintain data internally, meaning scripts do not require a separate `Data` object when using them. However, the first overloads of the `valueAt*()` functions do not collect data, because they retrieve values from a user-specified `Data` object.
For cases where a script requires a separate `Data` object for use with these overloads or other custom routines, this library exports the `collectData()` function. This function queues each bar's `source` value and opening timestamp into a `Data` object and returns the object's ID.
This function is particularly useful when searching for values from a specific series more than once. For instance, instead of using multiple calls to the second overloads of `valueAt*()` functions with the same `source` argument, programmers can call `collectData()` to store each bar's `source` and opening timestamp, then use the returned `Data` object's ID in calls to the first `valueAt*()` overloads to reduce memory usage.
The `collectData()` function and all the functions that collect data internally include two optional parameters for limiting the saved time-value pairs to a sliding window: `timeOffsetLimit` and `timeframeLimit`. When either has a non-na argument, the function restricts the collected data to the maximum number of recent bars covered by the specified millisecond- and timeframe-based intervals.
NOTE : All calls to the functions that collect data for a `source` series can execute up to once per bar or realtime tick, because each stored value requires a unique corresponding timestamp. Therefore, scripts cannot call these functions iteratively within a loop . If a call to these functions executes more than once inside a loop's scope, it causes a runtime error.
█ EXAMPLE CODE
The example code at the end of the script demonstrates one possible use case for this library's functions. The code retrieves historical price data at user-specified period offsets, calculates price returns for each period from the retrieved data, and then populates a table with the results.
The example code's process is as follows:
1. Input a list of periods – The user specifies a comma-separated list of period strings in the script's "Period list" input (e.g., "1W, 1M, 3M, 1Y, YTD"). Each item in the input list represents a period offset from the latest bar's opening time.
2. Process the period list – The example calls `getArrayFromString()` on the first bar to split the input list by its commas and construct an array of period strings.
3. Request historical data – The code uses a call to `getDataAtPeriodOffsets()` as the `expression` argument in a request.security() call to retrieve the closing prices of "1D" bars for each period included in the processed `periods` array.
4. Display information in a table – On the latest bar, the code uses the retrieved data to calculate price returns over each specified period, then populates a two-row table with the results. The cells for each return percentage are color-coded based on the magnitude and direction of the price change. The cells also include tooltips showing the compared daily bar's opening date in the exchange time zone.
█ NOTES
• This library's architecture relies on a user-defined type (UDT) for its data storage format. UDTs are blueprints from which scripts create objects , i.e., composite structures with fields containing independent values or references of any supported type.
• The library functions search through a `Data` object's `times` array using the array.binary_search_leftmost() function, which is more efficient than looping through collected data to identify matching timestamps. Note that this built-in works only for arrays with elements sorted in ascending order .
• Each function that collects data from a `source` series updates the values and times stored in a local `Data` object's arrays. If a single call to these functions were to execute in a loop , it would store multiple values with an identical timestamp, which can cause erroneous search behavior. To prevent looped calls to these functions, the library uses the `checkCall()` helper function in their scopes. This function maintains a counter that increases by one each time it executes on a confirmed bar. If the count exceeds the total number of bars, indicating the call executes more than once in a loop, it raises a runtime error .
• Typically, when requesting higher-timeframe data with request.security() while using barmerge.lookahead_on as the `lookahead` argument, the `expression` argument should be offset with the history-referencing operator to prevent lookahead bias on historical bars. However, the call in this script's example code enables lookahead without offsetting the `expression` because the script displays results only on the last historical bar and all realtime bars, where there is no future data to leak into the past. This call ensures the displayed results use the latest data available from the context on realtime bars.
Look first. Then leap.
█ EXPORTED TYPES
Data
A structure for storing successive timestamps and corresponding values from a dataset.
Fields:
times (array) : An "int" array containing a UNIX timestamp for each value in the `values` array.
values (array) : A "float" array containing values corresponding to the timestamps in the `times` array.
█ EXPORTED FUNCTIONS
getArrayFromString(str)
Splits a "string" into an array of substrings using the comma (`,`) as the delimiter. The function trims surrounding whitespace characters from each substring, and it excludes empty substrings from the result.
Parameters:
str (series string) : The "string" to split into an array based on its commas.
Returns: (array) An array of trimmed substrings from the specified `str`.
periodToTimestamp(period, referenceTime)
Calculates a UNIX timestamp representing the point offset behind a reference time by the amount of time within the specified `period`.
Parameters:
period (series string) : The period string, which determines the time offset of the returned timestamp. The specified argument must contain a unit and an optional multiplier (e.g., "1Y", "3M", "2W", "YTD"). Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the `referenceTime` value's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
referenceTime (series int) : The millisecond UNIX timestamp from which to calculate the offset time.
Returns: (int) A millisecond UNIX timestamp representing the offset time point behind the `referenceTime`.
collectData(source, timeOffsetLimit, timeframeLimit)
Collects `source` and `time` data successively across bars. The function stores the information within a `Data` object for use in other exported functions/methods, such as `valueAtTimeOffset()` and `valueAtPeriodOffset()`. Any call to this function cannot execute more than once per bar or realtime tick.
Parameters:
source (series float) : The source series to collect. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
Returns: (Data) A `Data` object containing collected `source` values and corresponding timestamps over the allowed time range.
method valueAtTime(data, timestamp)
(Overload 1 of 2) Retrieves value and time data from a `Data` object's fields at the index of the earliest timestamp closest to the specified `timestamp`. Callable as a method or a function.
Parameters:
data (series Data) : The `Data` object containing the collected time and value data.
timestamp (series int) : The millisecond UNIX timestamp to search. The function returns data for the earliest saved timestamp that is closest to the value.
Returns: ( ) A tuple containing the following data from the `Data` object:
- The stored value corresponding to the identified timestamp ("float").
- The earliest saved timestamp that is closest to the specified `timestamp` ("int").
valueAtTime(source, timestamp, timeOffsetLimit, timeframeLimit)
(Overload 2 of 2) Retrieves `source` and time information for the earliest bar whose opening timestamp is closest to the specified `timestamp`. Any call to this function cannot execute more than once per bar or realtime tick.
Parameters:
source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
timestamp (series int) : The millisecond UNIX timestamp to search. The function returns data for the earliest bar whose timestamp is closest to the value.
timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
timeframeLimit (simple string) : (simple string) Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
Returns: ( ) A tuple containing the following data:
- The `source` value corresponding to the identified timestamp ("float").
- The earliest bar's timestamp that is closest to the specified `timestamp` ("int").
- The current bar's `source` value ("float").
method valueAtTimeOffset(data, timeOffset)
(Overload 1 of 2) Retrieves value and time data from a `Data` object's fields at the index of the earliest saved timestamp closest to `timeOffset` milliseconds behind the current bar's opening time. Callable as a method or a function.
Parameters:
data (series Data) : The `Data` object containing the collected time and value data.
timeOffset (series int) : The millisecond offset behind the bar's opening time. The function returns data for the earliest saved timestamp that is closest to the calculated offset time.
Returns: ( ) A tuple containing the following data from the `Data` object:
- The stored value corresponding to the identified timestamp ("float").
- The earliest saved timestamp that is closest to `timeOffset` milliseconds before the current bar's opening time ("int").
valueAtTimeOffset(source, timeOffset, timeOffsetLimit, timeframeLimit)
(Overload 2 of 2) Retrieves `source` and time information for the earliest bar whose opening timestamp is closest to `timeOffset` milliseconds behind the current bar's opening time. Any call to this function cannot execute more than once per bar or realtime tick.
Parameters:
source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
timeOffset (series int) : The millisecond offset behind the bar's opening time. The function returns data for the earliest bar's timestamp that is closest to the calculated offset time.
timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
Returns: ( ) A tuple containing the following data:
- The `source` value corresponding to the identified timestamp ("float").
- The earliest bar's timestamp that is closest to `timeOffset` milliseconds before the current bar's opening time ("int").
- The current bar's `source` value ("float").
method valueAtPeriodOffset(data, period)
(Overload 1 of 2) Retrieves value and time data from a `Data` object's fields at the index of the earliest timestamp closest to a calculated offset behind the current bar's opening time. The calculated offset represents the amount of time covered by the specified `period`. Callable as a method or a function.
Parameters:
data (series Data) : The `Data` object containing the collected time and value data.
period (series string) : The period string, which determines the calculated time offset. The specified argument must contain a unit and an optional multiplier (e.g., "1Y", "3M", "2W", "YTD"). Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the current bar's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
Returns: ( ) A tuple containing the following data from the `Data` object:
- The stored value corresponding to the identified timestamp ("float").
- The earliest saved timestamp that is closest to the calculated offset behind the bar's opening time ("int").
valueAtPeriodOffset(source, period, timeOffsetLimit, timeframeLimit)
(Overload 2 of 2) Retrieves `source` and time information for the earliest bar whose opening timestamp is closest to a calculated offset behind the current bar's opening time. The calculated offset represents the amount of time covered by the specified `period`. Any call to this function cannot execute more than once per bar or realtime tick.
Parameters:
source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
period (series string) : The period string, which determines the calculated time offset. The specified argument must contain a unit and an optional multiplier (e.g., "1Y", "3M", "2W", "YTD"). Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the current bar's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
Returns: ( ) A tuple containing the following data:
- The `source` value corresponding to the identified timestamp ("float").
- The earliest bar's timestamp that is closest to the calculated offset behind the current bar's opening time ("int").
- The current bar's `source` value ("float").
getDataAtTimes(timestamps, source, timeOffsetLimit, timeframeLimit)
Retrieves `source` and time information for each bar whose opening timestamp is the earliest one closest to one of the UNIX timestamps specified in the `timestamps` array. Any call to this function cannot execute more than once per bar or realtime tick.
Parameters:
timestamps (array) : An array of "int" values representing UNIX timestamps. The function retrieves `source` and time data for each element in this array.
source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
Returns: ( ) A tuple of the following data:
- An array containing a `source` value for each identified timestamp (array).
- An array containing an identified timestamp for each item in the `timestamps` array (array).
- The current bar's `source` value ("float").
- The symbol's description from `syminfo.description` ("string").
getDataAtTimeOffsets(timeOffsets, source, timeOffsetLimit, timeframeLimit)
Retrieves `source` and time information for each bar whose opening timestamp is the earliest one closest to one of the time offsets specified in the `timeOffsets` array. Each offset in the array represents the absolute number of milliseconds behind the current bar's opening time. Any call to this function cannot execute more than once per bar or realtime tick.
Parameters:
timeOffsets (array) : An array of "int" values representing the millisecond time offsets used in the search. The function retrieves `source` and time data for each element in this array. For example, the array ` ` specifies that the function returns data for the timestamps closest to one day and one week behind the current bar's opening time.
source (float) : (series float) The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
Returns: ( ) A tuple of the following data:
- An array containing a `source` value for each identified timestamp (array).
- An array containing an identified timestamp for each offset specified in the `timeOffsets` array (array).
- The current bar's `source` value ("float").
- The symbol's description from `syminfo.description` ("string").
getDataAtPeriodOffsets(periods, source, timeOffsetLimit, timeframeLimit)
Retrieves `source` and time information for each bar whose opening timestamp is the earliest one closest to a calculated offset behind the current bar's opening time. Each calculated offset represents the amount of time covered by a period specified in the `periods` array. Any call to this function cannot execute more than once per bar or realtime tick.
Parameters:
periods (array) : An array of period strings, which determines the time offsets used in the search. The function retrieves `source` and time data for each element in this array. For example, the array ` ` specifies that the function returns data for the timestamps closest to one day, week, and month behind the current bar's opening time. Each "string" in the array must contain a unit and an optional multiplier. Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the current bar's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
source (float) : (series float) The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
Returns: ( ) A tuple of the following data:
- An array containing a `source` value for each identified timestamp (array).
- An array containing an identified timestamp for each period specified in the `periods` array (array).
- The current bar's `source` value ("float").
- The symbol's description from `syminfo.description` ("string").