ObjectStackLibrary "ObjectStack"
init()
push()
push()
push()
push()
push()
nextIndex()
nextIndex()
nextIndex()
nextIndex()
nextIndex()
delete()
delete()
delete()
delete()
delete()
cleanOldest()
cleanOldest()
cleanOldest()
cleanOldest()
cleanOldest()
Indicators and strategies
BjCandlePatternsLibrary "BjCandlePatterns"
Patterns is a Japanese candlestick pattern recognition Library for developers. Functions here within detect viable setups in a variety of popular patterns. Please note some patterns are without filters such as comparisons to average candle sizing, or trend detection to allow the author more freedom.
doji(dojiSize, dojiWickSize) Detects "Doji" candle patterns
Parameters:
dojiSize : (float) The relationship of body to candle size (ie. body is 5% of total candle size). Default is 5.0 (5%)
dojiWickSize : (float) Maximum wick size comparative to the opposite wick. (eg. 2 = bottom wick must be less than or equal to 2x the top wick). Default is 2
Returns: (series bool) True when pattern detected
dLab(showLabel, labelColor, textColor) Produces "Doji" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
bullEngulf(maxRejectWick, mustEngulfWick) Detects "Bullish Engulfing" candle patterns
Parameters:
maxRejectWick : (float) Maximum rejection wick size.
The maximum wick size as a percentge of body size allowable for a top wick on the resolution candle of the pattern. 0.0 disables the filter.
eg. 50 allows a top wick half the size of the body. Default is 0% (Disables wick detection).
mustEngulfWick : (bool) input to only detect setups that close above the high prior effectively engulfing the candle in its entirety. Default is false
Returns: (series bool) True when pattern detected
bewLab(showLabel, labelColor, textColor) Produces "Bullish Engulfing" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
bearEngulf(maxRejectWick, mustEngulfWick) Detects "Bearish Engulfing" candle patterns
Parameters:
maxRejectWick : (float) Maximum rejection wick size.
The maximum wick size as a percentge of body size allowable for a bottom wick on the resolution candle of the pattern. 0.0 disables the filter.
eg. 50 allows a botom wick half the size of the body. Default is 0% (Disables wick detection).
mustEngulfWick : (bool) Input to only detect setups that close below the low prior effectively engulfing the candle in its entirety. Default is false
Returns: (series bool) True when pattern detected
bebLab(showLabel, labelColor, textColor) Produces "Bearish Engulfing" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
hammer(ratio, shadowPercent) Detects "Hammer" candle patterns
Parameters:
ratio : (float) The relationship of body to candle size (ie. body is 33% of total candle size). Default is 33%.
shadowPercent : (float) The maximum allowable top wick size as a percentage of body size. Default is 5%.
Returns: (series bool) True when pattern detected
hLab(showLabel, labelColor, textColor) Produces "Hammer" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
star(ratio, shadowPercent) Detects "Star" candle patterns
Parameters:
ratio : (float) The relationship of body to candle size (ie. body is 33% of total candle size). Default is 33%.
shadowPercent : (float) The maximum allowable bottom wick size as a percentage of body size. Default is 5%.
Returns: (series bool) True when pattern detected
ssLab(showLabel, labelColor, textColor) Produces "Star" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
dragonflyDoji() Detects "Dragonfly Doji" candle patterns
Returns: (series bool) True when pattern detected
ddLab(showLabel, labelColor) Produces "Dragonfly Doji" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
Returns: (series label) A label visible at the chart level intended for the title pattern
gravestoneDoji() Detects "Gravestone Doji" candle patterns
Returns: (series bool) True when pattern detected
gdLab(showLabel, labelColor, textColor) Produces "Gravestone Doji" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
tweezerBottom(closeUpperHalf) Detects "Tweezer Bottom" candle patterns
Parameters:
closeUpperHalf : (bool) input to only detect setups that close above the mid-point of the candle prior increasing its bullish tendancy. Default is false
Returns: (series bool) True when pattern detected
tbLab(showLabel, labelColor, textColor) Produces "Tweezer Bottom" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
tweezerTop(closeLowerHalf) Detects "TweezerTop" candle patterns
Parameters:
closeLowerHalf : (bool) input to only detect setups that close below the mid-point of the candle prior increasing its bearish tendancy. Default is false
Returns: (series bool) True when pattern detected
ttLab(showLabel, labelColor, textColor) Produces "TweezerTop" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
spinningTopBull(wickSize) Detects "Bullish Spinning Top" candle patterns
Parameters:
wickSize : (float) input to adjust detection of the size of the top wick/ bottom wick as a percent of total candle size. Default is 34%, which ensures the wicks are both larger than the body.
Returns: (series bool) True when pattern detected
stwLab(showLabel, labelColor, textColor) Produces "Bullish Spinning Top" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
spinningTopBear(wickSize) Detects "Bearish Spinning Top" candle patterns
Parameters:
wickSize : (float) input to adjust detection of the size of the top wick/ bottom wick as a percent of total candle size. Default is 34%, which ensures the wicks are both larger than the body.
Returns: (series bool) True when pattern detected
stbLab(showLabel, labelColor, textColor) Produces "Bearish Spinning Top" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
spinningTop(wickSize) Detects "Spinning Top" candle patterns
Parameters:
wickSize : (float) input to adjust detection of the size of the top wick/ bottom wick as a percent of total candle size. Default is 34%, which ensures the wicks are both larger than the body.
Returns: (series bool) True when pattern detected
stLab(showLabel, labelColor, textColor) Produces "Spinning Top" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
morningStar() Detects "Bullish Morning Star" candle patterns
Returns: (series bool) True when pattern detected
msLab(showLabel, labelColor, textColor) Produces "Bullish Morning Star" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
eveningStar() Detects "Bearish Evening Star" candle patterns
Returns: (series bool) True when pattern detected
esLab(showLabel, labelColor, textColor) Produces "Bearish Evening Star" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
haramiBull() Detects "Bullish Harami" candle patterns
Returns: (series bool) True when pattern detected
hwLab(showLabel, labelColor, textColor) Produces "Bullish Harami" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
haramiBear() Detects "Bearish Harami" candle patterns
Returns: (series bool) True when pattern detected
hbLab(showLabel, labelColor, textColor) Produces "Bearish Harami" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
haramiBullCross() Detects "Bullish Harami Cross" candle patterns
Returns: (series bool) True when pattern detected
hcwLab(showLabel, labelColor, textColor) Produces "Bullish Harami Cross" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
haramiBearCross() Detects "Bearish Harami Cross" candle patterns
Returns: (series bool) True when pattern detected
hcbLab(showLabel, labelColor) Produces "Bearish Harami Cross" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
Returns: (series label) A label visible at the chart level intended for the title pattern
marubullzu() Detects "Bullish Marubozu" candle patterns
Returns: (series bool) True when pattern detected
mwLab(showLabel, labelColor, textColor) Produces "Bullish Marubozu" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
marubearzu() Detects "Bearish Marubozu" candle patterns
Returns: (series bool) True when pattern detected
mbLab(showLabel, labelColor, textColor) Produces "Bearish Marubozu" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
abandonedBull() Detects "Bullish Abandoned Baby" candle patterns
Returns: (series bool) True when pattern detected
abwLab(showLabel, labelColor, textColor) Produces "Bullish Abandoned Baby" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
abandonedBear() Detects "Bearish Abandoned Baby" candle patterns
Returns: (series bool) True when pattern detected
abbLab(showLabel, labelColor, textColor) Produces "Bearish Abandoned Baby" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
piercing() Detects "Piercing" candle patterns
Returns: (series bool) True when pattern detected
pLab(showLabel, labelColor, textColor) Produces "Piercing" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
darkCloudCover() Detects "Dark Cloud Cover" candle patterns
Returns: (series bool) True when pattern detected
dccLab(showLabel, labelColor, textColor) Produces "Dark Cloud Cover" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
tasukiBull() Detects "Upside Tasuki Gap" candle patterns
Returns: (series bool) True when pattern detected
utgLab(showLabel, labelColor, textColor) Produces "Upside Tasuki Gap" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
tasukiBear() Detects "Downside Tasuki Gap" candle patterns
Returns: (series bool) True when pattern detected
dtgLab(showLabel, labelColor, textColor) Produces "Downside Tasuki Gap" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
risingThree() Detects "Rising Three Methods" candle patterns
Returns: (series bool) True when pattern detected
rtmLab(showLabel, labelColor, textColor) Produces "Rising Three Methods" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
fallingThree() Detects "Falling Three Methods" candle patterns
Returns: (series bool) True when pattern detected
ftmLab(showLabel, labelColor, textColor) Produces "Falling Three Methods" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
risingWindow() Detects "Rising Window" candle patterns
Returns: (series bool) True when pattern detected
rwLab(showLabel, labelColor, textColor) Produces "Rising Window" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
fallingWindow() Detects "Falling Window" candle patterns
Returns: (series bool) True when pattern detected
fwLab(showLabel, labelColor, textColor) Produces "Falling Window" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
kickingBull() Detects "Bullish Kicking" candle patterns
Returns: (series bool) True when pattern detected
kwLab(showLabel, labelColor, textColor) Produces "Bullish Kicking" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
kickingBear() Detects "Bearish Kicking" candle patterns
Returns: (series bool) True when pattern detected
kbLab(showLabel, labelColor, textColor) Produces "Bearish Kicking" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
lls(ratio) Detects "Long Lower Shadow" candle patterns
Parameters:
ratio : (float) A relationship of the lower wick to the overall candle size expressed as a percent. Default is 75%
Returns: (series bool) True when pattern detected
llsLab(showLabel, labelColor, textColor) Produces "Long Lower Shadow" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
lus(ratio) Detects "Long Upper Shadow" candle patterns
Parameters:
ratio : (float) A relationship of the upper wick to the overall candle size expressed as a percent. Default is 75%
Returns: (series bool) True when pattern detected
lusLab(showLabel, labelColor, textColor) Produces "Long Upper Shadow" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
bullNeck() Detects "Bullish On Neck" candle patterns
Returns: (series bool) True when pattern detected
nwLab(showLabel, labelColor, textColor) Produces "Bullish On Neck" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
bearNeck() Detects "Bearish On Neck" candle patterns
Returns: (series bool) True when pattern detected
nbLab(showLabel, labelColor, textColor) Produces "Bearish On Neck" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
soldiers(wickSize) Detects "Three White Soldiers" candle patterns
Parameters:
wickSize : (float) Maximum allowable top wick size throughout pattern expressed as a percent of total candle height. Default is 5%
Returns: (series bool) True when pattern detected
wsLab(showLabel, labelColor, textColor) Produces "Three White Soldiers" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
crows(wickSize) Detects "Three Black Crows" candle patterns
Parameters:
wickSize : (float) Maximum allowable bottom wick size throughout pattern expressed as a percent of total candle height. Default is 5%
Returns: (series bool) True when pattern detected
bcLab(showLabel, labelColor, textColor) Produces "Three Black Crows" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
triStarBull() Detects "Bullish Tri-Star" candle patterns
Returns: (series bool) True when pattern detected
tswLab(showLabel, labelColor, textColor) Produces "Bullish Tri-Star" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
triStarBear() Detects "Bearish Tri-Star" candle patterns
Returns: (series bool) True when pattern detected
tsbLab(showLabel, labelColor, textColor) Produces "Bearish Tri-Star" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
wrap(cond, barsBack, borderColor, bgcolor) Produces a box wrapping the highs and lows over the look back.
Parameters:
cond : (series bool) Condition under which to draw the box.
barsBack : (series int) the number of bars back to begin drawing the box.
borderColor : (series color) Color of the four borders. Optional. The default is color.gray.
bgcolor : (series color) Background color of the box. Optional. The default is color.gray.
Returns: (series box) A box who's top and bottom are above and below the highest and lowest points over the lookback
topWick() returns the top wick size of the current candle
Returns: (series float) A value equivelent to the distance from the top of the candle body to its high
bottomWick() returns the bottom wick size of the current candle
Returns: (series float) A value equivelent to the distance from the bottom of the candle body to its low
body() returns the body size of the current candle
Returns: (series float) A value equivelent to the distance between the top and the bottom of the candle body
highestBody() returns the highest body of the current candle
Returns: (series float) A value equivelent to the highest body, whether it is the open or the close
lowestBody() returns the lowest body of the current candle
Returns: (series float) A value equivelent to the highest body, whether it is the open or the close
barRange() returns the height of the current candle
Returns: (series float) A value equivelent to the distance between the high and the low of the candle
bodyPct() returns the body size as a percent
Returns: (series float) A value equivelent to the percentage of body size to the overall candle size
midBody() returns the price of the mid-point of the candle body
Returns: (series float) A value equivelent to the center point of the distance bewteen the body low and the body high
bodyupGap() returns true if there is a gap up between the real body of the current candle in relation to the candle prior
Returns: (series bool) true if there is a gap up and no overlap in the real bodies of the current candle and the preceding candle
bodydwnGap() returns true if there is a gap down between the real body of the current candle in relation to the candle prior
Returns: (series bool) true if there is a gap down and no overlap in the real bodies of the current candle and the preceding candle
gapUp() returns true if there is a gap down between the real body of the current candle in relation to the candle prior
Returns: (series bool) true if there is a gap down and no overlap in the real bodies of the current candle and the preceding candle
gapDwn() returns true if there is a gap down between the real body of the current candle in relation to the candle prior
Returns: (series bool) true if there is a gap down and no overlap in the real bodies of the current candle and the preceding candle
dojiBody() returns true if the candle body is a doji
Returns: (series bool) true if the candle body is a doji. Defined by a body that is 5% of total candle size
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)
LibraryCOT█ OVERVIEW
This library is a Pine programmer's tool that provides functions to access Commitment of Traders (COT) data for futures. Four of our scripts use it:
• Commitment of Traders: Legacy Metrics
• Commitment of Traders: Disaggregated Metrics
• Commitment of Traders: Financial Metrics
• Commitment of Traders: Total
If you do not program in Pine and want to use COT data, please see the indicators linked above.
█ CONCEPTS
Commitment of Traders (COT) data is tallied by the Commodity Futures Trading Commission (CFTC) , a US federal agency that oversees the trading of derivative markets such as futures in the US. It is weekly data that provides traders with information about open interest for an asset. The CFTC oversees derivative markets traded on different exchanges, so COT data is available for assets that can be traded on CBOT, CME, NYMEX, COMEX, and ICEUS.
Accessing COT data from a Pine script requires the generation of a ticker ID string for use with request.security() . The ticker string must be encoded in a special format that includes both CFTC and TradingView-specific content. The format of the ticker IDs is somewhat complex; this library's functions make their generation easier. Note that if you know the COT ticker ID string for specific data, you can enter it from the chart's "Symbol Search" dialog box.
A ticker for COT data in Pine has the following structure:
COT:__<_metricDirection><_metricType>
where an underscore prefixing a component name inside <> is only included if the component is not a null string, and:
Is a digit representing the type of the COT report the data comes from: "" for legacy COT data, "2" for disaggregated data and "3" for financial data.
Is a six digit code that represents a commodity. Example: wheat futures (root "ZW") have the code "001602".
Is either "F" if the report data should exclude Options data, or "FO" if such data is included.
Is the TradingView code of the metric. This library's `metricNameAndDirectionToTicker()` function creates both
the and components of a COT ticker from the metric names and directions listed in the above chart.
The different metrics are explained in the CFTC's Explanatory Notes .
Is the direction of the metric: "Long", "Short", "Spreading" or "No direction".
Not all directions are applicable to all metrics. The valid ones are listed next to each metric in the above chart.
Is the type of the metric, possible values are "All", "Old" and "Other".
The difference between the types is explained in the "Old and Other Futures" section of the CFTC's Explanatory Notes .
As an example, the Legacy report Open Interest data for ZW futures (options included) in the old standard has the ticker "COT:001602_FO_OI_OLD". The same data using the current standard without futures has the ticker "COT:001602_F_OI".
█ USING THE LIBRARY
The first functions in the library are helper functions that generate components of a COT ticker ID. The last function, `COTTickerid()`, is the one that generates the full ticker ID string by calling some of the helper functions. We use it like this in our example:
exampleTicker = COTTickerid(
COTType = "Legacy",
CFTCCode = convertRootToCOTCode("Auto"),
includeOptions = false,
metricName = "Open Interest",
metricDirection = "No direction",
metricType = "All")
This library's chart displays the valid values for the `metricName` and `metricDirection` arguments. They vary for each of the three types of COT data (the `COTType` argument). The chart also displays the COT ticker ID string in the `exampleTicker` variable.
Look first. Then leap.
The library's functions are:
rootToCFTCCode(root)
Accepts a futures root and returns the relevant CFTC code.
Parameters:
root : Root prefix of the future's symbol, e.g. "ZC" for "ZC1!"" or "ZCU2021".
Returns: The part of a COT ticker corresponding to `root`, or "" if no CFTC code exists for the `root`.
currencyToCFTCCode(curr)
Converts a currency string to its corresponding CFTC code.
Parameters:
curr : Currency code, e.g., "USD" for US Dollar.
Returns: The corresponding to the currency, if one exists.
optionsToTicker(includeOptions)
Returns the part of a COT ticker using the `includeOptions` value supplied, which determines whether options data is to be included.
Parameters:
includeOptions : A "bool" value: 'true' if the symbol should include options and 'false' otherwise.
Returns: The part of a COT ticker: "FO" for data that includes options and "F" for data that doesn't.
metricNameAndDirectionToTicker(metricName, metricDirection)
Returns a string corresponding to a metric name and direction, which is one component required to build a valid COT ticker ID.
Parameters:
metricName : One of the metric names listed in this library's chart. Invalid values will cause a runtime error.
metricDirection : Metric direction. Possible values are: "Long", "Short", "Spreading", and "No direction".
Valid values vary with metrics. Invalid values will cause a runtime error.
Returns: The part of a COT ticker ID string, e.g., "OI_OLD" for "Open Interest" and "No direction",
or "TC_L" for "Traders Commercial" and "Long".
typeToTicker(metricType)
Converts a metric type into one component required to build a valid COT ticker ID.
See the "Old and Other Futures" section of the CFTC's Explanatory Notes for details on types.
Parameters:
metricType : Metric type. Accepted values are: "All", "Old", "Other".
Returns: The part of a COT ticker.
convertRootToCOTCode(mode, convertToCOT)
Depending on the `mode`, returns a CFTC code using the chart's symbol or its currency information when `convertToCOT = true`.
Otherwise, returns the symbol's root or currency information. If no COT data exists, a runtime error is generated.
Parameters:
mode : A string determining how the function will work. Valid values are:
"Root": the function extracts the futures symbol root (e.g. "ES" in "ESH2020") and looks for its CFTC code.
"Base currency": the function extracts the first currency in a pair (e.g. "EUR" in "EURUSD") and looks for its CFTC code.
"Currency": the function extracts the quote currency ("JPY" for "TSE:9984" or "USDJPY") and looks for its CFTC code.
"Auto": the function tries the first three modes (Root -> Base Currency -> Currency) until a match is found.
convertToCOT : "bool" value that, when `true`, causes the function to return a CFTC code.
Otherwise, the root or currency information is returned. Optional. The default is `true`.
Returns: If `convertToCOT` is `true`, the part of a COT ticker ID string.
If `convertToCOT` is `false`, the root or currency extracted from the current symbol.
COTTickerid(COTType, CTFCCode, includeOptions, metricName, metricDirection, metricType)
Returns a valid TradingView ticker for the COT symbol with specified parameters.
Parameters:
COTType : A string with the type of the report requested with the ticker, one of the following: "Legacy", "Disaggregated", "Financial".
CTFCCode : The for the asset, e.g., wheat futures (root "ZW") have the code "001602".
includeOptions : A boolean value. 'true' if the symbol should include options and 'false' otherwise.
metricName : One of the metric names listed in this library's chart.
metricDirection : Direction of the metric, one of the following: "Long", "Short", "Spreading", "No direction".
metricType : Type of the metric. Possible values: "All", "Old", and "Other".
Returns: A ticker ID string usable with `request.security()` to fetch the specified Commitment of Traders data.
█ AVAILABLE METRICS
Different COT types provide different metrics. The table of all metrics available for each of the types can be found below.
+------------------------------+------------------------+
| Legacy (COT) Metric Names | Directions |
+------------------------------+------------------------+
| Open Interest | No direction |
| Noncommercial Positions | Long, Short, Spreading |
| Commercial Positions | Long, Short |
| Total Reportable Positions | Long, Short |
| Nonreportable Positions | Long, Short |
| Traders Total | No direction |
| Traders Noncommercial | Long, Short, Spreading |
| Traders Commercial | Long, Short |
| Traders Total Reportable | Long, Short |
| Concentration Gross LT 4 TDR | Long, Short |
| Concentration Gross LT 8 TDR | Long, Short |
| Concentration Net LT 4 TDR | Long, Short |
| Concentration Net LT 8 TDR | Long, Short |
+------------------------------+------------------------+
+-----------------------------------+------------------------+
| Disaggregated (COT2) Metric Names | Directions |
+-----------------------------------+------------------------+
| Open Interest | No Direction |
| Producer Merchant Positions | Long, Short |
| Swap Positions | Long, Short, Spreading |
| Managed Money Positions | Long, Short, Spreading |
| Other Reportable Positions | Long, Short, Spreading |
| Total Reportable Positions | Long, Short |
| Nonreportable Positions | Long, Short |
| Traders Total | No Direction |
| Traders Producer Merchant | Long, Short |
| Traders Swap | Long, Short, Spreading |
| Traders Managed Money | Long, Short, Spreading |
| Traders Other Reportable | Long, Short, Spreading |
| Traders Total Reportable | Long, Short |
| Concentration Gross LE 4 TDR | Long, Short |
| Concentration Gross LE 8 TDR | Long, Short |
| Concentration Net LE 4 TDR | Long, Short |
| Concentration Net LE 8 TDR | Long, Short |
+-----------------------------------+------------------------+
+-------------------------------+------------------------+
| Financial (COT3) Metric Names | Directions |
+-------------------------------+------------------------+
| Open Interest | No Direction |
| Dealer Positions | Long, Short, Spreading |
| Asset Manager Positions | Long, Short, Spreading |
| Leveraged Funds Positions | Long, Short, Spreading |
| Other Reportable Positions | Long, Short, Spreading |
| Total Reportable Positions | Long, Short |
| Nonreportable Positions | Long, Short |
| Traders Total | No Direction |
| Traders Dealer | Long, Short, Spreading |
| Traders Asset Manager | Long, Short, Spreading |
| Traders Leveraged Funds | Long, Short, Spreading |
| Traders Other Reportable | Long, Short, Spreading |
| Traders Total Reportable | Long, Short |
| Concentration Gross LE 4 TDR | Long, Short |
| Concentration Gross LE 8 TDR | Long, Short |
| Concentration Net LE 4 TDR | Long, Short |
| Concentration Net LE 8 TDR | Long, Short |
+-------------------------------+------------------------+
FunctionBlackScholesLibrary "FunctionBlackScholes"
Some methods for the Black Scholes Options Model, which demonstrates several approaches to the valuation of a European call.
// reference:
// people.math.sc.edu
// people.math.sc.edu
asset_path(s0, mu, sigma, t1, n) Simulates the behavior of an asset price over time.
Parameters:
s0 : float, asset price at time 0.
mu : float, growth rate.
sigma : float, volatility.
t1 : float, time to expiry date.
n : int, time steps to expiry date.
Returns: option values at each equal timed step (0 -> t1)
binomial(s0, e, r, sigma, t1, m) Uses the binomial method for a European call.
Parameters:
s0 : float, asset price at time 0.
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
m : int, time steps to expiry date.
Returns: option value at time 0.
bsf(s0, t0, e, r, sigma, t1) Evaluates the Black-Scholes formula for a European call.
Parameters:
s0 : float, asset price at time 0.
t0 : float, time at which the price is known.
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
Returns: option value at time 0.
forward(e, r, sigma, t1, nx, nt, smax) Forward difference method to value a European call option.
Parameters:
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
nx : int, number of space steps in interval (0, L).
nt : int, number of time steps.
smax : float, maximum value of S to consider.
Returns: option values for the european call, float array of size ((nx-1) * (nt+1)).
mc(s0, e, r, sigma, t1, m) Uses Monte Carlo valuation on a European call.
Parameters:
s0 : float, asset price at time 0.
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
m : int, time steps to expiry date.
Returns: confidence interval for the estimated range of valuation.
ArrayExtLibrary "ArrayExt"
Array extensions
get(a, idx) Get element from the array at index, or na if index not found
Parameters:
a : The array
idx : The array index to get
Returns: The array item if exists or na
get(a, idx) Get element from the array at index, or na if index not found
Parameters:
a : The array
idx : The array index to get
Returns: The array item if exists or na
get(a, idx) Get element from the array at index, or na if index not found
Parameters:
a : The array
idx : The array index to get
Returns: The array item if exists or na
get(a, idx) Get element from the array at index, or na if index not found
Parameters:
a : The array
idx : The array index to get
Returns: The array item if exists or na
get(a, idx) Get element from the array at index, or na if index not found
Parameters:
a : The array
idx : The array index to get
Returns: The array item if exists or na
get(a, idx) Get element from the array at index, or na if index not found
Parameters:
a : The array
idx : The array index to get
Returns: The array item if exists or na
set(a, idx, val) Set array item at index, if array has no index at the specified index, the array is filled with na
Parameters:
a : The array
idx : The array index to set
val : The value to be set
set(a, idx, val) Set array item at index, if array has no index at the specified index, the array is filled with na
Parameters:
a : The array
idx : The array index to set
val : The value to be set
set(a, idx, val) Set array item at index, if array has no index at the specified index, the array is filled with na
Parameters:
a : The array
idx : The array index to set
val : The value to be set
set(a, idx, val) Set array item at index, if array has no index at the specified index, the array is filled with na
Parameters:
a : The array
idx : The array index to set
val : The value to be set
set(a, idx, val) Set array item at index, if array has no index at the specified index, the array is filled with na
Parameters:
a : The array
idx : The array index to set
val : The value to be set
set(a, idx, val) Set array item at index, if array has no index at the specified index, the array is filled with na
Parameters:
a : The array
idx : The array index to set
val : The value to be set
sar_taLevel: 3
Background
The Parabolic SAR is a technical indicator developed by J. Welles Wilder to determine the direction that an asset is moving. The indicator is also referred to as a stop and reverse system, which is abbreviated as SAR. It aims to identify potential reversals in the price movement of traded assets.
PINE v5 Version of SAR Library, which includes latest the Supertrend, Parabolic SAR, Gann Hilo activator, Chex indicators etc.
Function
This lib provides functions similar to SAR which can serve as a similar element for composite strategy. Parameters need to be tuned for the best performance and I will further inrish this collections.
Bonus,
If you can propose me a novel SAR source link, I would like to grant you one L4/L5 indicator with 2-month subscription for free.
Library "sar_ta"
tv_sar()
lucid_sar()
gl_activator()
ltb_sar()
chanex()
bjorgum_sar()
FunctionMinkowskiDistanceLibrary "FunctionMinkowskiDistance"
Method for Minkowski Distance,
The Minkowski distance or Minkowski metric is a metric in a normed vector space
which can be considered as a generalization of both the Euclidean distance and
the Manhattan distance.
It is named after the German mathematician Hermann Minkowski.
reference: en.wikipedia.org
double(point_ax, point_ay, point_bx, point_by, p_value) Minkowsky Distance for single points.
Parameters:
point_ax : float, x value of point a.
point_ay : float, y value of point a.
point_bx : float, x value of point b.
point_by : float, y value of point b.
p_value : float, p value, default=1.0(1: manhatan, 2: euclidean), does not support chebychev.
Returns: float
ndim(point_x, point_y, p_value) Minkowsky Distance for N dimensions.
Parameters:
point_x : float array, point x dimension attributes.
point_y : float array, point y dimension attributes.
p_value : float, p value, default=1.0(1: manhatan, 2: euclidean), does not support chebychev.
Returns: float
BE_CustomFx_LibraryLibrary "BE_CustomFx_Library"
A handful collection of regular functions, Custom Tools & Utility Functions could be used in regular Scripts. hope these functions can be understood by a non programmer like me too.
G_TextValOfNumber(ValueToConvert, RequiredDecimalPlaces, BeginingChar, EndChar) Function to return the String Value of Number with decimal precision with the prefix and suffix characters provided
Parameters:
ValueToConvert : = Number to Convert
RequiredDecimalPlaces : = No of Decimal values Required. supports to a max of 5 decimals else defaults to 2
BeginingChar : = Prefix character which is needed.
EndChar : = Suffix character which is needed.
Returns: Returns Out put with formated value of Given Number for the specified deicimal values with Prefix and suffix string
G_TradableValue(ValueToConvert, NeedCustomization, RequiredDecimalPlaces) Function to return the Tradable Value of Number
Parameters:
ValueToConvert : = Number to Convert
NeedCustomization : = set to 1 if you want to customize the decimal percision values. default is No customization needed, which provides output equalent to round_to_mintick
RequiredDecimalPlaces : = if NeedCustomization is set to 1 mention the decimal percision value required. max supported decimal is 5 else defaults to 2
Returns: Returns Out put with formated value of Given Number
G_TxtSizeForLables(SizeValue) Function to Get size Value for text values used in Lables
Parameters:
SizeValue : = auto, tiny, small, normal, large, huge. specify either of these values or default value Normal will be displayed as output
Returns: Returns Respective Text size
G_Reg_LineType(LineType) Function to Get Line Style Value for text values used in Lines
Parameters:
LineType : = 'solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)' or default line style 'dotted (┈)' will be the output
Returns: Returns Respective Line style
G_ShapeTypeForLables(ShapeType) Function to Get Shape Style Value for text values used in plot shapes
Parameters:
ShapeType : = 'XCross', 'Cross', 'Triangle Up', 'Triangle Down', 'Flag', 'Circle','Arrow Up', 'Arrow Down','Lable Up', 'Lable Down' or default shpae style Triangle Up will be the output
Returns: Returns Respective Shape style
G_Indicator_Val(string, float, int, int) Gets Output of the technical analyis indicator which has length Parameter. RSI, ATR, EMA, SMA, HMA, WMA, VWMA, 'CMO', 'MOM', 'ROC','VWAP'
Parameters:
string : IndicatorName to be specified
float : SrcVal for the TA indicator default is close
int : Length for the TA indicator
int : DecimalValue optional to specify if required formatted output with decimal percision
Returns: Value with the given parameters
G_CandleInfo(string, bool, float, bool) function to get Candle Informarion such as both wicksize, top wick size , bottom wick size, full candle size and body size in default points
Parameters:
string : WhatCandleInfo, string input with either of these options "Wick" , "TWick" , "BWick" , "Candle", "Body" , "BearfbVal", "BullfbVal" , "CandleOpen" ,"CandleClose", "CandleHigh" , "CandleLow", "BodyPct"
bool : RepaintingVersion, set to true if required data on the realtime bar else default is set to false
float : FibValueOfCandle, set the fibo value to extract fibvalue of the candle else default is set to 38.2%
bool : AccountforGaps, set to true if required data on considering the gap between previous and current bar else default is set to false
Returns: Returns Respective values for the candles
G_BullBearBarCount(int, int) Counts how many green & red bars have printed recently (ie. pullback count)
Parameters:
int : HowManyCandlesToCheck The lookback period to look back over
int : BullBear The color of the bar to count (1 = Bull, -1 = Bear), Open = close candles are ignored
Returns: The bar count of how many candles have retraced over the given lookback with specific candles
BarToStartYourCalculation(Int) function to get candle co-ordinate in order to use it further for calculating your analysis work . "Heart full Thanks to 3 Pine motivators (LonesomeTheBlue, Myank & Sriki) who helped me cracking this logic"
Parameters:
Int : SelectedCandleNumber (default=450) How many candles you would need to anlysie in your script from the right.
Returns: A boolean - output is returned to say the starting point and continue to diplay true for the future candles
isHammer(float, bool, 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)
bool : NeedRepainting (default=false) Specify True if you need them to calculate on the realtime bars
Returns: A boolean - true if the current bar matches the requirements of a hammer candle
isStar(float, bool, 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)
bool : NeedRepainting (default=false) Specify True if you need them to calculate on the realtime bars
Returns: A boolean - true if the current bar matches the requirements of a shooting star candle
isDoji(float, float, bool) Checks if the current bar is a doji candle based on the given parameters
Parameters:
float : _wickSize (default=1.5 times) The maximum allowed times can be top wick size compared to the bottom (and vice versa)
float : _bodySize (default= 5 percent to be mentioned as 0.05) The maximum body size as a percentage compared to the entire candle size
bool : NeedRepainting (default=false) Specify true if you need them to calculate on the realtime bars
Returns: A boolean - true if the current bar matches the requirements of a doji candle
isBullishEC(float, float, bool, 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?
bool : NeedRepainting (default=false) Specify True if you need them to calculate on the realtime bars
Returns: A boolean - true if the current bar matches the requirements of a bullish engulfing candle
isBearishEC(float, float, bool, 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?
bool : NeedRepainting (default=false) Specify True if you need them to calculate on the realtime bars
Returns: A boolean - true if the current bar matches the requirements of a bearish engulfing candle
Plot_TrendLineAtDegree(float, float, int, string, bool) helps you to plot the Trendlines based on the specified angle at the defined price to bar ratio
Parameters:
float : Degree (default=14) angle at which Trendline to be plot
float : price2bar_ratio (default=1e-10) The maximum rejection wick size compared to the body as a percentage
int : Bars2Plot (default=6) Does the engulfing candle require the wick to be engulfed as well?
string : LineStyle = 'solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)' or default line style 'dotted (┈)' will be the output
bool : PlotOnOpen_Close (default=false) Specify True if you need them to calculate on the Open\Close Values
Returns: plot the Trendlines based on the specified angle at the defined price to bar ratio
globalCurrently in PineScript you cannot modify global variables in functions because of scope limitations.
One way to work around that is to use arrays.
This Library simplifies the use of arrays as global variables to make your code look cleaner.
If you're coming from other programming languages, I'm sure you will come across this issue in your PineScript journey at some point.
------------------------------------
The code below will throw an error that says: Cannot modify global variable 'price' in function.
var price = 0.0
function() =>
price := 5.5
------------------------------------
To work around that you can do:
var price = array.new_float(1, 0.0)
function() =>
array.set(price, 0, 5.5)
But that code does not spark joy.
------------------------------------
So I bring to you the global library:
import marspumpkin/global/1
var price = global.init(0.0)
function() =>
global.set(price, 5.5)
Pivots libraryLibrary "Pivots"
TODO: add library description here
pivots(_type, _open, _high, _low, _clsoe) Calculates the pivot point and returns its value.
Parameters:
_type : Specifies the type of pivot point.
_open : The open price
_high : The high price
_low : The low price
_clsoe : The close price
Returns: Returns the value of the calculated pivot point as a tuple.
cpr(_high, _low, _clsoe) Calculate the Central Pivot Range
Parameters:
_high : The high price
_low : The low price
_clsoe : The close price
Returns: Returns the values as a tuple.
htf_ohlc(_htf) Calculate the HTF values
Parameters:
_htf : Resolution
Returns: Returns the values as a tuple.
regressLibrary "regress"
produces the slope (beta), y-intercept (alpha) and coefficient of determination for a linear regression
regress(x, y, len) regress: computes alpha, beta, and r^2 for a linear regression of y on x
Parameters:
x : the explaining (independent) variable
y : the dependent variable
len : use the most recent "len" values of x and y
Returns: : alpha is the x-intercept, beta is the slope, an r2 is the coefficient of determination
Note: the chart does not show anything, use the return values to compute model values in your own application, if you wish.
LukashereLibrary "Lukashere"
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
Percentual2nu()
getMA()
SymbolsTopMarketcap()
TitinhoIndicatorsLibraryOn this Library you cand find a shortcut for some indicators and just import them into your source.
Each indicator has its own input and output parameters and they are prety much self explanatory. :D
This is the list of the present indicators you can use with this library:
*Function_Adx()
*Function_Atr()
*Function_Mfi()
*Function_MovingAverage()
*Function_Sar()
*Function_Rsi()
*Function_StochasticRsi()
Have fun!!!
Ehlers_Super_SmootherThe 2 Pole and 3 Pole Super Smoother Filters were developed by John Ehlers and described in "Chapter 13: Super Smother" of his book Cybernetic Analysis for Stocks and Futures .
The 2 Pole Smoother is described as being a better approximation of price, whereas the 3 Pole Smoother has superior smoothing.
Library "Ehlers_Super_Smoother"
Provides the functions to calculate Double and Triple Exponentional Moving Averages (DEMA & TEMA)
twoPole(_source, _length) Calculates 2 Pole Ehlers Super Smoother Filter
Parameters:
_source : -> Open, Close, High, Low, etc ('close' is used if no argument is supplied)
_length : -> Ehlers Super Smoother length
Returns: 2 Pole Ehlers Super Smoothing to an input source at the specified input length
threePole(_source, _length) Calculates 3 Pole Ehlers Super Smoother Filter
Parameters:
_source : -> Open, Close, High, Low, etc ('close' is used if no argument is supplied)
_length : -> Ehlers Super Smoother length
Returns: 3 Pole Ehlers Super Smoothing to an input source at the specified input length
pandas_taLibrary "pandas_ta"
Level: 3
Background
Today is the first day of 2022 and happy new year every tradingviewers! May health and wealth go along with you all the time. I use this chance to publish my 1st PINE v5 lib : pandas_ta
This is not a piece of cake like thing, which cost me a lot of time and efforts to build this lib. Beyond 300 versions of this script was iterated in draft.
Function
Library "pandas_ta"
PINE v5 Counterpart of Pandas TA - A Technical Analysis Library in Python 3 at github.com
The Original Pandas Technical Analysis (Pandas TA) is an easy to use library that leverages the Pandas package with more than 130 Indicators and Utility functions and more than 60 TA Lib Candlestick Patterns.
I realized most of indicators except Candlestick Patterns because tradingview built-in Candlestick Patterns are even more powerful!
I use this to verify pandas_ta python version indicators for myself, but I realize that maybe many may need similar lib for pine v5 as well.
Function Brief Descriptions (Pls find details in script comments)
bton --> Binary to number
wcp --> Weighted Closing Price (WCP)
counter --> Condition counter
xbt --> Between
ebsw --> Even Better SineWave (EBSW)
ao --> Awesome Oscillator (AO)
apo --> Absolute Price Oscillator (APO)
xrf --> Dynamic shifted values
bias --> Bias (BIAS)
bop --> Balance of Power (BOP)
brar --> BRAR (BRAR)
cci --> Commodity Channel Index (CCI)
cfo --> Chande Forcast Oscillator (CFO)
cg --> Center of Gravity (CG)
cmo --> Chande Momentum Oscillator (CMO)
coppock --> Coppock Curve (COPC)
cti --> Correlation Trend Indicator (CTI)
dmi --> Directional Movement Index(DMI)
er --> Efficiency Ratio (ER)
eri --> Elder Ray Index (ERI)
fisher --> Fisher Transform (FISHT)
inertia --> Inertia (INERTIA)
kdj --> KDJ (KDJ)
kst --> 'Know Sure Thing' (KST)
macd --> Moving Average Convergence Divergence (MACD)
mom --> Momentum (MOM)
pgo --> Pretty Good Oscillator (PGO)
ppo --> Percentage Price Oscillator (PPO)
psl --> Psychological Line (PSL)
pvo --> Percentage Volume Oscillator (PVO)
qqe --> Quantitative Qualitative Estimation (QQE)
roc --> Rate of Change (ROC)
rsi --> Relative Strength Index (RSI)
rsx --> Relative Strength Xtra (rsx)
rvgi --> Relative Vigor Index (RVGI)
slope --> Slope
smi --> SMI Ergodic Indicator (SMI)
sqz* --> Squeeze (SQZ) * NOTE: code sufferred from very strange error, code was commented.
sqz_pro --> Squeeze PRO(SQZPRO)
xfl --> Condition filter
stc --> Schaff Trend Cycle (STC)
stoch --> Stochastic (STOCH)
stochrsi --> Stochastic RSI (STOCH RSI)
trix --> Trix (TRIX)
tsi --> True Strength Index (TSI)
uo --> Ultimate Oscillator (UO)
willr --> William's Percent R (WILLR)
alma --> Arnaud Legoux Moving Average (ALMA)
xll --> Dynamic rolling lowest values
dema --> Double Exponential Moving Average (DEMA)
ema --> Exponential Moving Average (EMA)
fwma --> Fibonacci's Weighted Moving Average (FWMA)
hilo --> Gann HiLo Activator(HiLo)
hma --> Hull Moving Average (HMA)
hwma --> HWMA (Holt-Winter Moving Average)
ichimoku --> Ichimoku Kinkō Hyō (ichimoku)
jma --> Jurik Moving Average Average (JMA)
kama --> Kaufman's Adaptive Moving Average (KAMA)
linreg --> Linear Regression Moving Average (linreg)
mgcd --> McGinley Dynamic Indicator
rma --> wildeR's Moving Average (RMA)
sinwma --> Sine Weighted Moving Average (SWMA)
ssf --> Ehler's Super Smoother Filter (SSF) © 2013
supertrend --> Supertrend (supertrend)
xsa --> X simple moving average
swma --> Symmetric Weighted Moving Average (SWMA)
t3 --> Tim Tillson's T3 Moving Average (T3)
tema --> Triple Exponential Moving Average (TEMA)
trima --> Triangular Moving Average (TRIMA)
vidya --> Variable Index Dynamic Average (VIDYA)
vwap --> Volume Weighted Average Price (VWAP)
vwma --> Volume Weighted Moving Average (VWMA)
wma --> Weighted Moving Average (WMA)
zlma --> Zero Lag Moving Average (ZLMA)
entropy --> Entropy (ENTP)
kurtosis --> Rolling Kurtosis
skew --> Rolling Skew
xev --> Condition all
zscore --> Rolling Z Score
adx --> Average Directional Movement (ADX)
aroon --> Aroon & Aroon Oscillator (AROON)
chop --> Choppiness Index (CHOP)
xex --> Condition any
cksp --> Chande Kroll Stop (CKSP)
dpo --> Detrend Price Oscillator (DPO)
long_run --> Long Run
psar --> Parabolic Stop and Reverse (psar)
short_run --> Short Run
vhf --> Vertical Horizontal Filter (VHF)
vortex --> Vortex
accbands --> Acceleration Bands (ACCBANDS)
atr --> Average True Range (ATR)
bbands --> Bollinger Bands (BBANDS)
donchian --> Donchian Channels (DC)
kc --> Keltner Channels (KC)
massi --> Mass Index (MASSI)
natr --> Normalized Average True Range (NATR)
pdist --> Price Distance (PDIST)
rvi --> Relative Volatility Index (RVI)
thermo --> Elders Thermometer (THERMO)
ui --> Ulcer Index (UI)
ad --> Accumulation/Distribution (AD)
cmf --> Chaikin Money Flow (CMF)
efi --> Elder's Force Index (EFI)
ecm --> Ease of Movement (EOM)
kvo --> Klinger Volume Oscillator (KVO)
mfi --> Money Flow Index (MFI)
nvi --> Negative Volume Index (NVI)
obv --> On Balance Volume (OBV)
pvi --> Positive Volume Index (PVI)
dvdi --> Dual Volume Divergence Index (DVDI)
xhh --> Dynamic rolling highest values
pvt --> Price-Volume Trend (PVT)
Remarks
I also incorporated func descriptions and func test script in commented mode, you can test the functino with the embedded test script and modify them as you wish.
This is a Level 3 free and open source indicator library.
Feedbacks are appreciated.
This is not the end of pandas_ta lib publication, but it is start point with pine v5 lib function and I will add more and more funcs into this lib for my own indicators.
Function Name List:
bton()
wcp()
count()
xbt()
ebsw()
ao()
apo()
xrf()
bias()
bop()
brar()
cci()
cfo()
cg()
cmo()
coppock()
cti()
dmi()
er()
eri()
fisher()
inertia()
kdj()
kst()
macd()
mom()
pgo()
ppo()
psl()
pvo()
qqe()
roc()
rsi()
rsx()
rvgi()
slope()
smi()
sqz_pro()
xfl()
stc()
stoch()
stochrsi()
trix()
tsi()
uo()
willr()
alma()
wcx()
xll()
dema()
ema()
fwma()
hilo()
hma()
hwma()
ichimoku()
jma()
kama()
linreg()
mgcd()
rma()
sinwma()
ssf()
supertrend()
xsa()
swma()
t3()
tema()
trima()
vidya()
vwap()
vwma()
wma()
zlma()
entropy()
kurtosis()
skew()
xev()
zscore()
adx()
aroon()
chop()
xex()
cksp()
dpo()
long_run()
psar()
short_run()
vhf()
vortex()
accbands()
atr()
bbands()
donchian()
kc()
massi()
natr()
pdist()
rvi()
thermo()
ui()
ad()
cmf()
efi()
ecm()
kvo()
mfi()
nvi()
obv()
pvi()
dvdi()
xhh()
pvt()
TimeLockedMALibrary "TimeLockedMA"
Library & function(s) which generates a moving average that stays locked to users desired time preference.
TODO - Add functionality for more moving average types. IE: smooth, weighted etc...
Example:
time_locked_ma(close, length=1, timeframe='days', type='ema')
Will generate a 1 day exponential moving average that will stay consistent across all chart intervals.
Error Handling
On small time frames with large moving averages (IE: 1min chart with a 50 week moving average), you'll get a study error that says "(function "sma") references too many candles in history" .
To fix this, make sure you have timeframe="" as an indicator() header. Next, in the indicator settings, increase the timeframe from to a higher interval until the error goes away.
By default, it's set to "Chart". Bringing the interval up to 1hr will usually solve the issue.
Furthermore, adding timeframe_gaps=false to your indicator() header will give you an approximation of real-time values.
Misc Info
For time_lock_ma() setting type='na' will return the relative length value that adjusts dynamically to user's chart time interval.
This is good for plugging into other functions where a lookback or length is required. (IE: Bollinger Bands)
time_locked_ma(source, length, timeframe, type) Creates a moving average that is locked to a desired timeframe
Parameters:
source : float, Moving average source
length : int, Moving average length
timeframe : string, Desired timeframe. Use: "minutes", "hours", "days", "weeks", "months", "chart"
type : string, string Moving average type. Use "SMA" (default) or "EMA". Value of "NA" will return relative lookback length.
Returns: moving average that is locked to desired timeframe.
timeframe_convert(t, a, b) Converts timeframe to desired timeframe. From a --> b
Parameters:
t : int, Time interval
a : string, Time period
b : string, Time period to convert to
Returns: Converted timeframe value
chart_time(timeframe_period, timeframe_multiplier) Separates timeframe.period function and returns chart interval and period
Parameters:
timeframe_period : string, timeframe.period
timeframe_multiplier : int, timeframe.multiplier
Enjoy :)
FunctionGenerateRandomPointsInShapeLibrary "FunctionGenerateRandomPointsInShape"
Generate random vector points in geometric shape (parallelogram, triangle)
random_parallelogram(vector_a, vector_b) Generate random vector point in a parallelogram shape.
Parameters:
vector_a : float array, vector of (x, y) shape.
vector_b : float array, vector of (x, y) shape.
Returns: float array, vector of (x, y) shape.
random_triangle(vector_a, vector_b) Generate random vector point in a triangle shape.
Parameters:
vector_a : float array, vector of (x, y) shape.
vector_b : float array, vector of (x, y) shape.
Returns: float array, vector of (x, y) shape.
FunctionArrayNextPreviousLibrary "FunctionArrayNextPrevious"
Methods to iterate through a array by a fixed anchor point.
array_next(array, start_index) retrieves the next value of the internal pointer index.
Parameters:
array : (any array type), array to iterate.
start_index : int, anchor index to start indexing.
array_previous(array, start_index) retrieves the previous value of the internal pointer index.
Parameters:
array : (any array type), array to iterate.
start_index : int, anchor index to start indexing.
note: regrettably is not possible to have global reference index without juggling it in the parameters and tracking it externally to switch between next/previous
VolatilityCheckerLibrary "VolatilityChecker"
Volatility is judged to be high when the range of one period is greater than the ATR of another period.
is_high(_periods, _smooth, _atr_periods, _atr_times) Return true if the volatility is high.
Parameters:
_periods : Range Period
_smooth : Smoothes the range width.
_atr_periods : ATR Period
_atr_times : Amplify the calculated ATR.
Returns: {Boolean}
is_low()
Ichimoku LibraryLibrary "Ichimoku"
Ichimoku Kinko Hyo library
calc(conversion, base, lead, displacement1, displacement2) : Calculate the Ichimoku Kinko Hyo values
Parameters:
conversion : Conversion line' periods
base : Base line's periods
lead : 2nd Leading line's periods
displacement1 : Leading line's offset
displacement2 : Lagging line's offset
Returns: