merge_pinbarLibrary "merge_pinbar"
merge_pinbar: merge bars and check whether the bar is a pinbar
merge_pinbar(simple, simple) merge_pinbar: merge bars and check whether the bar is a pinbar
Parameters:
simple : int period: the statistic bar period
simple : int max_bars: the max bars to be merged
Returns: array:
Library
Timed_exit_alert_for_webhookLibrary "Timed_exit_alert_for_webhook"
TODO: add library description here
fun(x) TODO: add function description here
Parameters:
x : TODO: add parameter x description here
Returns: TODO: add what function returns
for exiting FCM like Tradovate and AMP using API and python MT5 and Webhooks
the writer take no responsibility for trades made using this script its written for informational purposes only
adx: Configurable ADX (library) Library "adx"
Calculate ADX (and its constituent parts +DI, -DI, ATR),
using different moving averages and periods.
adx(atrMA, diMA, adxMA, atrLen, diLen, adxLen, h, l, c)
Parameters:
atrMA : Moving Average used for calculating the Average True Range.
Traditionally RMA, but using SMA here and in adxMA gives good results too.
diMA : Moving Average used for calculating the Directional Index.
Traditionally, RMA.
adxMA : Moving Average used for calculating the Average Directional
Index. Traditionally RMA, but using SMA here and in atrMA gives good results
too.
atrLen : Length of the Average True Range.
diLen : Length of the Directional Index.
adxLen : Length (smoothing) of the Average Directional Index.
h : Candle's high.
l : Candle's low.
c : Candle's close.
Returns:
statisticsLibrary "statistics"
General statistics library.
erf(x) The "error function" encountered in integrating the normal
distribution (which is a normalized form of the Gaussian function).
Parameters:
x : The input series.
Returns: The Error Function evaluated for each element of x.
erfc(x)
Parameters:
x : The input series
Returns: The Complementary Error Function evaluated for each alement of x.
sumOfReciprocals(src, len) Calculates the sum of the reciprocals of the series.
For each element 'elem' in the series:
sum += 1/elem
Should the element be 0, the reciprocal value of 0 is used instead
of NA.
Parameters:
src : The input series.
len : The length for the sum.
Returns: The sum of the resciprocals of 'src' for 'len' bars back.
mean(src, len) The mean of the series.
(wrapper around ta.sma).
Parameters:
src : The input series.
len : The length for the mean.
Returns: The mean of 'src' for 'len' bars back.
average(src, len) The mean of the series.
(wrapper around ta.sma).
Parameters:
src : The input series.
len : The length for the average.
Returns: The average of 'src' for 'len' bars back.
geometricMean(src, len) The Geometric Mean of the series.
The geometric mean is most important when using data representing
percentages, ratios, or rates of change. It cannot be used for
negative numbers
Since the pure mathematical implementation generates a very large
intermediate result, we performed the calculation in log space.
Parameters:
src : The input series.
len : The length for the geometricMean.
Returns: The geometric mean of 'src' for 'len' bars back.
harmonicMean(src, len) The Harmonic Mean of the series.
The harmonic mean is most applicable to time changes and, along
with the geometric mean, has been used in economics for price
analysis. It is more difficult to calculate; therefore, it is less
popular than eiter of the other averages.
0 values are ignored in the calculation.
Parameters:
src : The input series.
len : The length for the harmonicMean.
Returns: The harmonic mean of 'src' for 'len' bars back.
median(src, len) The median of the series.
(a wrapper around ta.median)
Parameters:
src : The input series.
len : The length for the median.
Returns: The median of 'src' for 'len' bars back.
variance(src, len, biased) The variance of the series.
Parameters:
src : The input series.
len : The length for the variance.
biased : Wether to use the biased calculation (for a population), or the
unbiased calculation (for a sample set). .
Returns: The variance of 'src' for 'len' bars back.
stdev(src, len, biased) The standard deviation of the series.
Parameters:
src : The input series.
len : The length for the stdev.
biased : Wether to use the biased calculation (for a population), or the
unbiased calculation (for a sample set). .
Returns: The standard deviation of 'src' for 'len' bars back.
skewness(src, len) The skew of the series.
Skewness measures the amount of distortion from a symmetric
distribution, making the curve appear to be short on the left
(lower prices) and extended to the right (higher prices). The
extended side, either left or right is called the tail, and a
longer tail to the right is called positive skewness. Negative
skewness has the tail extending towards the left.
Parameters:
src : The input series.
len : The length for the skewness.
Returns: The skewness of 'src' for 'len' bars back.
kurtosis(src, len) The kurtosis of the series.
Kurtosis describes the peakedness or flatness of a distribution.
This can be used as an unbiased assessment of whether prices are
trending or moving sideways. Trending prices will ocver a wider
range and thus a flatter distribution (kurtosis < 3; negative
kurtosis). If prices are range-bound, there will be a clustering
around the mean and we have positive kurtosis (kurtosis > 3)
Parameters:
src : The input series.
len : The length for the kurtosis.
Returns: The kurtosis of 'src' for 'len' bars back.
excessKurtosis(src, len) The normalized kurtosis of the series.
kurtosis > 0 --> positive kurtosis --> trending
kurtosis < 0 --> negative krutosis --> range-bound
Parameters:
src : The input series.
len : The length for the excessKurtosis.
Returns: The excessKurtosis of 'src' for 'len' bars back.
normDist(src, len, value) Calculates the probability mass for the value according to the
src and length. It calculates the probability for value to be
present in the normal distribution calculated for src and length.
Parameters:
src : The input series.
len : The length for the normDist.
value : The series of values to calculate the normal distance for
Returns: The normal distance of 'value' to 'src' for 'len' bars back.
normDistCumulative(src, len, value) Calculates the cumulative probability mass for the value according
to the src and length. It calculates the cumulative probability for
value to be present in the normal distribution calculated for src
and length.
Parameters:
src : The input series.
len : The length for the normDistCumulative.
value : The series of values to calculate the cumulative normal distance
for
Returns: The cumulative normal distance of 'value' to 'src' for 'len' bars
back.
zScore(src, len, value) Returns then z-score of objective to the series src.
It returns the number of stdev's the objective is away from the
mean(src, len)
Parameters:
src : The input series.
len : The length for the zScore.
value : The series of values to calculate the cumulative normal distance
for
Returns: The z-score of objectiv with respect to src and len.
er(src, len) Calculates the efficiency ratio of the series.
It measures the noise of the series. The lower the number, the
higher the noise.
Parameters:
src : The input series.
len : The length for the efficiency ratio.
Returns: The efficiency ratio of 'src' for 'len' bars back.
efficiencyRatio(src, len) Calculates the efficiency ratio of the series.
It measures the noise of the series. The lower the number, the
higher the noise.
Parameters:
src : The input series.
len : The length for the efficiency ratio.
Returns: The efficiency ratio of 'src' for 'len' bars back.
fractalEfficiency(src, len) Calculates the efficiency ratio of the series.
It measures the noise of the series. The lower the number, the
higher the noise.
Parameters:
src : The input series.
len : The length for the efficiency ratio.
Returns: The efficiency ratio of 'src' for 'len' bars back.
mse(src, len) Calculates the Mean Squared Error of the series.
Parameters:
src : The input series.
len : The length for the mean squared error.
Returns: The mean squared error of 'src' for 'len' bars back.
meanSquaredError(src, len) Calculates the Mean Squared Error of the series.
Parameters:
src : The input series.
len : The length for the mean squared error.
Returns: The mean squared error of 'src' for 'len' bars back.
rmse(src, len) Calculates the Root Mean Squared Error of the series.
Parameters:
src : The input series.
len : The length for the root mean squared error.
Returns: The root mean squared error of 'src' for 'len' bars back.
rootMeanSquaredError(src, len) Calculates the Root Mean Squared Error of the series.
Parameters:
src : The input series.
len : The length for the root mean squared error.
Returns: The root mean squared error of 'src' for 'len' bars back.
mae(src, len) Calculates the Mean Absolute Error of the series.
Parameters:
src : The input series.
len : The length for the mean absolute error.
Returns: The mean absolute error of 'src' for 'len' bars back.
meanAbsoluteError(src, len) Calculates the Mean Absolute Error of the series.
Parameters:
src : The input series.
len : The length for the mean absolute error.
Returns: The mean absolute error of 'src' for 'len' bars back.
CRCHud - HUD Library (Heads Up Display)Library "CRCHud"
Library of functions which will contain functions that allow reusable HUD (Heads up Display) components to used from within other scripts
add_cell_change() - Adds a new cell to designated table which displays the data source value, the line color, data title, and automatically calculated %percent change stats based on lookback value supplied (default - previous bar)
Punchline_LibLibrary "Punchline_Lib"
roundSmart(float) Truncates decimal points of a float value based on the amount of digits before the decimal point
Parameters:
float : _value any number
Returns: float
tostring_smart(float) converts a float to a string, intelligently cutting off decimal points
Parameters:
float : _value any number
Returns: string
The Divergent LibraryLibrary "TheDivergentLibrary"
The Divergent Library is only useful when combined with the Pro version of The Divergent - Advanced divergence indicator . This is because the Basic (free) version of The Divergent does not expose the "Divergence Signal" value.
Usage instructions:
1. Create a new chart
2. Add The Divergent (Pro) indicator to your chart
3. Create a new strategy, import this library, add a "source" input, link it to "The Divergent: Divergence Signal", and use the library to decode the divergence signals from The Divergent (You can find example strategy code published in our profile)
4. Act on the divergences signalled by The Divergent
---
isRegularBullishEnabled(context) Returns a boolean value indicating whether Regular Bullish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Regular Bullish divergence detection is enabled in The Divergent.
isHiddenBullishEnabled(context) Returns a boolean value indicating whether Hidden Bullish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Hidden Bullish divergence detection is enabled in The Divergent.
isRegularBearishEnabled(context) Returns a boolean value indicating whether Regular Bearish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Regular Bearish divergence detection is enabled in The Divergent.
isHiddenBearishEnabled(context) Returns a boolean value indicating whether Hidden Bearish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Hidden Bearish divergence detection is enabled in The Divergent.
getPivotDetectionSource(context) Returns the 'Pivot Detection Source' setting of The Divergent. The returned value can be either "Oscillator" or "Price".
Parameters:
context : The context of The Divergent Library.
Returns: One of the following string values: "Oscillator" or "Price".
getPivotDetectionMode(context) Returns the 'Pivot Detection Mode' setting of The Divergent. The returned value can be either "Bodies" or "Wicks".
Parameters:
context : The context of The Divergent Library.
Returns: One of the following string values: "Bodies" or "Wicks".
isLinked(context) Returns a boolean value indicating the link status to The Divergent indicator.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating the link status to The Divergent indicator.
init(firstBarSignal, displayLinkStatus, debug) Initialises The Divergent Library's context with the signal produced by The Divergent on the first bar. The value returned from this function is called the "context of The Divergent Library". Some of the other functions of this library requires you to pass in this context.
Parameters:
firstBarSignal : The signal from The Divergent indicator on the first bar.
displayLinkStatus : A boolean value indicating whether the Link Status window should be displayed in the bottom left corner of the chart. Defaults to true.
debug : A boolean value indicating whether the Link Status window should display debug information. Defaults to false.
Returns: A bool array containing the context of The Divergent Library.
processSignal(signal) Processes a signal from The Divergent and returns a 5-tuple with the decoded signal: [ int divergenceType, int priceBarIndexStart, int priceBarIndexEnd, int oscillatorBarIndexStart, int oscillatorBarIndexEnd]. `divergenceType` can be one of the following values: na → No divergence was detected, 1 → Regular Bullish, 2 → Regular Bullish early, 3 → Hidden Bullish, 4 → Hidden Bullish early, 5 → Regular Bearish, 6 → Regular Bearish early, 7 → Hidden Bearish, 8 → Hidden Bearish early.
Parameters:
signal : The signal from The Divergent indicator.
Returns: A 5-tuple with the following values: [ int divergenceType, int priceBarIndexStart, int priceBarIndexEnd, int oscillatorBarIndexStart, int oscillatorBarIndexEnd].
lib_Indicators_v2_DTULibrary "lib_Indicators_v2_DTU"
This library functions returns included Moving averages, indicators with factorization, functions candles, function heikinashi and more.
Created it to feed as backend of my indicator/strategy "Indicators & Combinations Framework Advanced v2 " that will be released ASAP.
This is replacement of my previous indicator (lib_indicators_DT)
I will add an indicator example which will use this indicator named as "lib_indicators_v2_DTU example" to help the usage of this library
Additionally library will be updated with more indicators in the future
NOTES:
Indicator functions returns only one series :-(
plotcandle function returns candle series
INDICATOR LIST:
hide = 'DONT DISPLAY', //Dont display & calculate the indicator. (For my framework usage)
alma = 'alma(src,len,offset=0.85,sigma=6)', //Arnaud Legoux Moving Average
ama = 'ama(src,len,fast=14,slow=100)', //Adjusted Moving Average
acdst = 'accdist()', //Accumulation/distribution index.
cma = 'cma(src,len)', //Corrective Moving average
dema = 'dema(src,len)', //Double EMA (Same as EMA with 2 factor)
ema = 'ema(src,len)', //Exponential Moving Average
gmma = 'gmma(src,len)', //Geometric Mean Moving Average
hghst = 'highest(src,len)', //Highest value for a given number of bars back.
hl2ma = 'hl2ma(src,len)', //higest lowest moving average
hma = 'hma(src,len)', //Hull Moving Average.
lgAdt = 'lagAdapt(src,len,perclen=5,fperc=50)', //Ehler's Adaptive Laguerre filter
lgAdV = 'lagAdaptV(src,len,perclen=5,fperc=50)', //Ehler's Adaptive Laguerre filter variation
lguer = 'laguerre(src,len)', //Ehler's Laguerre filter
lsrcp = 'lesrcp(src,len)', //lowest exponential esrcpanding moving line
lexp = 'lexp(src,len)', //lowest exponential expanding moving line
linrg = 'linreg(src,len,loffset=1)', //Linear regression
lowst = 'lowest(src,len)', //Lovest value for a given number of bars back.
pcnl = 'percntl(src,len)', //percentile nearest rank. Calculates percentile using method of Nearest Rank.
pcnli = 'percntli(src,len)', //percentile linear interpolation. Calculates percentile using method of linear interpolation between the two nearest ranks.
rema = 'rema(src,len)', //Range EMA (REMA)
rma = 'rma(src,len)', //Moving average used in RSI. It is the exponentially weighted moving average with alpha = 1 / length.
sma = 'sma(src,len)', //Smoothed Moving Average
smma = 'smma(src,len)', //Smoothed Moving Average
supr2 = 'super2(src,len)', //Ehler's super smoother, 2 pole
supr3 = 'super3(src,len)', //Ehler's super smoother, 3 pole
strnd = 'supertrend(src,len,period=3)', //Supertrend indicator
swma = 'swma(src,len)', //Sine-Weighted Moving Average
tema = 'tema(src,len)', //Triple EMA (Same as EMA with 3 factor)
tma = 'tma(src,len)', //Triangular Moving Average
vida = 'vida(src,len)', //Variable Index Dynamic Average
vwma = 'vwma(src,len)', //Volume Weigted Moving Average
wma = 'wma(src,len)', //Weigted Moving Average
angle = 'angle(src,len)', //angle of the series (Use its Input as another indicator output)
atr = 'atr(src,len)', //average true range. RMA of true range.
bbr = 'bbr(src,len,mult=1)', //bollinger %%
bbw = 'bbw(src,len,mult=2)', //Bollinger Bands Width. The Bollinger Band Width is the difference between the upper and the lower Bollinger Bands divided by the middle band.
cci = 'cci(src,len)', //commodity channel index
cctbb = 'cctbbo(src,len)', //CCT Bollinger Band Oscilator
chng = 'change(src,len)', //Difference between current value and previous, source - source .
cmo = 'cmo(src,len)', //Chande Momentum Oscillator. Calculates the difference between the sum of recent gains and the sum of recent losses and then divides the result by the sum of all price movement over the same period.
cog = 'cog(src,len)', //The cog (center of gravity) is an indicator based on statistics and the Fibonacci golden ratio.
cpcrv = 'copcurve(src,len)', //Coppock Curve. was originally developed by Edwin "Sedge" Coppock (Barron's Magazine, October 1962).
corrl = 'correl(src,len)', //Correlation coefficient. Describes the degree to which two series tend to deviate from their ta.sma values.
count = 'count(src,len)', //green avg - red avg
dev = 'dev(src,len)', //ta.dev() Measure of difference between the series and it's ta.sma
fall = 'falling(src,len)', //ta.falling() Test if the `source` series is now falling for `length` bars long. (Use its Input as another indicator output)
kcr = 'kcr(src,len,mult=2)', //Keltner Channels Range
kcw = 'kcw(src,len,mult=2)', //ta.kcw(). Keltner Channels Width. The Keltner Channels Width is the difference between the upper and the lower Keltner Channels divided by the middle channel.
macd = 'macd(src,len)', //macd
mfi = 'mfi(src,len)', //Money Flow Index
nvi = 'nvi()', //Negative Volume Index
obv = 'obv()', //On Balance Volume
pvi = 'pvi()', //Positive Volume Index
pvt = 'pvt()', //Price Volume Trend
rise = 'rising(src,len)', //ta.rising() Test if the `source` series is now rising for `length` bars long. (Use its Input as another indicator output)
roc = 'roc(src,len)', //Rate of Change
rsi = 'rsi(src,len)', //Relative strength Index
smosc = 'smi_osc(src,len,fast=5, slow=34)', //smi Oscillator
smsig = 'smi_sig(src,len,fast=5, slow=34)', //smi Signal
stdev = 'stdev(src,len)', //Standart deviation
trix = 'trix(src,len)' , //the rate of change of a triple exponentially smoothed moving average.
tsi = 'tsi(src,len)', //True Strength Index
vari = 'variance(src,len)', //ta.variance(). Variance is the expectation of the squared deviation of a series from its mean (ta.sma), and it informally measures how far a set of numbers are spread out from their mean.
wilpc = 'willprc(src,len)', //Williams %R
wad = 'wad()', //Williams Accumulation/Distribution.
wvad = 'wvad()' //Williams Variable Accumulation/Distribution.
}
f_func(string, float, simple, float, float, float, simple) f_func Return selected indicator value with different parameters. New version. Use extra parameters for available indicators
Parameters:
string : FuncType_ indicator from the indicator list
float : src_ close, open, high, low,hl2, hlc3, ohlc4 or any
simple : int length_ indicator length
float : p1 extra parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p2 extra parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p3 extra parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
simple : int version_ indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators
Returns: float Return calculated indicator value
fn_heikin(float, float, float, float) fn_heikin Return given src data (open, high,low,close) as heikin ashi candle values
Parameters:
float : o_ open value
float : h_ high value
float : l_ low value
float : c_ close value
Returns: float heikin ashi open, high,low,close vlues that will be used with plotcandle
fn_plotFunction(float, string, simple, bool) fn_plotFunction Return input src data with different plotting options
Parameters:
float : src_ indicator src_data or any other series.....
string : plotingType Ploting type of the function on the screen
simple : int stochlen_ length for plotingType for stochastic and PercentRank options
bool : plotSWMA Use SWMA for smoothing Ploting
Returns: float
fn_funcPlotV2(string, float, simple, float, float, float, simple, string, simple, bool, bool) fn_funcPlotV2 Return selected indicator value with different parameters. New version. Use extra parameters fora available indicators
Parameters:
string : FuncType_ indicator from the indicator list
float : src_data_ close, open, high, low,hl2, hlc3, ohlc4 or any
simple : int length_ indicator length
float : p1 extra parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p2 extra parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p3 extra parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
simple : int version_ indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators
string : plotingType Ploting type of the function on the screen
simple : int stochlen_ length for plotingType for stochastic and PercentRank options
bool : plotSWMA Use SWMA for smoothing Ploting
bool : log_ Use log on function entries
Returns: float Return calculated indicator value
fn_factor(string, float, simple, float, float, float, simple, simple, string, simple, bool, bool) fn_factor Return selected indicator's factorization with given arguments
Parameters:
string : FuncType_ indicator from the indicator list
float : src_data_ close, open, high, low,hl2, hlc3, ohlc4 or any
simple : int length_ indicator length
float : p1 parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p2 parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p3 parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
simple : int version_ indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators
simple : int fact_ Add double triple, Quatr factor to selected indicator (like converting EMA to 2-DEMA, 3-TEMA, 4-QEMA...)
string : plotingType Ploting type of the function on the screen
simple : int stochlen_ length for plotingType for stochastic and PercentRank options
bool : plotSWMA Use SWMA for smoothing Ploting
bool : log_ Use log on function entries
Returns: float Return result of the function
fn_plotCandles(string, simple, float, float, float, simple, string, simple, bool, bool, bool) fn_plotCandles Return selected indicator's candle values with different parameters also heikinashi is available
Parameters:
string : FuncType_ indicator from the indicator list
simple : int length_ indicator length
float : p1 parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p2 parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
float : p3 parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2)
simple : int version_ indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators
string : plotingType Ploting type of the function on the screen
simple : int stochlen_ length for plotingType for stochastic and PercentRank options
bool : plotSWMA Use SWMA for smoothing Ploting
bool : log_ Use log on function entries
bool : plotheikin_ Use Heikin Ashi on Plot
Returns: float
FunctionZigZagMultipleMethodsLibrary "FunctionZigZagMultipleMethods"
ZigZag Multiple Methods.
method(idx) Helper methods enumeration.
Parameters:
idx : int, index of method, range 0 to 4.
Returns: string
function(method, value_x, value_y) Multiple method ZigZag.
Parameters:
method : string, default='(MANUAL) Percent price move over X * Y', method for zigzag.
value_x : float, x value in method.
value_y : float, y value in method.
Returns: tuple with:
zigzag float
direction
reverse_line float
realtimeofpivot int
GenericTradingLibrary "GenericTrading"
This library aims to collect rare but useful operations for
get_most_recent_long_or_short_position_closed_index() : returns most recent long/short closed bar index.
get_most_recent_long_or_short_position_open_index() : returns most recent long/short closed bar index.
These two functions designed to help to speed up the coding for strategies that contains "re-enter" logic.
These two functions also could applies in the situations where time-count is needed in your condition.
lib_Indicators_DTLibrary "lib_Indicators_DT"
This library functions returns some Moving averages and indicators.
Created it to feed my indicator/strategy "INDICATOR & CONDITIONS COMBINATOR FRAMEWORK v1 " which I will publish it as soon as possible.
Credits: Library includes some public indicators, snippets from tradingview & @03.freeman's ("All MAs displayed") scripts.
(I hope, I dont break Tradingview's House Rules on Script Publishing)
f_plotPrep(src_, src_, src_, src_) Prepare Indicator Plot Type
Parameters:
src_ : Source
src_ : plotingType_ "Original, Stochastic, Percent"
src_ : stochlen_ Stochasting plottingtype length
src_ : plotSWMA_ Use SWMA for the output
Returns: Return the prepared indicator
f_funcPlot(string, float, simple, string, simple, bool) f_funcPlot(string f, float src_, simple int length_, string plotingType_ = "Original", simple int stochlen_=50, bool plotSWMA=false) Return selected indicator value with different parameters
Parameters:
string : f indicator-> options=
float : src_ close,open.....
simple : int length_ indicator length
string : plotingType return param-> options= ['Original', 'Stochastic', 'PercentRank')
simple : int stochlen_ length for return Param
bool : plotSWMA Use SWMA on Plot
Returns: float
DrawIndicatorOnTheChartLibrary "DrawIndicatorOnTheChart"
this library is used to show an indicator (such RSI, CCI, MOM etc) on the main chart with indicator's horizontal lines in a window. Location of the window is calculated dynamically by last price movemements
drawIndicator(indicatorName, indicator, indicatorcolor, period, indimax_, indimin_, levels, precision, xlocation) draws the related indicator on the chart
Parameters:
indicatorName : is the indicator name as string such "RSI", "CCI" etc
indicator : is the indicator you want to show, such rsi(close, 14), mom(close, 10) etc
indicatorcolor : is the color of indicator line
period : is the length of the window to show
indimax_ : is the maximum value of the indicator, for example for RSI it's 100.0, if the indicator (such CCI, MOM etc) doesn't have maximum value then use "na"
indimin_ : is the minimum value of the indicator, for example for RSI it's 0.0, if the indicator (such CCI, MOM etc)doesn't have maximum value then use "na"
levels : is the levels of the array for the horizontal lines. for example if you want horizontal lines at 30.0, and 70.0 then use array.from(30.0, 70.0). if no horizontal lines then use array.from(na)
precision : is the precision/number of decimals that is used to show indicator values, for example for RSI set it 2
xlocation : is end location of the indicator window, for example if xlocation = 0 window is created on the index of the last bar/candle
Returns: none
ZenLibraryLibrary "ZenLibrary"
A collection of custom tools & utility functions commonly used with my scripts.
getDecimals() Calculates how many decimals are on the quote price of the current market
Returns: The current decimal places on the market quote price
truncate(float, float) Truncates (cuts) excess decimal places
Parameters:
float : _number The number to truncate
float : _decimalPlaces (default=2) The number of decimal places to truncate to
Returns: The given _number truncated to the given _decimalPlaces
toWhole(float) Converts pips into whole numbers
Parameters:
float : _number The pip number to convert into a whole number
Returns: The converted number
toPips(float) Converts whole numbers back into pips
Parameters:
float : _number The whole number to convert into pips
Returns: The converted number
av_getPositionSize(float, float, float, float) Calculates OANDA forex position size for AutoView based on the given parameters
Parameters:
float : _balance The account balance to use
float : _risk The risk percentage amount (as a whole number - eg. 1 = 1% risk)
float : _stopPoints The stop loss distance in POINTS (not pips)
float : _conversionRate The conversion rate of our account balance currency
Returns: The calculated position size (in units - only compatible with OANDA)
getMA(int, string) Gets a Moving Average based on type
Parameters:
int : _length The MA period
string : _maType The type of MA
Returns: A moving average with the given parameters
getEAP(float) Performs EAP stop loss size calculation (eg. ATR >= 20.0 and ATR < 30, returns 20)
Parameters:
float : _atr The given ATR to base the EAP SL calculation on
Returns: The EAP SL converted ATR size
barsAboveMA(int, float) Counts how many candles are above the MA
Parameters:
int : _lookback The lookback period to look back over
float : _ma The moving average to check
Returns: The bar count of how many recent bars are above the MA
barsBelowMA(int, float) Counts how many candles are below the MA
Parameters:
int : _lookback The lookback period to look back over
float : _ma The moving average to reference
Returns: The bar count of how many recent bars are below the EMA
barsCrossedMA(int, float) Counts how many times the EMA was crossed recently
Parameters:
int : _lookback The lookback period to look back over
float : _ma The moving average to reference
Returns: The bar count of how many times price recently crossed the EMA
getPullbackBarCount(int, int) Counts how many green & red bars have printed recently (ie. pullback count)
Parameters:
int : _lookback The lookback period to look back over
int : _direction The color of the bar to count (1 = Green, -1 = Red)
Returns: The bar count of how many candles have retraced over the given lookback & direction
getBodySize() Gets the current candle's body size (in POINTS, divide by 10 to get pips)
Returns: The current candle's body size in POINTS
getTopWickSize() Gets the current candle's top wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's top wick size in POINTS
getBottomWickSize() Gets the current candle's bottom wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's bottom wick size in POINTS
getBodyPercent() Gets the current candle's body size as a percentage of its entire size including its wicks
Returns: The current candle's body size percentage
isHammer(float, bool) Checks if the current bar is a hammer candle based on the given parameters
Parameters:
float : _fib (default=0.382) The fib to base candle body on
bool : _colorMatch (default=false) Does the candle need to be green? (true/false)
Returns: A boolean - true if the current bar matches the requirements of a hammer candle
isStar(float, bool) Checks if the current bar is a shooting star candle based on the given parameters
Parameters:
float : _fib (default=0.382) The fib to base candle body on
bool : _colorMatch (default=false) Does the candle need to be red? (true/false)
Returns: A boolean - true if the current bar matches the requirements of a shooting star candle
isDoji(float, bool) Checks if the current bar is a doji candle based on the given parameters
Parameters:
float : _wickSize (default=2) The maximum top wick size compared to the bottom (and vice versa)
bool : _bodySize (default=0.05) The maximum body size as a percentage compared to the entire candle size
Returns: A boolean - true if the current bar matches the requirements of a doji candle
isBullishEC(float, float, bool) Checks if the current bar is a bullish engulfing candle
Parameters:
float : _allowance (default=0) How many POINTS to allow the open to be off by (useful for markets with micro gaps)
float : _rejectionWickSize (default=disabled) The maximum rejection wick size compared to the body as a percentage
bool : _engulfWick (default=false) Does the engulfing candle require the wick to be engulfed as well?
Returns: A boolean - true if the current bar matches the requirements of a bullish engulfing candle
isBearishEC(float, float, bool) Checks if the current bar is a bearish engulfing candle
Parameters:
float : _allowance (default=0) How many POINTS to allow the open to be off by (useful for markets with micro gaps)
float : _rejectionWickSize (default=disabled) The maximum rejection wick size compared to the body as a percentage
bool : _engulfWick (default=false) Does the engulfing candle require the wick to be engulfed as well?
Returns: A boolean - true if the current bar matches the requirements of a bearish engulfing candle
timeFilter(string, bool) Determines if the current price bar falls inside the specified session
Parameters:
string : _sess The session to check
bool : _useFilter (default=false) Whether or not to actually use this filter
Returns: A boolean - true if the current bar falls within the given time session
dateFilter(int, int) Determines if this bar's time falls within date filter range
Parameters:
int : _startTime The UNIX date timestamp to begin searching from
int : _endTime the UNIX date timestamp to stop searching from
Returns: A boolean - true if the current bar falls within the given dates
dayFilter(bool, bool, bool, bool, bool, bool, bool) Checks if the current bar's day is in the list of given days to analyze
Parameters:
bool : _monday Should the script analyze this day? (true/false)
bool : _tuesday Should the script analyze this day? (true/false)
bool : _wednesday Should the script analyze this day? (true/false)
bool : _thursday Should the script analyze this day? (true/false)
bool : _friday Should the script analyze this day? (true/false)
bool : _saturday Should the script analyze this day? (true/false)
bool : _sunday Should the script analyze this day? (true/false)
Returns: A boolean - true if the current bar's day is one of the given days
atrFilter(float, float) Checks the current bar's size against the given ATR and max size
Parameters:
float : _atr (default=ATR 14 period) The given ATR to check
float : _maxSize The maximum ATR multiplier of the current candle
Returns: A boolean - true if the current bar's size is less than or equal to _atr x _maxSize
fillCell(table, int, int, string, string, color, color) This updates the given table's cell with the given values
Parameters:
table : _table The table ID to update
int : _column The column to update
int : _row The row to update
string : _title The title of this cell
string : _value The value of this cell
color : _bgcolor The background color of this cell
color : _txtcolor The text color of this cell
Returns: A boolean - true if the current bar falls within the given dates
Bursa_SectorLibrary "Bursa_Sector"
: List of stocks classified by sector in Bursa Malaysia (As of Oct 2021)
getSector()
This function will get the sector of current stock that listed in Bursa Malaysia
CreateAndShowZigzagLibrary "CreateAndShowZigzag"
Functions in this library creates/updates zigzag array and shows the zigzag
getZigzag(zigzag, prd, max_array_size) calculates zigzag using period
Parameters:
zigzag : is the float array for the zigzag (should be defined like "var zigzag = array.new_float(0)"). each zigzag points contains 2 element: 1. price level of the zz point 2. bar_index of the zz point
prd : is the length to calculate zigzag waves by highest(prd)/lowest(prd)
max_array_size : is the maximum number of elements in zigzag, keep in mind each zigzag point contains 2 elements, so for example if it's 10 then zigzag has 10/2 => 5 zigzag points
Returns: dir that is the current direction of the zigzag
showZigzag(zigzag, oldzigzag, dir, upcol, dncol) this function shows zigzag
Parameters:
zigzag : is the float array for the zigzag (should be defined like "var zigzag = array.new_float(0)"). each zigzag points contains 2 element: 1. price level of the zz point 2. bar_index of the zz point
oldzigzag : is the float array for the zigzag, you get copy the zigzag array to oldzigzag by "oldzigzag = array.copy(zigzay)" before calling get_zigzag() function
dir : is the direction of the zigzag wave
upcol : is the color of the line if zigzag direction is up
dncol : is the color of the line if zigzag direction is down
Returns: null
taLibrary "ta"
█ OVERVIEW
This library holds technical analysis functions calculating values for which no Pine built-in exists.
Look first. Then leap.
█ FUNCTIONS
cagr(entryTime, entryPrice, exitTime, exitPrice)
It calculates the "Compound Annual Growth Rate" between two points in time. The CAGR is a notional, annualized growth rate that assumes all profits are reinvested. It only takes into account the prices of the two end points — not drawdowns, so it does not calculate risk. It can be used as a yardstick to compare the performance of two instruments. Because it annualizes values, the function requires a minimum of one day between the two end points (annualizing returns over smaller periods of times doesn't produce very meaningful figures).
Parameters:
entryTime : The starting timestamp.
entryPrice : The starting point's price.
exitTime : The ending timestamp.
exitPrice : The ending point's price.
Returns: CAGR in % (50 is 50%). Returns `na` if there is not >=1D between `entryTime` and `exitTime`, or until the two time points have not been reached by the script.
█ v2, Mar. 8, 2022
Added functions `allTimeHigh()` and `allTimeLow()` to find the highest or lowest value of a source from the first historical bar to the current bar. These functions will not look ahead; they will only return new highs/lows on the bar where they occur.
allTimeHigh(src)
Tracks the highest value of `src` from the first historical bar to the current bar.
Parameters:
src : (series int/float) Series to track. Optional. The default is `high`.
Returns: (float) The highest value tracked.
allTimeLow(src)
Tracks the lowest value of `src` from the first historical bar to the current bar.
Parameters:
src : (series int/float) Series to track. Optional. The default is `low`.
Returns: (float) The lowest value tracked.
█ v3, Sept. 27, 2022
This version includes the following new functions:
aroon(length)
Calculates the values of the Aroon indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
Returns: ( [float, float ]) A tuple of the Aroon-Up and Aroon-Down values.
coppock(source, longLength, shortLength, smoothLength)
Calculates the value of the Coppock Curve indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
longLength (simple int) : (simple int) Number of bars for the fast ROC value (length).
shortLength (simple int) : (simple int) Number of bars for the slow ROC value (length).
smoothLength (simple int) : (simple int) Number of bars for the weigted moving average value (length).
Returns: (float) The oscillator value.
dema(source, length)
Calculates the value of the Double Exponential Moving Average (DEMA).
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The double exponentially weighted moving average of the `source`.
dema2(src, length)
An alternate Double Exponential Moving Average (Dema) function to `dema()`, which allows a "series float" length argument.
Parameters:
src : (series int/float) Series of values to process.
length : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The double exponentially weighted moving average of the `src`.
dm(length)
Calculates the value of the "Demarker" indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
Returns: (float) The oscillator value.
donchian(length)
Calculates the values of a Donchian Channel using `high` and `low` over a given `length`.
Parameters:
length (int) : (series int) Number of bars (length).
Returns: ( [float, float, float ]) A tuple containing the channel high, low, and median, respectively.
ema2(src, length)
An alternate ema function to the `ta.ema()` built-in, which allows a "series float" length argument.
Parameters:
src : (series int/float) Series of values to process.
length : (series int/float) Number of bars (length).
Returns: (float) The exponentially weighted moving average of the `src`.
eom(length, div)
Calculates the value of the Ease of Movement indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
div (simple int) : (simple int) Divisor used for normalzing values. Optional. The default is 10000.
Returns: (float) The oscillator value.
frama(source, length)
The Fractal Adaptive Moving Average (FRAMA), developed by John Ehlers, is an adaptive moving average that dynamically adjusts its lookback period based on fractal geometry.
Parameters:
source (float) : (series int/float) Series of values to process.
length (int) : (series int) Number of bars (length).
Returns: (float) The fractal adaptive moving average of the `source`.
ft(source, length)
Calculates the value of the Fisher Transform indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Number of bars (length).
Returns: (float) The oscillator value.
ht(source)
Calculates the value of the Hilbert Transform indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
Returns: (float) The oscillator value.
ichimoku(conLength, baseLength, senkouLength)
Calculates values of the Ichimoku Cloud indicator, including tenkan, kijun, senkouSpan1, senkouSpan2, and chikou. NOTE: offsets forward or backward can be done using the `offset` argument in `plot()`.
Parameters:
conLength (int) : (series int) Length for the Conversion Line (Tenkan). The default is 9 periods, which returns the mid-point of the 9 period Donchian Channel.
baseLength (int) : (series int) Length for the Base Line (Kijun-sen). The default is 26 periods, which returns the mid-point of the 26 period Donchian Channel.
senkouLength (int) : (series int) Length for the Senkou Span 2 (Leading Span B). The default is 52 periods, which returns the mid-point of the 52 period Donchian Channel.
Returns: ( [float, float, float, float, float ]) A tuple of the Tenkan, Kijun, Senkou Span 1, Senkou Span 2, and Chikou Span values. NOTE: by default, the senkouSpan1 and senkouSpan2 should be plotted 26 periods in the future, and the Chikou Span plotted 26 days in the past.
ift(source)
Calculates the value of the Inverse Fisher Transform indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
Returns: (float) The oscillator value.
kvo(fastLen, slowLen, trigLen)
Calculates the values of the Klinger Volume Oscillator.
Parameters:
fastLen (simple int) : (simple int) Length for the fast moving average smoothing parameter calculation.
slowLen (simple int) : (simple int) Length for the slow moving average smoothing parameter calculation.
trigLen (simple int) : (simple int) Length for the trigger moving average smoothing parameter calculation.
Returns: ( [float, float ]) A tuple of the KVO value, and the trigger value.
pzo(length)
Calculates the value of the Price Zone Oscillator.
Parameters:
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
rms(source, length)
Calculates the Root Mean Square of the `source` over the `length`.
Parameters:
source (float) : (series int/float) Series of values to process.
length (int) : (series int) Number of bars (length).
Returns: (float) The RMS value.
rwi(length)
Calculates the values of the Random Walk Index.
Parameters:
length (simple int) : (simple int) Lookback and ATR smoothing parameter length.
Returns: ( [float, float ]) A tuple of the `rwiHigh` and `rwiLow` values.
stc(source, fast, slow, cycle, d1, d2)
Calculates the value of the Schaff Trend Cycle indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
fast (simple int) : (simple int) Length for the MACD fast smoothing parameter calculation.
slow (simple int) : (simple int) Length for the MACD slow smoothing parameter calculation.
cycle (simple int) : (simple int) Number of bars for the Stochastic values (length).
d1 (simple int) : (simple int) Length for the initial %D smoothing parameter calculation.
d2 (simple int) : (simple int) Length for the final %D smoothing parameter calculation.
Returns: (float) The oscillator value.
stochFull(periodK, smoothK, periodD)
Calculates the %K and %D values of the Full Stochastic indicator.
Parameters:
periodK (simple int) : (simple int) Number of bars for Stochastic calculation. (length).
smoothK (simple int) : (simple int) Number of bars for smoothing of the %K value (length).
periodD (simple int) : (simple int) Number of bars for smoothing of the %D value (length).
Returns: ( [float, float ]) A tuple of the slow %K and the %D moving average values.
stochRsi(lengthRsi, periodK, smoothK, periodD, source)
Calculates the %K and %D values of the Stochastic RSI indicator.
Parameters:
lengthRsi (simple int) : (simple int) Length for the RSI smoothing parameter calculation.
periodK (simple int) : (simple int) Number of bars for Stochastic calculation. (length).
smoothK (simple int) : (simple int) Number of bars for smoothing of the %K value (length).
periodD (simple int) : (simple int) Number of bars for smoothing of the %D value (length).
source (float) : (series int/float) Series of values to process. Optional. The default is `close`.
Returns: ( [float, float ]) A tuple of the slow %K and the %D moving average values.
supertrend(factor, atrLength, wicks)
Calculates the values of the SuperTrend indicator with the ability to take candle wicks into account, rather than only the closing price.
Parameters:
factor (float) : (series int/float) Multiplier for the ATR value.
atrLength (simple int) : (simple int) Length for the ATR smoothing parameter calculation.
wicks (simple bool) : (simple bool) Condition to determine whether to take candle wicks into account when reversing trend, or to use the close price. Optional. Default is false.
Returns: ( [float, int ]) A tuple of the superTrend value and trend direction.
szo(source, length)
Calculates the value of the Sentiment Zone Oscillator.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
t3(source, length, vf)
Calculates the value of the Tilson Moving Average (T3).
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
vf (simple float) : (simple float) Volume factor. Affects the responsiveness.
Returns: (float) The Tilson moving average of the `source`.
t3Alt(source, length, vf)
An alternate Tilson Moving Average (T3) function to `t3()`, which allows a "series float" `length` argument.
Parameters:
source (float) : (series int/float) Series of values to process.
length (float) : (series int/float) Length for the smoothing parameter calculation.
vf (simple float) : (simple float) Volume factor. Affects the responsiveness.
Returns: (float) The Tilson moving average of the `source`.
tema(source, length)
Calculates the value of the Triple Exponential Moving Average (TEMA).
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The triple exponentially weighted moving average of the `source`.
tema2(source, length)
An alternate Triple Exponential Moving Average (TEMA) function to `tema()`, which allows a "series float" `length` argument.
Parameters:
source (float) : (series int/float) Series of values to process.
length (float) : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The triple exponentially weighted moving average of the `source`.
trima(source, length)
Calculates the value of the Triangular Moving Average (TRIMA).
Parameters:
source (float) : (series int/float) Series of values to process.
length (int) : (series int) Number of bars (length).
Returns: (float) The triangular moving average of the `source`.
trima2(src, length)
An alternate Triangular Moving Average (TRIMA) function to `trima()`, which allows a "series int" length argument.
Parameters:
src : (series int/float) Series of values to process.
length : (series int) Number of bars (length).
Returns: (float) The triangular moving average of the `src`.
trix(source, length, signalLength, exponential)
Calculates the values of the TRIX indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
signalLength (simple int) : (simple int) Length for smoothing the signal line.
exponential (simple bool) : (simple bool) Condition to determine whether exponential or simple smoothing is used. Optional. The default is `true` (exponential smoothing).
Returns: ( [float, float, float ]) A tuple of the TRIX value, the signal value, and the histogram.
uo(fastLen, midLen, slowLen)
Calculates the value of the Ultimate Oscillator.
Parameters:
fastLen (simple int) : (series int) Number of bars for the fast smoothing average (length).
midLen (simple int) : (series int) Number of bars for the middle smoothing average (length).
slowLen (simple int) : (series int) Number of bars for the slow smoothing average (length).
Returns: (float) The oscillator value.
vhf(source, length)
Calculates the value of the Vertical Horizontal Filter.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Number of bars (length).
Returns: (float) The oscillator value.
vi(length)
Calculates the values of the Vortex Indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
Returns: ( [float, float ]) A tuple of the viPlus and viMinus values.
vzo(length)
Calculates the value of the Volume Zone Oscillator.
Parameters:
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
williamsFractal(period)
Detects Williams Fractals.
Parameters:
period (int) : (series int) Number of bars (length).
Returns: ( [bool, bool ]) A tuple of an up fractal and down fractal. Variables are true when detected.
wpo(length)
Calculates the value of the Wave Period Oscillator.
Parameters:
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
█ v7, Nov. 2, 2023
This version includes the following new and updated functions:
atr2(length)
An alternate ATR function to the `ta.atr()` built-in, which allows a "series float" `length` argument.
Parameters:
length (float) : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The ATR value.
changePercent(newValue, oldValue)
Calculates the percentage difference between two distinct values.
Parameters:
newValue (float) : (series int/float) The current value.
oldValue (float) : (series int/float) The previous value.
Returns: (float) The percentage change from the `oldValue` to the `newValue`.
donchian(length)
Calculates the values of a Donchian Channel using `high` and `low` over a given `length`.
Parameters:
length (int) : (series int) Number of bars (length).
Returns: ( [float, float, float ]) A tuple containing the channel high, low, and median, respectively.
highestSince(cond, source)
Tracks the highest value of a series since the last occurrence of a condition.
Parameters:
cond (bool) : (series bool) A condition which, when `true`, resets the tracking of the highest `source`.
source (float) : (series int/float) Series of values to process. Optional. The default is `high`.
Returns: (float) The highest `source` value since the last time the `cond` was `true`.
lowestSince(cond, source)
Tracks the lowest value of a series since the last occurrence of a condition.
Parameters:
cond (bool) : (series bool) A condition which, when `true`, resets the tracking of the lowest `source`.
source (float) : (series int/float) Series of values to process. Optional. The default is `low`.
Returns: (float) The lowest `source` value since the last time the `cond` was `true`.
relativeVolume(length, anchorTimeframe, isCumulative, adjustRealtime)
Calculates the volume since the last change in the time value from the `anchorTimeframe`, the historical average volume using bars from past periods that have the same relative time offset as the current bar from the start of its period, and the ratio of these volumes. The volume values are cumulative by default, but can be adjusted to non-accumulated with the `isCumulative` parameter.
Parameters:
length (simple int) : (simple int) The number of periods to use for the historical average calculation.
anchorTimeframe (simple string) : (simple string) The anchor timeframe used in the calculation. Optional. Default is "D".
isCumulative (simple bool) : (simple bool) If `true`, the volume values will be accumulated since the start of the last `anchorTimeframe`. If `false`, values will be used without accumulation. Optional. The default is `true`.
adjustRealtime (simple bool) : (simple bool) If `true`, estimates the cumulative value on unclosed bars based on the data since the last `anchor` condition. Optional. The default is `false`.
Returns: ( [float, float, float ]) A tuple of three float values. The first element is the current volume. The second is the average of volumes at equivalent time offsets from past anchors over the specified number of periods. The third is the ratio of the current volume to the historical average volume.
rma2(source, length)
An alternate RMA function to the `ta.rma()` built-in, which allows a "series float" `length` argument.
Parameters:
source (float) : (series int/float) Series of values to process.
length (float) : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The rolling moving average of the `source`.
supertrend2(factor, atrLength, wicks)
An alternate SuperTrend function to `supertrend()`, which allows a "series float" `atrLength` argument.
Parameters:
factor (float) : (series int/float) Multiplier for the ATR value.
atrLength (float) : (series int/float) Length for the ATR smoothing parameter calculation.
wicks (simple bool) : (simple bool) Condition to determine whether to take candle wicks into account when reversing trend, or to use the close price. Optional. Default is `false`.
Returns: ( [float, int ]) A tuple of the superTrend value and trend direction.
vStop(source, atrLength, atrFactor)
Calculates an ATR-based stop value that trails behind the `source`. Can serve as a possible stop-loss guide and trend identifier.
Parameters:
source (float) : (series int/float) Series of values that the stop trails behind.
atrLength (simple int) : (simple int) Length for the ATR smoothing parameter calculation.
atrFactor (float) : (series int/float) The multiplier of the ATR value. Affects the maximum distance between the stop and the `source` value. A value of 1 means the maximum distance is 100% of the ATR value. Optional. The default is 1.
Returns: ( [float, bool ]) A tuple of the volatility stop value and the trend direction as a "bool".
vStop2(source, atrLength, atrFactor)
An alternate Volatility Stop function to `vStop()`, which allows a "series float" `atrLength` argument.
Parameters:
source (float) : (series int/float) Series of values that the stop trails behind.
atrLength (float) : (series int/float) Length for the ATR smoothing parameter calculation.
atrFactor (float) : (series int/float) The multiplier of the ATR value. Affects the maximum distance between the stop and the `source` value. A value of 1 means the maximum distance is 100% of the ATR value. Optional. The default is 1.
Returns: ( [float, bool ]) A tuple of the volatility stop value and the trend direction as a "bool".
Removed Functions:
allTimeHigh(src)
Tracks the highest value of `src` from the first historical bar to the current bar.
allTimeLow(src)
Tracks the lowest value of `src` from the first historical bar to the current bar.
trima2(src, length)
An alternate Triangular Moving Average (TRIMA) function to `trima()`, which allows a
"series int" length argument.
[UTILS] Unit Testing FrameworkTL;DR
This script doesn't provide any buy/sell signals.
This script won't make you profitable implicitly.
This script is intended for utility function testing, library testing, custom assertions.
It is free and open-source.
Introduction
About the idea: is not exclusive, programmers tend to use this method a lot and for a long time.
The point is to ensure that parts of a software, "units" (i.e modules, functions, procedures, class methods etc), work as they should, meet they design and behave as intended. That's why we use the term "Unit testing".
In PineScript we don't have a lot of entities mentioned above yet. What we have are functions. For example, a function that sums numbers should return a number, a particular sum. Or a professor wrote a function that calculates something or whatever. He and you want to be sure that the function works as expected and further code changes (refactoring) won't break its behaviour. What the professor needs to do is to write unit tests for his function/library of functions. And what you need to do is to check if the professor wrote tests or not.
No tests = No code
- Total test-driven development
Ok, it is not so serious, but very important in software development. And I created a tool for that.
I tried to follow the APIs of testing tools/libs/frameworks I worked or work with: Jasmine (Javascript), Mocha/Chai (Javascript), Jest (Javascript), RSpec (Ruby), unittest (Python), pytest (Python) and others. Got something workable but it would be much easier to implement (and it would look much better) if PineScript had a higher-order functions feature.
API
_describe(suiteName: string)
A function to declare a test suite. Each suite with tests may have 2 statuses:
✔️ Passed
❌ Failed
A suite is considered to be failed if at least one of the specs in it has failed.
_it(specName: string, actual: any, expected: any)
A function to run a test. Each test may have 3 statuses:
✔️ Passed
❌ Failed
⛔ Skipped
Some examples:
_it("is a falsey value", 1 != 2, true)
_it("is not a number", na(something), true)
_it("should sum two integers", _sum(1, 2), 1)
_it("arrays are equal", _isEqual(array.from(1, 2), array.from(1, 2)), true)
Remember that both the 'actual' and 'expected' arguments must be of the same type.
And a group of _it() functions must be preceded by a _describe() declaration (see in the code).
_test(specName: string, actual: any, expected: any)
An alias for _it . Does the same thing.
_xit(specName: string, actual: any, expected: any)
A function to skip a particular test for a while. Doesn't make any comparisons, but the test will appear in the results as skipped.
This feature is unstable and may be removed in the future releases.
_xtest(specName: string, actual: any, expected: any)
An alias for _xit . Does the same thing.
_isEqual(id_1: array, id_2: array)
A function to compare two arrays for equality. Both arrays must be of the same type.
This function doesn't take into account the order of elements in each array. So arrays like (1, 2, 3) and (3, 2, 1) will be equal.
_isStrictEqual(id_1: array, id_2: array)
A function to compare two arrays for equality. Both arrays must be of the same type.
This function is a stricter version of _isEqual because it takes into account the order of elements in each array. So arrays like (1, 2, 3) and (3, 2, 1) won't be equal.
Usage
To use this script to test your library you need to do the following steps:
1) Copy all the code you see between line #5 and #282 (Unit Testing Framework Core)
2) Place the copied code at the very beginning of your script (but below study())
3) Start to write suites and tests where your code ends. That's it.
NOTE
The current version is 0.0.1 which means that a lot of things may be changed on the way to 1.0.0 - the first stable version.
Weighted Harrell-Davis Quantile Estimator with AbsoluteDeviation
QUANTILE ESTIMATORS
Weighted Harrell-Davis Quantile Estimator with Absolute Deviation Fences.
DISCLAIMER:
The Following indicator/code IS NOT intended to be a formal investment advice or recommendation by the author, nor should be construed as such. Users will be fully responsible by their use regarding their own trading vehicles/assets.
The following indicator was made for NON LUCRATIVE ACTIVITIES and must remain as is, following TradingView's regulations. Use of indicator and their code are published for work and knowledge sharing. All access granted over it, their use, copy or re-use should mention authorship(s) and origin(s).
WARNING NOTICE!
THE INCLUDED FUNCTION MUST BE CONSIDERED FOR TESTING. The models included in the indicator have been taken from open sources on the web and some of them has been modified by the author, problems could occur at diverse data sceneries, compiler version, or any other externality.
Purpose:
Weighted Quantiles or <> are quite difficult to find on must systems, also it's non-weighted approach are rarely used to estimate the location parameter of price distribution WICH IS NOT NORMAL, all this in favour of it's non-robust counterpart, the Arithmetic rolling Mean or <> and it's weighted variants like the WMA, VWAP, etc.
Also, a big drawback from this is that must statistics derived from Normal-Distribution parameter location (the Mean) definitely will not fit for an efficient, nor robust estimation for price distributions, so their moments like the standard deviation, kurtosis, skewness, etc. will not be the better tools to build derived algorithms or technical indicators among price/volume.
In an effort searching better statistical tools for price distributions, I found the excellent work of Andrey Akinshin that took me to port some of their Math research contributions for the compute benchmarking field , and bring it here at the TradingView ecosystem to take a shot at the price distribution crazy fields. For a better detail of what the weighted Harrell-Davis Quantile Estimator can do, who better than drink directly from the source at References:
References:
Weighted Quantile Estimators.
DoubleMAD outlier detector based on the Harrell-Davis quantile estimator.
Unbiased median absolute deviation based on the Harrell-Davis quantile estimator.
Quantile confidence intervals for weighted samples.
Licensing:
This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International Copyright (c) 2021 (CC BY-NC-SA 4.0)
Copyright's & Mentions:
The Gamma Functions & Beta Probability Density Functions C# implementations by the Math.NET Numerics, part of the Math.NET Project.
The Regularized Incomplete (Left) Beta Function C# implementation by the SAMTools, htslib project.
The Weighted Harrell-Davis Quantile estimator ; C# & R implementations by Andrey Akinshin.
External PineScript code, methods, support & consultancy by @PineCoders staff with special mention for:
+ "ma sorter ('sort by array' example)- JD" by @Duyck.
+ Porting, mods, compilation and debugging for this script by @XeL_Arjona for the TradingView's @PineCoders community.
Pinescript - Common Label & Line Array Functions Library by RRBPinescript - Common Label & Line Array Functions Library by RagingRocketBull 2021
Version 1.0
This script provides a library of common array functions for arrays of label and line objects with live testing of all functions.
Using this library you can easily create, update, delete, join label/line object arrays, and get/set properties of individual label/line object array items.
You can find the full list of supported label/line array functions below.
There are several libraries:
- Common String Functions Library
- Standard Array Functions Library
- Common Fixed Type Array Functions Library
- Common Label & Line Array Functions Library
- Common Variable Type Array Functions Library
Features:
- 30 array functions in categories create/update/delete/join/get/set with support for both label/line objects (45+ including all implementations)
- Create, Update label/line object arrays from list/array params
- GET/SET properties of individual label/line array items by index
- Join label/line objects/arrays into a single string for output
- Supports User Input of x,y coords of 5 different types: abs/rel/rel%/inc/inc% list/array, auto transforms x,y input into list/array based on type, base and xloc, translates rel into abs bar indexes
- Supports User Input of lists with shortened names of string properties, auto expands all standard string properties to their full names for use in functions
- Live Output for all/selected functions based on User Input. Test any function for possible errors you may encounter before using in script.
- Output filters: hide all excluded and show only allowed functions using a list of function names
- Output Panel customization options: set custom style, color, text size, and line spacing
Usage:
- select create function - create label/line arrays from lists or arrays (optional). Doesn't affect the update functions. The only change in output should be function name regardless of the selected implementation.
- specify num_objects for both label/line arrays (default is 7)
- specify common anchor point settings x,y base/type for both label/line arrays and GET/SET items in Common Settings
- fill lists with items to use as inputs for create label/line array functions in Create Label/Line Arrays section
- specify label/line array item index and properties to SET in corresponding sections
- select label/line SET function to see the changes applied live
Code Structure:
- translate x,y depending on x,y type, base and xloc as specified in UI (required for all functions)
- expand all shortened standard property names to full names (required for create/update* from arrays and set* functions, not needed for create/update* from lists) to prevent errors in label.new and line.new
- create param arrays from string lists (required for create/update* from arrays and set* functions, not needed for create/update* from lists)
- create label/line array from string lists (property names are auto expanded) or param arrays (requires already expanded properties)
- update entire label/line array or
- get/set label/line array item properties by index
Transforming/Expanding Input values:
- for this script to work on any chart regardless of price/scale, all x*,y* are specified as % increase relative to x0,y0 base levels by default, but user can enter abs x,price values specific for that chart if necessary.
- all lists can be empty, contain 1 or several items, have the same/different lengths. Array Length = min(min(len(list*)), mum_objects) is used to create label/line objects. Missing list items are replaced with default property values.
- when a list contains only 1 item it is duplicated (label name/tooltip is also auto incremented) to match the calculated Array Length
- since this script processes user input, all x,y values must be translated to abs bar indexes before passing them to functions. Your script may provide all data internally and doesn't require this step.
- at first int x, float y arrays are created from user string lists, transformed as described below and returned as x,y arrays.
- translated x,y arrays can then be passed to create from arrays function or can be converted back to x,y string lists for the create from lists function if necessary.
- all translation logic is separated from create/update/set functions for the following reasons:
- to avoid redundant code/dependency on ext functions/reduce local scopes and to be able to translate everything only once in one place - should be faster
- to simplify internal logic of all functions
- because your script may provide all data internally without user input and won't need the translation step
- there are 5 types available for both x,y: abs, rel, rel%, inc, inc%. In addition to that, x can be: bar index or time, y is always price.
- abs - absolute bar index/time from start bar0 (x) or price (y) from 0, is >= 0
- rel - relative bar index/time from cur bar n (x) or price from y0 base level, is >= 0
- rel% - relative % increase of bar index/time (x) or price (y) from corresponding base level (x0 or y0), can be <=> 0
- inc - relative increment (step) for each new level of bar index/time (x) or price (y) from corresponding base level (x0 or y0), can be <=> 0
- inc% - relative % increment (% step) for each new level of bar index/time (x) or price (y) from corresponding base level (x0 or y0), can be <=> 0
- x base level >= 0
- y base level can be 0 (empty) or open, close, high, low of cur bar
- single item x1_list = "50" translates into:
- for x type abs: "50, 50, 50 ..." num_objects times regardless of xloc => x = 50
- for x type rel: "50, 50, 50 ... " num_objects times => x = x_base + 50
- for x type rel%: "50%, 50%, 50% ... " num_objects times => x_base * (1 + 0.5)
- for x type inc: "0, 50, 100 ... " num_objects times => x_base + 50 * i
- for x type inc%: "0%, 50%, 100% ... " num_objects times => x_base * (1 + 0.5 * i)
- when xloc = xloc.bar_index each rel*/inc* value in the above list is then subtracted from n: n - x to convert rel to abs bar index, values of abs type are not affected
- x1_list = "0, 50, 100, ..." of type rel is the same as "50" of type inc
- x1_list = "50, 50, 50, ..." of type abs/rel/rel% produces a sequence of the same values and can be shortened to just "50"
- single item y1_list = "2" translates into (ragardless of yloc):
- for y type abs: "2, 2, 2 ..." num_objects times => y = 2
- for y type rel: "2, 2, 2 ... " num_objects times => y = y_base + 2
- for y type rel%: "2%, 2%, 2% ... " num_objects times => y = y_base * (1 + 0.02)
- for y type inc: "0, 2, 4 ... " num_objects times => y = y_base + 2 * i
- for y type inc%: "0%, 2%, 4% ... " num_objects times => y = y_base * (1 + 0.02 * i)
- when yloc != yloc.price all calculated values above are simply ignored
- y1_list = "0, 2, 4" of type rel% is the same as "2" with type inc%
- y1_list = "2, 2, 2" of type abs/rel/rel% produces a sequence of the same values and can be shortened to just "2"
- you can enter shortened property names in lists. To lookup supported shortened names use corresponding dropdowns in Set Label/Line Array Item Properties sections
- all shortened standard property names must be expanded to full names (required for create/update* from arrays and set* functions, not needed for create/update* from lists) to prevent errors in label.new and line.new
- examples of shortened property names that can be used in lists: bar_index, large, solid, label_right, white, left, left, price
- expanded to their corresponding full names: xloc.bar_index, size.large, line.style_solid, label.style_label_right, color.white, text.align_left, extend.left, yloc.price
- all expanding logic is separated from create/update* from arrays and set* functions for the same reasons as above, and because param arrays already have different types, implying the use of final values.
- all expanding logic is included in the create/update* from lists functions because it seemed more natural to process string lists from user input directly inside the function, since they are already strings.
Creating Label/Line Objects:
- use study max_lines_count and max_labels_count params to increase the max number of label/line objects to 500 (+3) if necessary. Default number of label/line objects is 50 (+3)
- all functions use standard param sequence from methods in reference, except style always comes before colors.
- standard label/line.get* functions only return a few properties, you can't read style, color, width etc.
- label.new(na, na, "") will still create a label with x = n-301, y = NaN, text = "" because max default scope for a var is 300 bars back.
- there are 2 types of color na, label color requires color(na) instead of color_na to prevent error. text_color and line_color can be color_na
- for line to be visible both x1, x2 ends must be visible on screen, also when y1 == y2 => abs(x1 - x2) >= 2 bars => line is visible
- xloc.bar_index line uses abs x1, x2 indexes and can only be within 0 and n ends, where n <= 5000 bars (free accounts) or 10000 bars (paid accounts) limit, can't be plotted into the future
- xloc.bar_time line uses abs x1, x2 times, can't go past bar0 time but can continue past cur bar time into the future, doesn't have a length limit in bars.
- xloc.bar_time line with length = exact number of bars can be plotted only within bar0 and cur bar, can't be plotted into the future reliably because of future gaps due to sessions on some charts
- xloc.bar_index line can't be created on bar 0 with fixed length value because there's only 1 bar of horiz length
- it can be created on cur bar using fixed length x < n <= 5000 or
- created on bar0 using na and then assigned final x* values on cur bar using set_x*
- created on bar0 using n - fixed_length x and then updated on cur bar using set_x*, where n <= 5000
- default orientation of lines (for style_arrow* and extend) is from left to right (from bar 50 to bar 0), it reverses when x1 and x2 are swapped
- price is a function, not a line object property
Variable Type Arrays:
- you can't create an if/function that returns var type value/array - compiler uses strict types and doesn't allow that
- however you can assign array of any type to another array of any type creating an arr pointer of invalid type that must be reassigned to a matching array type before used in any expression to prevent error
- create_any_array2 uses this loophole to return an int_arr pointer of a var type array
- this works for all array types defined with/without var keyword and doesn't work for string arrays defined with var keyword for some reason
- you can't do this with var type vars, only var type arrays because arrays are pointers passed by reference, while vars are actual values passed by value.
- you can only pass a var type value/array param to a function if all functions inside support every type - otherwise error
- alternatively values of every type must be passed simultaneously and processed separately by corresponding if branches/functions supporting these particular types returning a common single type result
- get_var_types solves this problem by generating a list of dummy values of every possible type including the source type, tricking the compiler into allowing a single valid branch to execute without error, while ignoring all dummy results
Notes:
- uses Pinescript v3 Compatibility Framework
- uses Common String Functions Library, Common Fixed Type Array Functions Library, Common Variable Type Array Functions Library
- has to be a separate script to reduce the number of local scopes/compiled file size, can't be merged with another library.
- lets you live test all label/line array functions for errors. If you see an error - change params in UI
- if you see "Loop too long" error - hide/unhide or reattach the script
- if you see "Chart references too many candles" error - change x type or value between abs/rel*. This can happen on charts with 5000+ bars when a rel bar index x is passed to label.new or line.new instead of abs bar index n - x
- create/update_label/line_array* use string lists, while create/update_label/line_array_from_arrays* use array params to create label/line arrays. "from_lists" is dropped to shorten the names of the most commonly used functions.
- create_label/line_array2,4 are preferable, 5,6 are listed for pure demonstration purposes only - don't use them, they don't improve anything but dramatically increase local scopes/compiled file size
- for this reason you would mainly be using create/update_label/line_array2,4 for list params or create/update_label/line_array_from_arrays2 for array params
- all update functions are executed after each create as proof of work and can be disabled. Only create functions are required. Use update functions when necessary - when list/array params are changed by your script.
- both lists and array item properties use the same x,y_type, x,y_base from common settings
- doesn't use pagination, a single str contains all output
- why is this so complicated? What are all these functions for?
- this script merges standard label/line object methods with standard array functions to create a powerful set of label/line object array functions to simplify manipulation of these arrays.
- this library also extends the functionality of Common Variable Type Array Functions Library providing support for label/line types in var type array functions (any_to_str6, join_any_array5)
- creating arrays from either lists or arrays adds a level of flexibility that comes with complexity. It's very likely that in your script you'd have to deal with both string lists as input, and arrays internally, once everything is converted.
- processing user input, allowing customization and targeting for any chart adds a whole new layer of complexity, all inputs must be translated and expanded before used in functions.
- different function implementations can increase/reduce local scopes and compiled file size. Select a version that best suits your needs. Creating complex scripts often requires rewriting your code multiple times to fit the limits, every line matters.
P.S. Don't rely too much on labels, for too often they are fables.
List of functions*:
* - functions from other libraries are not listed
1. Join Functions
Labels
- join_label_object(label_, d1, d2)
- join_label_array(arr, d1, d2)
- join_label_array2(arr, d1, d2, d3)
Lines
- join_line_object(line_, d1, d2)
- join_line_array(arr, d1, d2)
- join_line_array2(arr, d1, d2, d3)
Any Type
- any_to_str6(arr, index, type)
- join_any_array4(arr, d1, d2, type)
- join_any_array5(arr, d, type)
2. GET/SET Functions
Labels
- label_array_get_text(arr, index)
- label_array_get_xy(arr, index)
- label_array_get_fields(arr, index)
- label_array_set_text(arr, index, str)
- label_array_set_xy(arr, index, x, y)
- label_array_set_fields(arr, index, x, y, str)
- label_array_set_all_fields(arr, index, x, y, str, xloc, yloc, label_style, label_color, text_color, text_size, text_align, tooltip)
- label_array_set_all_fields2(arr, index, x, y, str, xloc, yloc, label_style, label_color, text_color, text_size, text_align, tooltip)
Lines
- line_array_get_price(arr, index, bar)
- line_array_get_xy(arr, index)
- line_array_get_fields(arr, index)
- line_array_set_text(arr, index, width)
- line_array_set_xy(arr, index, x1, y1, x2, y2)
- line_array_set_fields(arr, index, x1, y1, x2, y2, width)
- line_array_set_all_fields(arr, index, x1, y1, x2, y2, xloc, extend, line_style, line_color, width)
- line_array_set_all_fields2(arr, index, x1, y1, x2, y2, xloc, extend, line_style, line_color, width)
3. Create/Update/Delete Functions
Labels
- delete_label_array(label_arr)
- create_label_array(list1, list2, list3, list4, list5, d)
- create_label_array2(x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- create_label_array3(x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- create_label_array4(x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- create_label_array5(x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- create_label_array6(x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- update_label_array2(label_arr, x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- update_label_array4(label_arr, x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- create_label_array_from_arrays2(x_arr, y_arr, str_arr, xloc_arr, yloc_arr, style_arr, color1_arr, color2_arr, size_arr, align_arr, tooltip_arr, d)
- create_label_array_from_arrays4(x_arr, y_arr, str_arr, xloc_arr, yloc_arr, style_arr, color1_arr, color2_arr, size_arr, align_arr, tooltip_arr, d)
- update_label_array_from_arrays2(label_arr, x_arr, y_arr, str_arr, xloc_arr, yloc_arr, style_arr, color1_arr, color2_arr, size_arr, align_arr, tooltip_arr, d)
Lines
- delete_line_array(line_arr)
- create_line_array(list1, list2, list3, list4, list5, list6, d)
- create_line_array2(x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- create_line_array3(x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- create_line_array4(x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- create_line_array5(x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- create_line_array6(x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- update_line_array2(line_arr, x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- update_line_array4(line_arr, x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- create_line_array_from_arrays2(x1_arr, y1_arr, x2_arr, y2_arr, xloc_arr, extend_arr, style_arr, color_arr, width_arr, d)
- update_line_array_from_arrays2(line_arr, x1_arr, y1_arr, x2_arr, y2_arr, xloc_arr, extend_arr, style_arr, color_arr, width_arr, d)
Pinescript - Standard Array Functions Library by RRBStandard Array Functions Library by RagingRocketBull 2021
Version 1.0
This script provides a library of every standard Pinescript array function for live testing with all supported array types.
You can find the full list of supported standard array functions below.
There are several libraries:
- Common String Functions Library
- Common Array Functions Library
- Standard Array Functions Library
Features:
- Supports all standard array functions (30+) with all possible array types* (* - except array.new* functions and label, line array types)
- Live Output for all/selected functions based on User Input. Test any function for possible errors you may encounter before using in script.
- Output filters: show errors, hide all excluded and show only allowed functions using a list of function names
- Console customization options: set custom text size, color, page length, line spacing
Notes:
- uses Pinescript v3 Compatibility Framework
- uses Common String Functions Library
- has to be a separate script to reduce the number of local scopes in Common Array Function Library, there's no way to merge these scripts into a single library.
- lets you live test all standard array functions for errors. If you see an error - change params in UI
- array types that are not supported by certain functions and producing a compilation error were disabled with "error" showing up as result
- if you see "Loop too long" error - hide/unhide or reattach the script
- doesn't use pagination, a single str contains all output
- for most array functions to work (except push), an array must be defined with at least 1 pre-existing dummy element 0.
- array.slice and array.fill require from_index < to_index otherwise error
- array.join only supports string arrays, and delimiter must be a const string, can't be var/input. Use join_any_array to join any array type into string. You can also use tostring() to join int, float arrays.
- array.sort only supports int, float arrays. Use sort_any_array from the Common Array Function Library to sort any array type.
- array.sort only sorts values, doesn't preserve indexes. Use sort_any_array from the Common Array Function Library to sort any array while preserving indexes.
- array.concat appends string arrays in reverse order, other array types are appended correctly
- array.covariance requires 2 int, float arrays of the same size
- tostring(flag) works only for internal bool vars, flag expression can't depend on any inputs of any type, use bool_to_str instead
- you can't create an if/function that returns var type value/array - compiler uses strict types and doesn't allow that
- however you can assign array of any type to another array of any type creating an arr pointer of invalid type that must be reassigned to a matching array type before used in any expression to prevent error
- source_array and create_any_array2 use this loophole to return an int_arr pointer of a var type array
- this works for all array types defined with/without var keyword. This doesn't work for string arrays defined with var keyword for some reason
- you can't do this with var type vars, this can be done only with var type arrays because they are pointers passed by reference, while vars are the actual values passed by value.
- wrapper functions solve the problem of returning var array types. This is the only way of doing it when the top level arr type is undefined.
- you can only pass a var type value/array param to a function if all functions inside support every type - otherwise error
- alternatively values of every type must be passed simultaneously and processed separately by corresponding if branches/functions supporting these particular types returning a common single result type
- get_var_types solves this problem by generating a list of dummy values of every possible type including the source type, allowing a single valid branch to execute without error
- examples of functions supporting all array types: array.size, array.get, array.push. Examples of functions with limited type support: array.sort, array.join, array.max, tostring
- unlike var params/global vars, you can modify array params and global arrays directly from inside functions using standard array functions, but you can't use := (it only works for local arrays)
- inside function always work with array.copy to prevent accidental array modification
- you can't compare arrays
- there's no na equivalent for arrays, na(arr) doesn't work
P.S. A wide array of skills calls for an even wider array of responsibilities
List of functions:
- array.avg(arr)
- array.clear(arr)
- array.concat(arr1, arr2)
- array.copy(arr)
- array.covariance(arr1, arr2)
- array.fill(arr, value, index_from, index_to)
- array.get(arr, index)
- array.includes(arr, value)
- array.indexof(arr, value)
- array.insert(arr, index, value)
- array.join(arr, delimiter)
- array.lastindexof(arr, value)
- array.max(arr)
- array.median(arr)
- array.min(arr)
- array.mode(arr)
- array.pop(arr)
- array.push(arr, value)
- array.range(arr)
- array.remove(arr, index)
- array.reverse(arr)
- array.set(arr, index, value)
- array.shift(arr)
- array.size(arr)
- array.slice(arr, index_from, index_to)
- array.sort(arr, order)
- array.standardize()
- array.stdev(arr)
- array.sum(arr)
- array.unshift(arr, value)
- array.variance(arr)
Pinescript - Common String Functions Library by RRBCommon String Functions Library by RagingRocketBull 2021
Version 1.0
Pinescript now has strong support for arrays with many powerful functions, but still lacks built-in string functions. Luckily you can easily process and manipulate strings using arrays.
This script provides a library of common string functions for everyday use, such as: indexOf, substr, replace, ascii_code, str_to_int etc. There are 100+ unique functions (130 including all implementations)
It should serve as building blocks to speed up the development of your custom scripts. You should also be able to learn how Pinescript arrays works and how you can process strings.
Similar libraries for Array and Statistical Functions are in the works. You can find the full list of functions below.
Features:
- 100+ unique string functions (130 including all implementations) in categories: lookup, testing, conversion, modification, extraction, type conversion, date and time, console output
- Live Output for all/selected functions based on User Input. Test any function before using in script.
- Live Unit Test Output for several functions based on pre-defined inputs.
- Output filters: show unique functions/all implementations, grouping
- Console customization options: set custom text size, color, page length
- Support for Pages - auto splits output into pages with fixed length, use pages in your scripts
- Several easy to use console output functions to speed up debugging/output.
WARNING:
- Compilation Time: 1 min
Notes:
- uses Pinescript v3 Compatibility Framework
- this script is packed to the max and sets a new record in testing of Pinescript's limits: 500 local scopes, 4000+ lines, 180kb+ source size. It's not possible to add more ifs/fors/functions without reducing functionality
- to fit the max limit of local scopes = 500 all ifs were replaced with ?: where possible, the number of function calls was reduced, some calls replaced with inline function code
- ifs are faster (especially when lots of them are used in a for cycle), more readable, but ifs/fors/functions increase local scopes (+1) and compiled file size, have max nesting limit = 10.
- ?: are slower (especially in for cycles), hard to read when nested, don't affect local scopes, reduce compiled file size, can't contain plots, for statements (break/continue) and sets of statements
- for most array functions to work (except push), an array must be defined with at least 1 pre-existing dummy element 0.
- if you see "String too long" error - enable Show Pages, reduce Max Chars Per Page < Max String Length limit = 4096.
- if you see "Loop too long" error - hide/unhide or reattach the script
- some functions have several implementations that can be faster/slower, use internal code/ext functions
- 1 is manual string processing using for cycles (array.get) and ext functions - provided in case you want to implement your own logic, may sometimes be slower
- 2 is a 2nd alternate implementation mostly done using built-in functions (array.indexof, array.slice, array.insert, array.remove, str.replace_all),
attempts to minimize local scopes and dependency on ext functions, should generally be faster
- 3 is a 3rd alternate (array.includes, array.fill) or a more advanced implementation (datetime3_str) with lots of params, giving you the most control over output
- most functions have dependencies, such as const names, global arrays, inputs, other functions.
P.S. Strings of Time may be closed unto themselves or have loose ends; they can vibrate, stretch, join or split.
Function Groups:
1. Char Functions
- repeat(str, num)
- ascii_char(code)
- ascii_code(char)
- is_digit(char)
- is_letter(char)
- digit_to_int(char)
- is_space_char(char)
2. Char Test and Lookup Functions
- char_at(str, pos)
- char_code_at(str, pos)
- indexOf_char(str, char)
- lastIndexOf_char(str, char)
- nth_indexOf_char(str, char, num)
- includes_char(str, char)
3. String Lookup Functions
- indexOf(str, target)
- lastIndexOf(str, target)
- nth_indexOf(str, target, num)
- indexesOf(str, target)
- numIndexesOf(str, target)
4. String Conversion Functions
- lowercase(str)
- uppercase(str)
5. String Modification and Extraction Functions
- split(str, separator)
- insert(str, pos, new_str)
- remove(str, pos, length)
- insert_char(str, pos, char)
- remove_char(str, pos)
- reverse(str)
- fill_char(str, char, start_pos, end_pos)
- replace(str, target, new_str)
- replace_first(str, target, new_str)
- replace_last(str, target, new_str)
- replace_nth(str, target, new_str, num)
- replace_left(str, new_str)
- replace_right(str, new_str)
- replace_middle(str, pos, new_str)
- left(str, num)
- right(str, num)
- first_char(str)
- last_char(str)
- truncate(str, max_len)
- truncate_middle2(str, trunc_str, pos, max_len)
- truncate_from2(str, trunc_str, pos, max_len, side)
- concat(str1, str2, trunc_str, max_len, mode)
- concat_from(str1, str2, trunc_str, max_len, side, mode)
- trim(str)
- substr(str, pos, length)
- substring(str, start_pos, end_pos)
- strip(str, mask, target, is_allowed)
- extract_groups(str)
- extract_numbers(str, d1, d2, mode)
- str_to_float(str, d1, d2)
- str_to_int(str)
- extract_ranges(str, d1, d2, d3, type)
6. String Test Functions
- includes(str, target)
- starts_with(str, target)
- ends_with(str, target)
- str_compare(str1, str2)
7. Type Conversion Functions
- tf_check2(tf)
- tf_to_mins()
- convert_tf(tf)
- period_to_mins(tf)
- convert_tf2(tf)
- convert_tf3(tf)
- bool_to_str(flag)
- get_src(src_str)
- get_size(size_str)
- get_style(style)
- get_bool(bool_str)
- get_int(str)
- get_float(str, d1, d2)
- get_color(str, def_color)
- color_tr2(col_str, transp)
- get_month(str)
- month_name(num, format)
- weekday_name(num, format)
- dayofweek_name(t)
8. Date and Time Functions
- date_str(t, d)
- time_str(t, d)
- datetime_str(t, d1, d2)
- date2_str(t, d, type)
- time2_str(t, d, type)
- datetime2_str(t, d1, d2, format1, format2)
- date3_str(t, template)
- time3_str(t, template)
- datetime3_str(t, template)
9. Console Output & Helper Functions
- echo1(con, str)
- echo2(x, y, con, str)
- echo3(v_shift, con, str, msg_color, text_size)
- echo4(x, y, con, str, msg_style, msg_color, text_size, text_align, msg_xloc)
- echo5(x, y, con, str, msg_style, msg_color, text_size, text_align, msg_xloc)
- echo6(x, y, con, str)
- echo7(v_shift, con, str, msg_color, text_size)
- echo8(x, y, con, str, msg_style, msg_color, text_size, text_align, msg_xloc)
- echo9(x, y, con, str, msg_style, msg_color, text_size, text_align, msg_xloc)
- new_page(str, line_str, trunc_str, header_str, footer_str, length, page_count, page, mode)