ATE_Common_Functions_LibraryLibrary "ATE_Common_Functions_Library"
- ATE_Common_Functions_Library was created to assist in constructing CCOMET Scanners
RCI(_rciLength, _source, _interval)
You will see me using this a lot. DEFINITELY my favorite oscillator to utilize for SO many different things from
timing entries/exits to determining trends.Calculation of this indicator based on Spearmans Correlation.
Parameters:
_rciLength (int) : (int)
Amount of bars back to use in RCI calculations.
_source (float) : (float)
Source to use in RCI calculations (can use ANY source series. Ie, open,close,high,low,etc).
_interval (int) : (int)
Optional (if parameter not included, it defaults to 3). RCI calculation groups bars by this amount and then will.
rank these groups of bars.
Returns: (float)
Returns a single RCI value that will oscillates between -100 and +100.
RCIAVG(_rciSMAlen, _source, _interval, firstLength, lastLength)
20 RCI's are averaged together to get this RCI Avg (Rank Correlation Index Average). Each RCI (of the 20 total RCI)
has a progressively LARGER Lookback Length. Rather than having ALL of the RCI Lengths be individually adjustable (because of too many inputs),
I have made the FIRST Length used (smallest Length value in the set) and the LAST Length used (largest length value in the set) be adjustable
and all other 18 Lengths are equally spread out between the 'firstLength' and the 'lastLength'.
Parameters:
_rciSMAlen (int) : (int)
Unlike the Single RCI Function, this function smooths out the end result using an SMA with a length value that is this parameter.
_source (float) : (float)
Source to use in RCI calculations (can use ANY source series. Ie, open,close,high,low,etc).
_interval (int) : (int)
Optional (if parameter not included, it defaults to 3). Within the RCI calculation, bars next to each other are grouped together
and then these groups are Ranked against each other. This parameter is the number of adjacent bars that are grouped together.
firstLength (int) : (int)
Optional (if parameter is not included when the function is called on in the script, then it defaults to 200).
This parameter is the Lookback Length for the 1st RCI used (so the SMALLEST Length used) in the RCI Avg.
lastLength (int) : (int)
Optional (if parameter is not included when the function is called on in the script, then it defaults to 2500).
This parameter is the Lookback Length for the 20th(the LAST) RCI used (so the LARGEST Length used) in the RCI Avg.
***** BEWARE ***** The 'lastLength' must be less than (or possibly equal to) 5000 because Tradingview has capped it at 5000, causing an error.
***** BEWARE ***** If the script gives a compiler "time out" error then the 'lastLength' must be lowered until it no longer times out when compiling.
Returns: (float)
Returns a single RCI value that is the Avg of many RCI values that will oscillate between -100 and +100.
PercentChange(_startingValue, _endingValue)
This is a quick function to calculate how much % change has occurred between the '_startingValue' and the '_endingValue'
that you input into the function.
Parameters:
_startingValue (float) : (float)
The source value to START the % change calculation from.
_endingValue (float) : (float)
The source value to END the % change caluclation from.
Returns: Returns a single output being the % value between 0-100 (with trailing numbers behind a decimal). If you want only
a certain amount of numbers behind the decimal, this function needs to be put within a formatting function to do so.
Rescale(_source, _oldMin, _oldMax, _newMin, _newMax)
Rescales series with a known '_oldMin' & '_oldMax'. Use this when the scale of the '_source' to
rescale is known (bounded).
Parameters:
_source (float) : (float)
Source to be normalized.
_oldMin (int) : (float)
The known minimum of the '_source'.
_oldMax (int) : (float)
The known maximum of the '_source'.
_newMin (int) : (float)
What you want the NEW minimum of the '_source' to be.
_newMax (int) : (float)
What you want the NEW maximum of the '_source' to be.
Returns: Outputs your previously bounded '_source', but now the value will only move between the '_newMin' and '_newMax'
values you set in the variables.
Normalize_Historical(_source, _minimumLvl, _maximumLvl)
Normalizes '_source' that has a previously unknown min/max(unbounded) determining the max & min of the '_source'
FROM THE ENTIRE CHARTS HISTORY. ]
Parameters:
_source (float) : (float)
Source to be normalized.
_minimumLvl (int) : (float)
The Lower Boundary Level.
_maximumLvl (int) : (float)
The Upper Boundary Level.
Returns: Returns your same '_source', but now the value will MOSTLY stay between the minimum and maximum values you set in the
'_minimumLvl' and '_maximumLvl' variables (ie. if the source you input is an RSI...the output is the same RSI value but
instead of moving between 0-100 it will move between the maxand min you set).
Normailize_Local(_source, _length, _minimumLvl, _maximumLvl)
Normalizes series with previously unknown min/max(unbounded). Much like the Normalize_Historical function above this one,
but rather than using the Highest/Lowest Values within the ENTIRE charts history, this on looks for the Highest/Lowest
values of '_source' within the last ___ bars (set by user as/in the '_length' parameter. ]
Parameters:
_source (float) : (float)
Source to be normalized.
_length (int) : (float)
The amount of bars to look back to determine the highest/lowest '_source' value.
_minimumLvl (int) : (float)
The Lower Boundary Level.
_maximumLvl (int) : (float)
The Upper Boundary Level.
Returns: Returns a single output variable being the previously unbounded '_source' that is now normalized and bound between
the values used for '_minimumLvl'/'_maximumLvl' of the '_source' within the user defined lookback period.
Techindicator
convergingpatternsLibrary "convergingpatterns"
Library having implementation of converging chart patterns
getPatternNameByType(patternType)
Returns pattern name based on type
Parameters:
patternType (int) : integer value representing pattern type
Returns: string name of the pattern
method find(this, sProperties, dProperties, patterns, ohlcArray)
find converging patterns for given zigzag
Namespace types: zg.Zigzag
Parameters:
this (Zigzag type from Trendoscope/ZigzagLite/2) : Current zigzag Object
sProperties (ScanProperties) : ScanProperties Object
dProperties (DrawingProperties type from Trendoscope/abstractchartpatterns/5) : DrawingProperties Object
patterns (array type from Trendoscope/abstractchartpatterns/5) : array of existing patterns to check for duplicates
ohlcArray (array type from Trendoscope/ohlc/1) : array of OHLC values for historical reference
Returns: string name of the pattern
ScanProperties
Object containing properties for pattern scanning
Fields:
baseProperties (ScanProperties type from Trendoscope/abstractchartpatterns/5) : Object of Base Scan Properties
convergingDistanceMultiplier (series float) : when multiplied with pattern size gets the max number of bars within which the pattern should converge
basechartpatternsLibrary "basechartpatterns"
Library having complete chart pattern implementation
getPatternNameById(id)
Returns pattern name by id
Parameters:
id (int) : pattern id
Returns: Pattern name
method find(points, properties, dProperties, ohlcArray)
Find patterns based on array of points
Namespace types: chart.point
Parameters:
points (chart.point ) : array of chart.point objects
properties (ScanProperties type from Trendoscope/abstractchartpatterns/1) : ScanProperties object
dProperties (DrawingProperties type from Trendoscope/abstractchartpatterns/1) : DrawingProperties object
ohlcArray (OHLC type from Trendoscope/ohlc/1)
Returns: Flag indicating if the pattern is valid, Current Pattern object
method find(this, properties, dProperties, patterns, ohlcArray)
Find patterns based on the currect zigzag object but will not store them in the pattern array.
Namespace types: zg.Zigzag
Parameters:
this (Zigzag type from Trendoscope/ZigzagLite/2) : Zigzag object containing pivots
properties (ScanProperties type from Trendoscope/abstractchartpatterns/1) : ScanProperties object
dProperties (DrawingProperties type from Trendoscope/abstractchartpatterns/1) : DrawingProperties object
patterns (Pattern type from Trendoscope/abstractchartpatterns/1) : Array of Pattern objects
ohlcArray (OHLC type from Trendoscope/ohlc/1)
Returns: Flag indicating if the pattern is valid, Current Pattern object
abstractchartpatternsLibrary "abstractchartpatterns"
Library having abstract types and methods for chart pattern implementations
checkBarRatio(p1, p2, p3, properties)
checks if three zigzag pivot points are having uniform bar ratios
Parameters:
p1 (chart.point) : First pivot point
p2 (chart.point) : Second pivot point
p3 (chart.point) : Third pivot point
properties (ScanProperties)
Returns: true if points are having uniform bar ratio
getRatioDiff(p1, p2, p3)
gets ratio difference between 3 pivot combinations
Parameters:
p1 (chart.point)
p2 (chart.point)
p3 (chart.point)
Returns: returns the ratio difference between pivot2/pivot1 ratio and pivot3/pivot2 ratio
method inspect(points, stratingBar, endingBar, direction, ohlcArray)
Creates a trend line between 2 or 3 points and validates and selects best combination
Namespace types: chart.point
Parameters:
points (chart.point ) : Array of chart.point objects used for drawing trend line
stratingBar (int) : starting bar of the trend line
endingBar (int) : ending bar of the trend line
direction (float) : direction of the last pivot. Tells whether the line is joining upper pivots or the lower pivots
ohlcArray (OHLC type from Trendoscope/ohlc/1) : Array of OHLC values
Returns: boolean flag indicating if the trend line is valid and the trend line object as tuple
method draw(this)
draws pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be drawn
Returns: Current Pattern object
method erase(this)
erase the given pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be erased
Returns: Current Pattern object
method push(this, p, maxItems)
push Pattern object to the array by keeping maxItems limit
Namespace types: Pattern
Parameters:
this (Pattern ) : array of Pattern objects
p (Pattern) : Pattern object to be added to array
@oaram maxItems Max number of items the array can hold
maxItems (int)
Returns: Current Pattern array
method deepcopy(this)
Perform deep copy of a chart point array
Namespace types: chart.point
Parameters:
this (chart.point ) : array of chart.point objects
Returns: deep copy array
DrawingProperties
Object containing properties for pattern drawing
Fields:
patternLineWidth (series int) : Line width of the pattern trend lines
showZigzag (series bool) : show zigzag associated with pattern
zigzagLineWidth (series int) : line width of the zigzag lines. Used only when showZigzag is set to true
zigzagLineColor (series color) : color of the zigzag lines. Used only when showZigzag is set to true
showPatternLabel (series bool) : display pattern label containing the name
patternLabelSize (series string) : size of the pattern label. Used only when showPatternLabel is set to true
showPivotLabels (series bool) : Display pivot labels of the patterns marking 1-6
pivotLabelSize (series string) : size of the pivot label. Used only when showPivotLabels is set to true
pivotLabelColor (series color) : color of the pivot label outline. chart.bg_color or chart.fg_color are the appropriate values.
deleteOnPop (series bool) : delete the pattern when popping out from the array of Patterns.
Pattern
Object containing Individual Pattern data
Fields:
points (chart.point )
originalPoints (chart.point )
trendLine1 (Line type from Trendoscope/LineWrapper/1) : First trend line joining pivots 1, 3, 5
trendLine2 (Line type from Trendoscope/LineWrapper/1) : Second trend line joining pivots 2, 4 (, 6)
properties (DrawingProperties) : DrawingProperties Object carrying common properties
patternColor (series color) : Individual pattern color. Lines and labels will be using this color.
ratioDiff (series float) : Difference between trendLine1 and trendLine2 ratios
zigzagLine (series polyline) : Internal zigzag line drawing Object
pivotLabels (label ) : array containning Pivot labels
patternLabel (series label) : pattern label Object
patternType (series int) : integer representing the pattern type
patternName (series string) : Type of pattern in string
ScanProperties
Object containing properties for pattern scanning
Fields:
offset (series int) : Zigzag pivot offset. Set it to 1 for non repainting scan.
numberOfPivots (series int) : Number of pivots to be used in pattern search. Can be either 5 or 6
errorRatio (series float) : Error Threshold to be considered for comparing the slope of lines
flatRatio (series float) : Retracement ratio threshold used to determine if the lines are flat
checkBarRatio (series bool) : Also check bar ratio are within the limits while scanning the patterns
barRatioLimit (series float) : Bar ratio limit used for checking the bars. Used only when checkBarRatio is set to true
avoidOverlap (series bool) : avoid overlapping patterns.
allowedPatterns (bool ) : array of bool encoding the allowed pattern types.
allowedLastPivotDirections (int ) : array of int representing allowed last pivot direction for each pattern types
themeColors (color ) : color array of themes to be used.
FunctionsLibrary "Functions"
half_candle()
Half Candles
Returns: half candles (difference between open and close)
super_smoother(source, len)
Ehlers Super Smoother
Parameters:
source (float) : Source
len (int)
Returns: super smoothed moving average
quotient(length, K)
Ehlers early onset trend
Parameters:
length (int) : Length (default = 1)
K (float) : Factor (default = 0.8)
Returns: Ehlers early onset trend
butterworth_2Pole(src, length)
Ehlers 2 Pole Butterworth Filter
Parameters:
src (float) : Source
length (int) : Length
Returns: Ehlers 2 Pole Butterworth Filter
hann_ma(src, length)
Ehler's Hann Moving Average
Parameters:
src (float) : Source
length (int) : Length
Returns: Ehler's Hann Moving Average
oef(src)
Ehlers Optimum Elliptic Filter
Parameters:
src (float) : Source
Returns: Ehlers Optimum Elliptic Filter
moef(src)
Ehlers Modified Optimum Elliptic Filter
Parameters:
src (float) : Source
Returns: Ehlers Modified Optimum Elliptic Filter
arsi(src, length)
Advanced RSI
Parameters:
src (float) : Source
length (simple int) : Length (default = 14)
Returns: ARSI
smoothrng(src, length, multi)
Smooth Range
Parameters:
src (float) : Source
length (simple int) : Length
multi (float) : Multiplikator (default 3.0)
Returns: Smooth Range
ottlibLibrary "ottlib"
█ OVERVIEW
This library contains functions for the calculation of the OTT (Optimized Trend Tracker) and its variants, originally created by Anıl Özekşi (Anil_Ozeksi). Special thanks to him for the concept and to Kıvanç Özbilgiç (KivancOzbilgic) and dg_factor (dg_factor) for adapting them to Pine Script.
█ WHAT IS "OTT"
The OTT (Optimized Trend Tracker) is a highly customizable and very effective trend-following indicator that relies on moving averages and a trailing stop at its core. Moving averages help reduce noise by smoothing out sudden price movements in the markets, while trailing stops assist in detecting trend reversals with precision. Initially developed as a noise-free trailing stop, the current variants of OTT range from rapid trend reversal detection to long-term trend confirmation, thanks to its extensive customizability.
It's well-known variants are:
OTT (Optimized Trend Tracker).
TOTT (Twin OTT).
OTT Channels.
RISOTTO (RSI OTT).
SOTT (Stochastic OTT).
HOTT & LOTT (Highest & Lowest OTT)
ROTT (Relative OTT)
FT (Original name is Fırsatçı Trend in Turkish which translates to Opportunist Trend)
█ LIBRARY FEATURES
This library has been prepared in accordance with the style, coding, and annotation standards of Pine Script version 5. As a result, explanations and examples will appear when users hover over functions or enter function parameters in the editor.
█ USAGE
Usage of this library is very simple. Just import it to your script with the code below and use its functions.
import ismailcarlik/ottlib/1 as ottlib
█ FUNCTIONS
• f_vidya(source, length, cmoLength)
Short Definition: Chande's Variable Index Dynamic Average (VIDYA).
Details: This function computes Chande's Variable Index Dynamic Average (VIDYA), which serves as the original moving average for OTT. The 'length' parameter determines the number of bars used to calculate the average of the given source. Lower values result in less smoothing of prices, while higher values lead to greater smoothing. While primarily used internally in this library, it has been made available for users who wish to utilize it as a moving average or use in custom OTT implementations.
Parameters:
source (float) : (series float) Series of values to process.
length (simple int) : (simple int) Number of bars to lookback.
cmoLength (simple int) : (simple int) Number of bars to lookback for calculating CMO. Default value is `9`.
Returns: (float) Calculated average of `source` for `length` bars back.
Example:
vidyaValue = ottlib.f_vidya(source = close, length = 20)
plot(vidyaValue, color = color.blue)
• f_mostTrail(source, multiplier)
Short Definition: Calculates trailing stop value.
Details: This function calculates the trailing stop value for a given source and the percentage. The 'multiplier' parameter defines the percentage of the trailing stop. Lower values are beneficial for catching short-term reversals, while higher values aid in identifying long-term trends. Although only used once internally in this library, it has been made available for users who wish to utilize it as a traditional trailing stop or use in custom OTT implementations.
Parameters:
source (float) : (series int/float) Series of values to process.
multiplier (simple float) : (simple float) Percent of trailing stop.
Returns: (float) Calculated value of trailing stop.
Example:
emaValue = ta.ema(source = close, length = 14)
mostValue = ottlib.f_mostTrail(source = emaValue, multiplier = 2.0)
plot(mostValue, color = emaValue >= mostValue ? color.green : color.red)
• f_ottTrail(source, multiplier)
Short Definition: Calculates OTT-specific trailing stop value.
Details: This function calculates the trailing stop value for a given source in the manner used in OTT. Unlike a traditional trailing stop, this function modifies the traditional trailing stop value from two bars prior by adjusting it further with half the specified percentage. The 'multiplier' parameter defines the percentage of the trailing stop. Lower values are beneficial for catching short-term reversals, while higher values aid in identifying long-term trends. Although primarily used internally in this library, it has been made available for users who wish to utilize it as a trailing stop or use in custom OTT implementations.
Parameters:
source (float) : (series int/float) Series of values to process.
multiplier (simple float) : (simple float) Percent of trailing stop.
Returns: (float) Calculated value of OTT-specific trailing stop.
Example:
vidyaValue = ottlib.f_vidya(source = close, length = 20)
ottValue = ottlib.f_ottTrail(source = vidyaValue, multiplier = 1.5)
plot(ottValue, color = vidyaValue >= ottValue ? color.green : color.red)
• ott(source, length, multiplier)
Short Definition: Calculates OTT (Optimized Trend Tracker).
Details: The OTT consists of two lines. The first, known as the "Support Line", is the VIDYA of the given source. The second, called the "OTT Line", is the trailing stop based on the Support Line. The market is considered to be in an uptrend when the Support Line is above the OTT Line, and in a downtrend when it is below.
Parameters:
source (float) : (series float) Series of values to process. Default value is `close`.
length (simple int) : (simple int) Number of bars to lookback. Default value is `2`.
multiplier (simple float) : (simple float) Percent of trailing stop. Default value is `1.4`.
Returns: ( [ float, float ]) Tuple of `supportLine` and `ottLine`.
Example:
= ottlib.ott(source = close, length = 2, multiplier = 1.4)
longCondition = ta.crossover(supportLine, ottLine)
shortCondition = ta.crossunder(supportLine, ottLine)
• tott(source, length, multiplier, bandsMultiplier)
Short Definition: Calculates TOTT (Twin OTT).
Details: TOTT consists of three lines: the "Support Line," which is the VIDYA of the given source; the "Upper Line," a trailing stop of the Support Line adjusted with an added multiplier; and the "Lower Line," another trailing stop of the Support Line, adjusted with a reduced multiplier. The market is considered in an uptrend if the Support Line is above the Upper Line and in a downtrend if it is below the Lower Line.
Parameters:
source (float) : (series float) Series of values to process. Default value is `close`.
length (simple int) : (simple int) Number of bars to lookback. Default value is `40`.
multiplier (simple float) : (simple float) Percent of trailing stop. Default value is `0.6`.
bandsMultiplier (simple float) : Multiplier for bands. Default value is `0.0006`.
Returns: ( [ float, float, float ]) Tuple of `supportLine`, `upperLine` and `lowerLine`.
Example:
= ottlib.tott(source = close, length = 40, multiplier = 0.6, bandsMultiplier = 0.0006)
longCondition = ta.crossover(supportLine, upperLine)
shortCondition = ta.crossunder(supportLine, lowerLine)
• ott_channel(source, length, multiplier, ulMultiplier, llMultiplier)
Short Definition: Calculates OTT Channels.
Details: OTT Channels comprise nine lines. The central line, known as the "Mid Line," is the OTT of the given source's VIDYA. The remaining lines are positioned above and below the Mid Line, shifted by specified multipliers.
Parameters:
source (float) : (series float) Series of values to process. Default value is `close`
length (simple int) : (simple int) Number of bars to lookback. Default value is `2`
multiplier (simple float) : (simple float) Percent of trailing stop. Default value is `1.4`
ulMultiplier (simple float) : (simple float) Multiplier for upper line. Default value is `0.01`
llMultiplier (simple float) : (simple float) Multiplier for lower line. Default value is `0.01`
Returns: ( [ float, float, float, float, float, float, float, float, float ]) Tuple of `ul4`, `ul3`, `ul2`, `ul1`, `midLine`, `ll1`, `ll2`, `ll3`, `ll4`.
Example:
= ottlib.ott_channel(source = close, length = 2, multiplier = 1.4, ulMultiplier = 0.01, llMultiplier = 0.01)
• risotto(source, length, rsiLength, multiplier)
Short Definition: Calculates RISOTTO (RSI OTT).
Details: RISOTTO comprised of two lines: the "Support Line," which is the VIDYA of the given source's RSI value, calculated based on the length parameter, and the "RISOTTO Line," a trailing stop of the Support Line. The market is considered in an uptrend when the Support Line is above the RISOTTO Line, and in a downtrend if it is below.
Parameters:
source (float) : (series float) Series of values to process. Default value is `close`.
length (simple int) : (simple int) Number of bars to lookback. Default value is `50`.
rsiLength (simple int) : (simple int) Number of bars used for RSI calculation. Default value is `100`.
multiplier (simple float) : (simple float) Percent of trailing stop. Default value is `0.2`.
Returns: ( [ float, float ]) Tuple of `supportLine` and `risottoLine`.
Example:
= ottlib.risotto(source = close, length = 50, rsiLength = 100, multiplier = 0.2)
longCondition = ta.crossover(supportLine, risottoLine)
shortCondition = ta.crossunder(supportLine, risottoLine)
• sott(source, kLength, dLength, multiplier)
Short Definition: Calculates SOTT (Stochastic OTT).
Details: SOTT is comprised of two lines: the "Support Line," which is the VIDYA of the given source's Stochastic value, based on the %K and %D lengths, and the "SOTT Line," serving as the trailing stop of the Support Line. The market is considered in an uptrend when the Support Line is above the SOTT Line, and in a downtrend when it is below.
Parameters:
source (float) : (series float) Series of values to process. Default value is `close`.
kLength (simple int) : (simple int) Stochastic %K length. Default value is `500`.
dLength (simple int) : (simple int) Stochastic %D length. Default value is `200`.
multiplier (simple float) : (simple float) Percent of trailing stop. Default value is `0.5`.
Returns: ( [ float, float ]) Tuple of `supportLine` and `sottLine`.
Example:
= ottlib.sott(source = close, kLength = 500, dLength = 200, multiplier = 0.5)
longCondition = ta.crossover(supportLine, sottLine)
shortCondition = ta.crossunder(supportLine, sottLine)
• hottlott(length, multiplier)
Short Definition: Calculates HOTT & LOTT (Highest & Lowest OTT).
Details: HOTT & LOTT are composed of two lines: the "HOTT Line", which is the OTT of the highest price's VIDYA, and the "LOTT Line", the OTT of the lowest price's VIDYA. A high price surpassing the HOTT Line can be considered a long signal, while a low price dropping below the LOTT Line may indicate a short signal.
Parameters:
length (simple int) : (simple int) Number of bars to lookback. Default value is `20`.
multiplier (simple float) : (simple float) Percent of trailing stop. Default value is `0.6`.
Returns: ( [ float, float ]) Tuple of `hottLine` and `lottLine`.
Example:
= ottlib.hottlott(length = 20, multiplier = 0.6)
longCondition = ta.crossover(high, hottLine)
shortCondition = ta.crossunder(low, lottLine)
• rott(source, length, multiplier)
Short Definition: Calculates ROTT (Relative OTT).
Details: ROTT comprises two lines: the "Support Line", which is the VIDYA of the given source, and the "ROTT Line", the OTT of the Support Line's VIDYA. The market is considered in an uptrend if the Support Line is above the ROTT Line, and in a downtrend if it is below. ROTT is similar to OTT, but the key difference is that the ROTT Line is derived from the VIDYA of two bars of Support Line, not directly from it.
Parameters:
source (float) : (series float) Series of values to process. Default value is `close`.
length (simple int) : (simple int) Number of bars to lookback. Default value is `200`.
multiplier (simple float) : (simple float) Percent of trailing stop. Default value is `0.1`.
Returns: ( [ float, float ]) Tuple of `supportLine` and `rottLine`.
Example:
= ottlib.rott(source = close, length = 200, multiplier = 0.1)
isUpTrend = supportLine > rottLine
isDownTrend = supportLine < rottLine
• ft(source, length, majorMultiplier, minorMultiplier)
Short Definition: Calculates Fırsatçı Trend (Opportunist Trend).
Details: FT is comprised of two lines: the "Support Line", which is the VIDYA of the given source, and the "FT Line", a trailing stop of the Support Line calculated using both minor and major trend values. The market is considered in an uptrend when the Support Line is above the FT Line, and in a downtrend when it is below.
Parameters:
source (float) : (series float) Series of values to process. Default value is `close`.
length (simple int) : (simple int) Number of bars to lookback. Default value is `30`.
majorMultiplier (simple float) : (simple float) Percent of major trend. Default value is `3.6`.
minorMultiplier (simple float) : (simple float) Percent of minor trend. Default value is `1.8`.
Returns: ( [ float, float ]) Tuple of `supportLine` and `ftLine`.
Example:
= ottlib.ft(source = close, length = 30, majorMultiplier = 3.6, minorMultiplier = 1.8)
longCondition = ta.crossover(supportLine, ftLine)
shortCondition = ta.crossunder(supportLine, ftLine)
█ CUSTOM OTT CREATION
Users can create custom OTT implementations using f_ottTrail function in this library. The example code which uses EMA of 7 period as moving average and calculates OTT based of it is below.
Source Code:
//@version=5
indicator("Custom OTT", shorttitle = "COTT", overlay = true)
import ismailcarlik/ottlib/1 as ottlib
src = input.source(close, title = "Source")
length = input.int(7, title = "Length", minval = 1)
multiplier = input.float(2.0, title = "Multiplier", minval = 0.1)
support = ta.ema(source = src, length = length)
ott = ottlib.f_ottTrail(source = support, multiplier = multiplier)
pSupport = plot(support, title = "Moving Average Line (Support)", color = color.blue)
pOtt = plot(ott, title = "Custom OTT Line", color = color.orange)
fillColor = support >= ott ? color.new(color.green, 60) : color.new(color.red, 60)
fill(pSupport, pOtt, color = fillColor, title = "Direction")
Result:
█ DISCLAIMER
Trading is risky and most of the day traders lose money eventually. This library and its functions are only for educational purposes and should not be construed as financial advice. Past performances does not guarantee future results.
chartpatternsLibrary "chartpatterns"
Library having complete chart pattern implementation
method draw(this)
draws pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be drawn
Returns: Current Pattern object
method erase(this)
erase the given pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be erased
Returns: Current Pattern object
method findPattern(this, properties, patterns)
Find patterns based on the currect zigzag object and store them in the patterns array
Namespace types: zg.Zigzag
Parameters:
this (Zigzag type from Trendoscope/ZigzagLite/2) : Zigzag object containing pivots
properties (PatternProperties) : PatternProperties object
patterns (Pattern ) : Array of Pattern objects
Returns: Current Pattern object
PatternProperties
Object containing properties for pattern scanning
Fields:
offset (series int) : Zigzag pivot offset. Set it to 1 for non repainting scan.
numberOfPivots (series int) : Number of pivots to be used in pattern search. Can be either 5 or 6
errorRatio (series float) : Error Threshold to be considered for comparing the slope of lines
flatRatio (series float) : Retracement ratio threshold used to determine if the lines are flat
checkBarRatio (series bool) : Also check bar ratio are within the limits while scanning the patterns
barRatioLimit (series float) : Bar ratio limit used for checking the bars. Used only when checkBarRatio is set to true
avoidOverlap (series bool)
patternLineWidth (series int) : Line width of the pattern trend lines
showZigzag (series bool) : show zigzag associated with pattern
zigzagLineWidth (series int) : line width of the zigzag lines. Used only when showZigzag is set to true
zigzagLineColor (series color) : color of the zigzag lines. Used only when showZigzag is set to true
showPatternLabel (series bool) : display pattern label containing the name
patternLabelSize (series string) : size of the pattern label. Used only when showPatternLabel is set to true
showPivotLabels (series bool) : Display pivot labels of the patterns marking 1-6
pivotLabelSize (series string) : size of the pivot label. Used only when showPivotLabels is set to true
pivotLabelColor (series color) : color of the pivot label outline. chart.bg_color or chart.fg_color are the appropriate values.
allowedPatterns (bool ) : array of bool encoding the allowed pattern types.
themeColors (color ) : color array of themes to be used.
Pattern
Object containing Individual Pattern data
Fields:
pivots (Pivot type from Trendoscope/ZigzagLite/2) : array of Zigzag Pivot points
trendLine1 (Line type from Trendoscope/LineWrapper/1) : First trend line joining pivots 1, 3, 5
trendLine2 (Line type from Trendoscope/LineWrapper/1) : Second trend line joining pivots 2, 4 (, 6)
properties (PatternProperties) : PatternProperties Object carrying common properties
patternColor (series color) : Individual pattern color. Lines and labels will be using this color.
ratioDiff (series float) : Difference between trendLine1 and trendLine2 ratios
zigzagLine (series polyline) : Internal zigzag line drawing Object
pivotLabels (label ) : array containning Pivot labels
patternLabel (series label) : pattern label Object
patternType (series int) : integer representing the pattern type
patternName (series string) : Type of pattern in string
ZigzagLiteLibrary "ZigzagLite"
Lighter version of the Zigzag Library. Without indicators and sub-component divisions
method getPrices(pivots)
Gets the array of prices from array of Pivots
Namespace types: Pivot
Parameters:
pivots (Pivot ) : array array of Pivot objects
Returns: array array of pivot prices
method getBars(pivots)
Gets the array of bars from array of Pivots
Namespace types: Pivot
Parameters:
pivots (Pivot ) : array array of Pivot objects
Returns: array array of pivot bar indices
method getPoints(pivots)
Gets the array of chart.point from array of Pivots
Namespace types: Pivot
Parameters:
pivots (Pivot ) : array array of Pivot objects
Returns: array array of pivot points
method getPoints(this)
Namespace types: Zigzag
Parameters:
this (Zigzag)
method calculate(this, ohlc, ltfHighTime, ltfLowTime)
Calculate zigzag based on input values and indicator values
Namespace types: Zigzag
Parameters:
this (Zigzag) : Zigzag object
ohlc (float ) : Array containing OHLC values. Can also have custom values for which zigzag to be calculated
ltfHighTime (int) : Used for multi timeframe zigzags when called within request.security. Default value is current timeframe open time.
ltfLowTime (int) : Used for multi timeframe zigzags when called within request.security. Default value is current timeframe open time.
Returns: current Zigzag object
method calculate(this)
Calculate zigzag based on properties embedded within Zigzag object
Namespace types: Zigzag
Parameters:
this (Zigzag) : Zigzag object
Returns: current Zigzag object
method nextlevel(this)
Namespace types: Zigzag
Parameters:
this (Zigzag)
method clear(this)
Clears zigzag drawings array
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing ) : array
Returns: void
method clear(this)
Clears zigzag drawings array
Namespace types: ZigzagDrawingPL
Parameters:
this (ZigzagDrawingPL ) : array
Returns: void
method drawplain(this)
draws fresh zigzag based on properties embedded in ZigzagDrawing object without trying to calculate
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing) : ZigzagDrawing object
Returns: ZigzagDrawing object
method drawplain(this)
draws fresh zigzag based on properties embedded in ZigzagDrawingPL object without trying to calculate
Namespace types: ZigzagDrawingPL
Parameters:
this (ZigzagDrawingPL) : ZigzagDrawingPL object
Returns: ZigzagDrawingPL object
method drawfresh(this, ohlc)
draws fresh zigzag based on properties embedded in ZigzagDrawing object
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing) : ZigzagDrawing object
ohlc (float ) : values on which the zigzag needs to be calculated and drawn. If not set will use regular OHLC
Returns: ZigzagDrawing object
method drawcontinuous(this, ohlc)
draws zigzag based on the zigzagmatrix input
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing) : ZigzagDrawing object
ohlc (float ) : values on which the zigzag needs to be calculated and drawn. If not set will use regular OHLC
Returns:
PivotCandle
PivotCandle represents data of the candle which forms either pivot High or pivot low or both
Fields:
_high (series float) : High price of candle forming the pivot
_low (series float) : Low price of candle forming the pivot
length (series int) : Pivot length
pHighBar (series int) : represents number of bar back the pivot High occurred.
pLowBar (series int) : represents number of bar back the pivot Low occurred.
pHigh (series float) : Pivot High Price
pLow (series float) : Pivot Low Price
Pivot
Pivot refers to zigzag pivot. Each pivot can contain various data
Fields:
point (chart.point) : pivot point coordinates
dir (series int) : direction of the pivot. Valid values are 1, -1, 2, -2
level (series int) : is used for multi level zigzags. For single level, it will always be 0
ratio (series float) : Price Ratio based on previous two pivots
sizeRatio (series float)
ZigzagFlags
Flags required for drawing zigzag. Only used internally in zigzag calculation. Should not set the values explicitly
Fields:
newPivot (series bool) : true if the calculation resulted in new pivot
doublePivot (series bool) : true if the calculation resulted in two pivots on same bar
updateLastPivot (series bool) : true if new pivot calculated replaces the old one.
Zigzag
Zigzag object which contains whole zigzag calculation parameters and pivots
Fields:
length (series int) : Zigzag length. Default value is 5
numberOfPivots (series int) : max number of pivots to hold in the calculation. Default value is 20
offset (series int) : Bar offset to be considered for calculation of zigzag. Default is 0 - which means calculation is done based on the latest bar.
level (series int) : Zigzag calculation level - used in multi level recursive zigzags
zigzagPivots (Pivot ) : array which holds the last n pivots calculated.
flags (ZigzagFlags) : ZigzagFlags object which is required for continuous drawing of zigzag lines.
ZigzagObject
Zigzag Drawing Object
Fields:
zigzagLine (series line) : Line joining two pivots
zigzagLabel (series label) : Label which can be used for drawing the values, ratios, directions etc.
ZigzagProperties
Object which holds properties of zigzag drawing. To be used along with ZigzagDrawing
Fields:
lineColor (series color) : Zigzag line color. Default is color.blue
lineWidth (series int) : Zigzag line width. Default is 1
lineStyle (series string) : Zigzag line style. Default is line.style_solid.
showLabel (series bool) : If set, the drawing will show labels on each pivot. Default is false
textColor (series color) : Text color of the labels. Only applicable if showLabel is set to true.
maxObjects (series int) : Max number of zigzag lines to display. Default is 300
xloc (series string) : Time/Bar reference to be used for zigzag drawing. Default is Time - xloc.bar_time.
curved (series bool) : Boolean field to print curved zigzag - used only with polyline implementation
ZigzagDrawing
Object which holds complete zigzag drawing objects and properties.
Fields:
zigzag (Zigzag) : Zigzag object which holds the calculations.
properties (ZigzagProperties) : ZigzagProperties object which is used for setting the display styles of zigzag
drawings (ZigzagObject ) : array which contains lines and labels of zigzag drawing.
ZigzagDrawingPL
Object which holds complete zigzag drawing objects and properties - polyline version
Fields:
zigzag (Zigzag) : Zigzag object which holds the calculations.
properties (ZigzagProperties) : ZigzagProperties object which is used for setting the display styles of zigzag
zigzagLabels (label )
zigzagLine (series polyline) : polyline object of zigzag lines
ForecastingThis Forecasting library has a couple of Novel and traditional approaches to forecasting stock prices.
Traditionally, it provides a basic ARIMA forecaster using simple autoregression, as well as a linear regression and quadratic regression channel forecaster.
Novel approaches to forecasting include:
1) A Moving Average based Forecaster (modelled after ARIMA), it is capable of forecasting based on a user selected SMA.
2) Z-Score Forecast: Forecasting based on Z-Score (example displayed in chart).
Library "Forecasting"
ARIMA_Modeller(src)
: Creates a generic autoregressive ARIMA model
Parameters:
src (float)
Returns: : arima_result, arima_ucl, arima_lcl, arima_cor, arima_r2, arima_err, y1, y2, y3, y0
machine_learning_regression(output, x1, x2, x3, x4, x5, show_statistics)
: Creates an automatic regression based forecast model (can be used for other regression operations) from a list of possible independent variables.
Parameters:
output (float)
x1 (float)
x2 (float)
x3 (float)
x4 (float)
x5 (float)
show_statistics (bool)
Returns: : result, upper bound levels, lower bound levels, optional statitics table that displays the model parameters and statistics
time_series_linear_forecast(src, forecast_length, standard_deviation_extension_1, standard_deviation_extension_2)
: Creates a simple linear regression time series channel
Parameters:
src (float)
forecast_length (int)
standard_deviation_extension_1 (float)
standard_deviation_extension_2 (float)
Returns: : Linreg Channel
quadratic_time_series_forecast(src, forecast_length)
: Creates a simple quadratic regression time series channel
Parameters:
src (float)
forecast_length (int)
Returns: : Quadratic Regression Channel
moving_average_forecaster(source, train_time, ma_length, forecast_length, forecast_result, upper_bound_result, lower_bound_result)
: Creates an ARIMA style moving average forecaster
Parameters:
source (float)
train_time (int)
ma_length (int)
forecast_length (int)
forecast_result (float )
upper_bound_result (float )
lower_bound_result (float )
Returns: : forecast_result, upper_bound_result, lower_bound_result, moving_average, ucl, lcl
zscore_forecast(z_length, z_source, show_alerts, forecast_length, show_forecast_table)
: Creates a Z-Score Forecast and is capable of plotting the immediate forecast via a Polyline
Parameters:
z_length (int)
z_source (float)
show_alerts (bool)
forecast_length (int)
show_forecast_table (bool)
Returns: : The export is void, it will export the Polyline forecast and the Z-forecast table if you enable it.
ZigzagLibrary "Zigzag"
Zigzag related user defined types. Depends on DrawingTypes library for basic types
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts ZigzagTypes/Pivot object to string representation
Namespace types: Pivot
Parameters:
this (Pivot) : ZigzagTypes/Pivot
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (string ) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of ZigzagTypes/Pivot
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts Array of Pivot objects to string representation
Namespace types: Pivot
Parameters:
this (Pivot ) : Pivot object array
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (string ) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of Pivot object array
method tostring(this)
Converts ZigzagFlags object to string representation
Namespace types: ZigzagFlags
Parameters:
this (ZigzagFlags) : ZigzagFlags object
Returns: string representation of ZigzagFlags
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts ZigzagTypes/Zigzag object to string representation
Namespace types: Zigzag
Parameters:
this (Zigzag) : ZigzagTypes/Zigzagobject
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (string ) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of ZigzagTypes/Zigzag
method calculate(this, ohlc, indicators, indicatorNames)
Calculate zigzag based on input values and indicator values
Namespace types: Zigzag
Parameters:
this (Zigzag) : Zigzag object
ohlc (float ) : Array containing OHLC values. Can also have custom values for which zigzag to be calculated
indicators (matrix) : Array of indicator values
indicatorNames (string ) : Array of indicator names for which values are present. Size of indicators array should be equal to that of indicatorNames
Returns: current Zigzag object
method calculate(this)
Calculate zigzag based on properties embedded within Zigzag object
Namespace types: Zigzag
Parameters:
this (Zigzag) : Zigzag object
Returns: current Zigzag object
method nextlevel(this)
Calculate Next Level Zigzag based on the current calculated zigzag object
Namespace types: Zigzag
Parameters:
this (Zigzag) : Zigzag object
Returns: Next Level Zigzag object
method clear(this)
Clears zigzag drawings array
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing ) : array
Returns: void
method drawplain(this)
draws fresh zigzag based on properties embedded in ZigzagDrawing object without trying to calculate
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing) : ZigzagDrawing object
Returns: ZigzagDrawing object
method drawfresh(this, ohlc, indicators, indicatorNames)
draws fresh zigzag based on properties embedded in ZigzagDrawing object
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing) : ZigzagDrawing object
ohlc (float ) : values on which the zigzag needs to be calculated and drawn. If not set will use regular OHLC
indicators (matrix) : Array of indicator values
indicatorNames (string ) : Array of indicator names for which values are present. Size of indicators array should be equal to that of indicatorNames
Returns: ZigzagDrawing object
method drawcontinuous(this, ohlc, indicators, indicatorNames)
draws zigzag based on the zigzagmatrix input
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing) : ZigzagDrawing object
ohlc (float ) : values on which the zigzag needs to be calculated and drawn. If not set will use regular OHLC
indicators (matrix) : Array of indicator values
indicatorNames (string ) : Array of indicator names for which values are present. Size of indicators array should be equal to that of indicatorNames
Returns:
method getPrices(pivots)
Namespace types: Pivot
Parameters:
pivots (Pivot )
method getBars(pivots)
Namespace types: Pivot
Parameters:
pivots (Pivot )
Indicator
Indicator is collection of indicator values applied on high, low and close
Fields:
indicatorHigh (series float) : Indicator Value applied on High
indicatorLow (series float) : Indicator Value applied on Low
PivotCandle
PivotCandle represents data of the candle which forms either pivot High or pivot low or both
Fields:
_high (series float) : High price of candle forming the pivot
_low (series float) : Low price of candle forming the pivot
length (series int) : Pivot length
pHighBar (series int) : represents number of bar back the pivot High occurred.
pLowBar (series int) : represents number of bar back the pivot Low occurred.
pHigh (series float) : Pivot High Price
pLow (series float) : Pivot Low Price
indicators (Indicator ) : Array of Indicators - allows to add multiple
Pivot
Pivot refers to zigzag pivot. Each pivot can contain various data
Fields:
point (chart.point) : pivot point coordinates
dir (series int) : direction of the pivot. Valid values are 1, -1, 2, -2
level (series int) : is used for multi level zigzags. For single level, it will always be 0
componentIndex (series int) : is the lower level zigzag array index for given pivot. Used only in multi level Zigzag Pivots
subComponents (series int) : is the number of sub waves per each zigzag wave. Only applicable for multi level zigzags
microComponents (series int) : is the number of base zigzag components in a zigzag wave
ratio (series float) : Price Ratio based on previous two pivots
sizeRatio (series float)
subPivots (Pivot )
indicatorNames (string ) : Names of the indicators applied on zigzag
indicatorValues (float ) : Values of the indicators applied on zigzag
indicatorRatios (float ) : Ratios of the indicators applied on zigzag based on previous 2 pivots
ZigzagFlags
Flags required for drawing zigzag. Only used internally in zigzag calculation. Should not set the values explicitly
Fields:
newPivot (series bool) : true if the calculation resulted in new pivot
doublePivot (series bool) : true if the calculation resulted in two pivots on same bar
updateLastPivot (series bool) : true if new pivot calculated replaces the old one.
Zigzag
Zigzag object which contains whole zigzag calculation parameters and pivots
Fields:
length (series int) : Zigzag length. Default value is 5
numberOfPivots (series int) : max number of pivots to hold in the calculation. Default value is 20
offset (series int) : Bar offset to be considered for calculation of zigzag. Default is 0 - which means calculation is done based on the latest bar.
level (series int) : Zigzag calculation level - used in multi level recursive zigzags
zigzagPivots (Pivot ) : array which holds the last n pivots calculated.
flags (ZigzagFlags) : ZigzagFlags object which is required for continuous drawing of zigzag lines.
ZigzagObject
Zigzag Drawing Object
Fields:
zigzagLine (series line) : Line joining two pivots
zigzagLabel (series label) : Label which can be used for drawing the values, ratios, directions etc.
ZigzagProperties
Object which holds properties of zigzag drawing. To be used along with ZigzagDrawing
Fields:
lineColor (series color) : Zigzag line color. Default is color.blue
lineWidth (series int) : Zigzag line width. Default is 1
lineStyle (series string) : Zigzag line style. Default is line.style_solid.
showLabel (series bool) : If set, the drawing will show labels on each pivot. Default is false
textColor (series color) : Text color of the labels. Only applicable if showLabel is set to true.
maxObjects (series int) : Max number of zigzag lines to display. Default is 300
xloc (series string) : Time/Bar reference to be used for zigzag drawing. Default is Time - xloc.bar_time.
ZigzagDrawing
Object which holds complete zigzag drawing objects and properties.
Fields:
zigzag (Zigzag) : Zigzag object which holds the calculations.
properties (ZigzagProperties) : ZigzagProperties object which is used for setting the display styles of zigzag
drawings (ZigzagObject ) : array which contains lines and labels of zigzag drawing.
New_Concepts_in_Technical_Trading_SystemsLibrary "New_Concepts_in_Technical_Trading_Systems"
A library for trading with mathematical indicators as described by J. Welles Wilder Jr. in 1978
psar(highSeries, lowSeries, closeSeries, start, increment, max)
psar calculates the parabolic SAR for the given series. Uses defaults as described by Wilder
Parameters:
highSeries (float) : the series of high price values
lowSeries (float) : the series of low price values
closeSeries (float) : the series of close price values
start (float) : the initial acceleration factor
increment (float) : amount the acceleration factor is incremented each step
max (float) : the maximum acceleration factor
Returns: the value of the stop and reverse price
momentum(closeSeries)
momentum calculates the momentum value, representing an acceleration of the current trend direction. Also calculates the trend balancing point which is a pivot to the momentum increasing or decreasing.
Parameters:
closeSeries (float) : the series of close price values
Returns: the value of the momentum and the next trend balance point
TrendPivotsLibrary "TrendPivots"
This library provides functions to search for bullish and bearish divergences between pivots and indicators. Functions search for higher highs and lower lows, automating lines, labels and signals for technical analysis and strategies.
method maxBeforeLast(id)
Method function to get the maximum price before the last, stored in an array pivotPoint.
Namespace types: pivotPoint
Parameters:
id (pivotPoint ) : (array pivotPoint) The pivotPoint array to inspect.
Returns: pivotPoint
method minBeforeLast(id)
Method function to get the minimum price before the last, stored in an array pivotPoint.
Namespace types: pivotPoint
Parameters:
id (pivotPoint ) : (array pivotPoint) The pivotPoint array to inspect.
Returns: pivotPoint
method pivotLine(id, a, b, color)
Sets the coordinates of a given line using two pivotPoint variables.
Namespace types: series line
Parameters:
id (line) : (line) Existing line
a (pivotPoint) : (pivotPoint) First pivotPoint.
b (pivotPoint) : (pivotPoint) Second pivotPoint.
color (color) : (color) The desired color. Default is red.
Returns: void
bearishDivergence(pivotArray)
Look for bearish divergence in a pivotPoint array cointaining pivot highs.
Parameters:
pivotArray (pivotPoint ) : (array pivotPoint) The pivotPoint array to inspect.
Returns: bool True if bearish divergence was found.
bullishDivergence(pivotArray)
Look for bullish divergence in a pivotPoint array cointaining pivot lows.
Parameters:
pivotArray (pivotPoint ) : (array pivotPoint) The pivotPoint array to inspect.
Returns: bool True if bullish divergence was found.
uptrendPivot(leftBars, rightBars, indicator, reset, plotLabel, plotLine)
Detects higher highs, higher lows and bearish divergence in an uptrend. Creates a line when bearish divergence is found, and labels.
Parameters:
leftBars (int) : (int)
rightBars (int) : (int)
indicator (float) : (float) RSI, MACD or other value.
reset (bool) : (bool) A bool variable to reinitiates the pivot computation, such as time changes, crossovers, or another.
plotLabel (bool) : (bool) If true (default), plots labels to higher highs and for each pivot low. Default = true.
plotLine (bool) : (bool) If true (default), plots a line linking the lower lows with divergence. Default = true.
Returns:
downtrendPivot(leftBars, rightBars, indicator, reset, plotLabel, plotLine)
Detects lower lows, lower highs, and bullish divergence in a downtrend. Creates a line when bullish divergence is found, and labels.
Parameters:
leftBars (int) : (int)
rightBars (int) : (int)
indicator (float) : (float) RSI, MACD or other value.
reset (bool) : (bool) A bool variable to reinitiates the pivot computation, such as time changes, crossovers, or another.
plotLabel (bool) : (bool) If true (default), plots labels to lower lows, and for each pivot low.
plotLine (bool) : (bool) If true (default), plots a line linking the lower lows with divergence. Default = true.
Returns:
pivotPoint
The coordinates of a pivot point and corresponding indicator value.
Fields:
x (series int) : (int) Time.
y (series float) : (float) Price.
indicator (series float) : (float) Indicator value.
WeightedSumIndexLibrary "WeightedSumIndex"
WeightedSumIndex: Helper class to build indices.
Index value is a normalized weighted sum of all its input signals.
The value is from 0 to 100
fun(x)
TODO: add function description here
Parameters:
x (float) : TODO: add parameter x description here
Returns: TODO: add what function returns
init()
Initialize an Index
Returns: A new instance of Index object with no signals
method add(idx, signal)
Adds the specified signal to the index
Namespace types: Index
Parameters:
idx (Index) : The Index object
signal (Signal) : Signal object
method calc(idx)
Caclulates the Index value
Namespace types: Index
Parameters:
idx (Index) : The Index object
Returns: Normalized weighted sum of all signals with on=true
method update(idx)
Calculates the Index value by calling idx.calc() and stores its value in the Index object.
Namespace types: Index
Parameters:
idx (Index) : The Index object
Signal
Parameters of input signal
Fields:
on (series bool) : Switch the signal on/off
weight (series float)
value (series float) : Value of the signal: should be between min and max
min (series float)
max (series float)
Index
The Index type with its properties and stored values
Fields:
signals (Signal )
value (series float) : Value of the index, must be calculated using calc() method
GuageLibrary "Gauge"
The gauge library utilizes a gaugeParams object, encapsulating crucial parameters for gauge creation. Essential attributes include num (the measured value) , min (the minimum value equating to 100% on the gauge's minimum scale) , and max (the maximum value equating to 100% on the gauge's maximum scale) . The size attribute (defaulting to 10) splits the scale into increments, each representing 100% divided by the specified size.
The num value dynamically shifts within the gauge based on its percentage move from the mathematical average between min and max . When num is below the average, the minimum portion of the scale activates, displaying the appropriate percentage based on the distance from the average to the minimum. The same principle applies when num exceeds the average. The 100% scale is reached at either end when num equals min or max .
The library offers full customization, allowing users to configure color schemes, labels, and titles. The gauge can be displayed either vertically (default) or horizontally. The colors employ a gradient, adapting based on the number's movement. Overall, the gauge library provides a flexible and comprehensive tool for visualizing and interpreting numerical values within a specified range.
A_Traders_Edge__LibraryLibrary "A_Traders_Edge__Library"
- A Trader's Edge (ATE)_Library was created to assist in constructing Market Overview Scanners (MOS)
LabelLocation(_firstLocation)
This function is used when there's a desire to print an assets ALERT LABELS at a set location on the scale that will
NOT change throughout the progression of the script. This is created so that if a lot of alerts are triggered, they
will stay relatively visible and not overlap each other. Ex. If you set your '_firstLocation' parameter as 1, since
there are a max of 40 assets that can be scanned, the 1st asset's location is assigned the value in the '_firstLocation' parameter,
the 2nd asset's location is the (1st asset's location+1)...and so on. If your first location is set to 81 then
the 1st asset is 81 and 2nd is 82 and so on until the 40th location = 120(in this particular example).
Parameters:
_firstLocation (simple int) : (simple int)
Optional(starts at 1 if no parameter added).
Location that you want the first asset to print its label if is triggered to do so.
ie. loc2=loc1+1, loc3=loc2+1, etc.
Returns: Returns 40 output variables each being a different location to print the labels so that an asset is asssigned to
a particular location on the scale. Regardless of if you have the maximum amount of assets being screened (40 max), this
function will output 40 locations… So there needs to be 40 variables assigned in the tuple in this function. What I
mean by that is you need to have 40 output location variables within your tuple (ie. between the ' ') regarless of
if your scanning 40 assets or not. If you only have 20 assets in your scripts input settings, then only the first 20
variables within the ' ' Will be assigned to a value location and the other 20 will be assigned 'NA', but their
variables still need to be present in the tuple.
SeparateTickerids(_string)
You must form this single tickerID input string exactly as described in the scripts info panel (little gray 'i' that
is circled at the end of the settings in the settings/input panel that you can hover your cursor over this 'i' to read the
details of that particular input). IF the string is formed correctly then it will break up this single string parameter into
a total of 40 separate strings which will be all of the tickerIDs that the script is using in your MO scanner.
Parameters:
_string (simple string) : (string)
A maximum of 40 Tickers (ALL joined as 1 string for the input parameter) that is formulated EXACTLY as described
within the tooltips of the TickerID inputs in my MOS Scanner scripts:
assets = input.text_area(tIDset1, title="TickerID (MUST READ TOOLTIP)", tooltip="Accepts 40 TICKERID's for each
copy of the script on the chart. TEXT FORMATTING RULES FOR TICKERID'S:
(1) To exclude the EXCHANGE NAME in the Labels, de-select the next input option.
(2) MUST have a space (' ') AFTER each TickerID.
(3) Capitalization in the Labels will match cap of these TickerID's.
(4) If your asset has a BaseCurrency & QuoteCurrency (ie. ADAUSDT ) BUT you ONLY want Labels
to show BaseCurrency(ie.'ADA'), include a FORWARD SLASH ('/') between the Base & Quote (ie.'ADA/USDT')", display=display.none)
Returns: Returns 40 output variables of the different strings of TickerID's (ie. you need to output 40 variables within the
tuple ' ' regardless of if you were scanning using all possible (40) assets or not.
If your scanning for less than 40 assets, then once the variables are assigned to all of the tickerIDs, the rest
of the 40 variables in the tuple will be assigned "NA".
TickeridForLabelsAndSecurity(_includeExchange, _ticker)
This function accepts the TickerID Name as its parameter and produces a single string that will be used in all of your labels.
Parameters:
_includeExchange (simple bool) : (bool)
Optional(if parameter not included in function it defaults to false ).
Used to determine if the Exchange name will be included in all labels/triggers/alerts.
_ticker (simple string) : (string)
For this parameter, input the varible named '_coin' from your 'f_main()' function for this parameter. It is the raw
Ticker ID name that will be processed.
Returns: ( )
Returns 2 output variables:
1st ('_securityTickerid') is to be used in the 'request.security()' function as this string will contain everything
TV needs to pull the correct assets data.
2nd ('lblTicker') is to be used in all of the labels in your MOS as it will only contain what you want your labels
to show as determined by how the tickerID is formulated in the MOS's input.
InvalidTID(_tablePosition, _stackVertical, _close, _securityTickerid, _invalidArray)
This is to add a table in the middle right of your chart that prints all the TickerID's that were either not formulated
correctly in the '_source' input or that is not a valid symbol and should be changed.
Parameters:
_tablePosition (simple string) : (string)
Optional(if parameter not included, it defaults to position.middle_right). Location on the chart you want the table printed.
Possible strings include: position.top_center, position.top_left, position.top_right, position.middle_center,
position.middle_left, position.middle_right, position.bottom_center, position.bottom_left, position.bottom_right.
_stackVertical (simple bool) : (bool)
Optional(if parameter not included, it defaults to true). All of the assets that are counted as INVALID will be
created in a list. If you want this list to be prited as a column then input 'true' here.
_close (float) : (float)
If you want them printed as a single row then input 'false' here.
This should be the closing value of each of the assets being tested to determine in the TickerID is valid or not.
_securityTickerid (string) : (string)
Throughout the entire charts updates, if a '_close' value is never regestered then the logic counts the asset as INVALID.
This will be the 1st TickerID varible (named _securityTickerid) outputted from the tuple of the TickeridForLabels()
function above this one.
_invalidArray (string ) : (array string)
Input the array from the original script that houses all of the invalidArray strings.
Returns: (na)
Returns a table with the screened assets Invalid TickerID's. Table draws automatically if any are Invalid, thus,
no output variable to deal with.
LabelSizes(_barCnt, _lblSzRfrnce)
This function sizes your Alert Trigger Labels according to the amount of Printed Bars the chart has printed within
a set time period, while also keeping in mind the smallest relative reference size you input in the 'lblSzRfrnceInput'
parameter of this function. A HIGHER % of Printed Bars(aka...more trades occurring for that asset on the exchange),
the LARGER the Name Label will print, potentially showing you the better opportunities on the exchange to avoid
exchange manipulation liquidations.
*** SHOULD NOT be used as size of labels that are your asset Name Labels next to each asset's Line Plot...
if your MOS includes these as you want these to be the same size for every asset so the larger ones dont cover the
smaller ones if the plots are all close to each other ***
Parameters:
_barCnt (float) : (float)
Get the 1st variable('barCnt') from the 'PrintedBarCount' function's tuple and input it as this functions 1st input
parameter which will directly affect the size of the 2nd output variable ('alertTrigLabel') outputted by this function.
_lblSzRfrnce (string) : (string)
Optional(if parameter not included, it defaults to size.small). This will be the size of the 1st variable outputted
by this function ('assetNameLabel') BUT also affects the 2nd variable outputted by this function.
Returns: ( )
Returns 2 variables:
1st output variable ('AssetNameLabel') is assigned to the size of the 'lblSzRfrnceInput' parameter.
2nd output variable('alertTrigLabel') can be of variying sizes depending on the 'barCnt' parameter...BUT the smallest
size possible for the 2nd output variable ('alertTrigLabel') will be the size set in the 'lblSzRfrnceInput' parameter.
AssetColor()
This function is used to assign 40 different colors to 40 variables to be used for the different labels/plots.
Returns: Returns 40 output variables each with a different color assigned to them to be used in your plots & labels.
Regardless of if you have the maximum amount of assets your scanning(40 max) or less,
this function will assign 40 colors to 40 variables that you have between the ' '.
PrintedBarCount(_time, _barCntLength, _barCntPercentMin)
The Printed BarCount Filter looks back a User Defined amount of minutes and calculates the % of bars that have printed
out of the TOTAL amount of bars that COULD HAVE been printed within the same amount of time.
Parameters:
_time (int) : (int)
The time associated with the chart of the particular asset that is being screened at that point.
_barCntLength (int) : (int)
The amount of time (IN MINUTES) that you want the logic to look back at to calculate the % of bars that have actually
printed in the span of time you input into this parameter.
_barCntPercentMin (int) : (int)
The minimum % of Printed Bars of the asset being screened has to be GREATER than the value set in this parameter
for the output variable 'bc_gtg' to be true.
Returns: ( )
Returns 2 outputs:
1st is the % of Printed Bars that have printed within the within the span of time you input in the '_barCntLength' parameter.
2nd is true/false according to if the Printed BarCount % is above the threshold that you input into the '_barCntPercentMin' parameter.
RCI(_rciLength, _source, _interval)
You will see me using this a lot. DEFINITELY my favorite oscillator to utilize for SO many different things from
timing entries/exits to determining trends.Calculation of this indicator based on Spearmans Correlation.
Parameters:
_rciLength (int) : (int)
Amount of bars back to use in RCI calculations.
_source (float) : (float)
Source to use in RCI calculations (can use ANY source series. Ie, open,close,high,low,etc).
_interval (int) : (int)
Optional(if parameter not included, it defaults to 3). RCI calculation groups bars by this amount and then will.
rank these groups of bars.
Returns: (float)
Returns a single RCI value that will oscillates between -100 and +100.
RCIAVG(firstLength, _amtBtLengths, _rciSMAlen, _source, _interval)
20 RCI's are averaged together to get this RCI Avg (Rank Correlation Index Average). Each RCI (of the 20 total RCI)
has a progressively LARGER Lookback Length. Though the RCI Lengths are not individually adjustable,
there are 2 factors that ARE:
(1) the Lookback Length of the 1st RCI and
(2) the amount of values between one RCI's Lookback Length and the next.
*** If you set 'firstLength' to it's default of 200 and '_amtBtLengths' to it's default of 120 (aka AMOUNT BETWEEN LENGTHS=120)...
then RCI_2 Length=320, RCI_3 Length=440, RCI_4 Length=560, and so on.
Parameters:
firstLength (int) : (int)
Optional(if parameter is not included when the function is called, then it defaults to 200).
This parameter is the Lookback Length for the 1st RCI used in the RCI Avg.
_amtBtLengths (int) : (int)
Optional(if parameter not included when the function is called, then it defaults to 120).
This parameter is the value amount between each of the progressively larger lengths used for the 20 RCI's that
are averaged in the RCI Avg.
***** BEWARE ***** Too large of a value here will cause the calc to look back too far, causing an error(thus the value must be lowered)
_rciSMAlen (int) : (int)
Unlike the Single RCI Function, this function smooths out the end result using an SMA with a length value that is this parameter.
_source (float) : (float)
Source to use in RCI calculations (can use ANY source series. Ie, open,close,high,low,etc).
_interval (int) : (int)
Optional(if parameter not included, it defaults to 3). Within the RCI calculation, bars next to each other are grouped together
and then these groups are Ranked against each other. This parameter is the number of adjacent bars that are grouped together.
Returns: (float)
Returns a single RCI value that is the Avg of many RCI values that will oscillate between -100 and +100.
PercentChange(_startingValue, _endingValue)
This is a quick function to calculate how much % change has occurred between the '_startingValue' and the '_endingValue'
that you input into the function.
Parameters:
_startingValue (float) : (float)
The source value to START the % change calculation from.
_endingValue (float) : (float)
The source value to END the % change caluclation from.
Returns: Returns a single output being the % value between 0-100 (with trailing numbers behind a decimal). If you want only
a certain amount of numbers behind the decimal, this function needs to be put within a formatting function to do so.
Rescale(_source, _oldMin, _oldMax, _newMin, _newMax)
Rescales series with a known '_oldMin' & '_oldMax'. Use this when the scale of the '_source' to
rescale is known (bounded).
Parameters:
_source (float) : (float)
Source to be normalized.
_oldMin (int) : (float)
The known minimum of the '_source'.
_oldMax (int) : (float)
The known maximum of the '_source'.
_newMin (int) : (float)
What you want the NEW minimum of the '_source' to be.
_newMax (int) : (float)
What you want the NEW maximum of the '_source' to be.
Returns: Outputs your previously bounded '_source', but now the value will only move between the '_newMin' and '_newMax'
values you set in the variables.
Normalize_Historical(_source, _minimumLvl, _maximumLvl)
Normalizes '_source' that has a previously unknown min/max(unbounded) determining the max & min of the '_source'
FROM THE ENTIRE CHARTS HISTORY. ]
Parameters:
_source (float) : (float)
Source to be normalized.
_minimumLvl (int) : (float)
The Lower Boundary Level.
_maximumLvl (int) : (float)
The Upper Boundary Level.
Returns: Returns your same '_source', but now the value will MOSTLY stay between the minimum and maximum values you set in the
'_minimumLvl' and '_maximumLvl' variables (ie. if the source you input is an RSI...the output is the same RSI value but
instead of moving between 0-100 it will move between the maxand min you set).
Normailize_Local(_source, _length, _minimumLvl, _maximumLvl)
Normalizes series with previously unknown min/max(unbounded). Much like the Normalize_Historical function above this one,
but rather than using the Highest/Lowest Values within the ENTIRE charts history, this on looks for the Highest/Lowest
values of '_source' within the last ___ bars (set by user as/in the '_length' parameter. ]
Parameters:
_source (float) : (float)
Source to be normalized.
_length (int) : (float)
The amount of bars to look back to determine the highest/lowest '_source' value.
_minimumLvl (int) : (float)
The Lower Boundary Level.
_maximumLvl (int) : (float)
The Upper Boundary Level.
Returns: Returns a single output variable being the previously unbounded '_source' that is now normalized and bound between
the values used for '_minimumLvl'/'_maximumLvl' of the '_source' within the user defined lookback period.
SessionVolumeProfileLibrary "SessionVolumeProfile"
Analyzes price & volume during regular trading hours to provide a session volume profile analysis. The primary goal of this library is to provide the developer with three values: the value area high, low and the point of control. The library also provides methods for rendering the value areas and histograms. To learn more about this library and how you can use it, click on the website link in my profile where you will find a blog post with detailed information.
debug(vp, position)
Helper function to write some information about the supplied SVP object to the screen in a table.
Parameters:
vp (Object) : The SVP object to debug
position (string) : The position.* to place the table. Defaults to position.bottom_center
getLowerTimeframe()
Depending on the timeframe of the chart, determines a lower timeframe to grab volume data from for the analysis
Returns: The timeframe string to fetch volume for
get(volumeProfile, lowerTimeframeHigh, lowerTimeframeLow, lowerTimeframeVolume)
Populated the provided SessionVolumeProfile object with vp data on the session.
Parameters:
volumeProfile (Object) : The SessionVolumeProfile object to populate
lowerTimeframeHigh (float ) : The lower timeframe high values
lowerTimeframeLow (float ) : The lower timeframe low values
lowerTimeframeVolume (float ) : The lower timeframe volume values
drawPriorValueAreas(todaySessionVolumeProfile, extendYesterdayOverToday, showLabels, labelSize, pocColor, pocStyle, pocWidth, vahlColor, vahlStyle, vahlWidth, vaColor)
Given a SessionVolumeProfile Object, will render the historical value areas for that object.
Parameters:
todaySessionVolumeProfile (Object) : The SessionVolumeProfile Object to draw
extendYesterdayOverToday (bool) : Defaults to true
showLabels (bool) : Defaults to true
labelSize (string) : Defaults to size.small
pocColor (color) : Defaults to #e500a4
pocStyle (string) : Defaults to line.style_solid
pocWidth (int) : Defaults to 1
vahlColor (color) : The color of the value area high/low lines. Defaults to #1592e6
vahlStyle (string) : The style of the value area high/low lines. Defaults to line.style_solid
vahlWidth (int) : The width of the value area high/low lines. Defaults to 1
vaColor (color) : The color of the value area background. Defaults to #00bbf911)
drawHistogram(volumeProfile, bgColor, showVolumeOnHistogram)
Given a SessionVolumeProfile object, will render the histogram for that object.
Parameters:
volumeProfile (Object) : The SessionVolumeProfile object to draw
bgColor (color) : The baseline color to use for the histogram. Defaults to #00bbf9
showVolumeOnHistogram (bool) : Show the volume amount on the histogram bars. Defaults to false.
Object
Fields:
numberOfRows (series__integer)
valueAreaCoverage (series__integer)
trackDevelopingVa (series__bool)
valueAreaHigh (series__float)
pointOfControl (series__float)
valueAreaLow (series__float)
startTime (series__integer)
endTime (series__integer)
dayHigh (series__float)
dayLow (series__float)
step (series__float)
pointOfControlLevel (series__integer)
valueAreaHighLevel (series__integer)
valueAreaLowLevel (series__integer)
volumeRows (array__float)
priceLevelRows (array__float)
ltfSessionHighs (array__float)
ltfSessionLows (array__float)
ltfSessionVols (array__float)
Margin/Leverage CalculationMargin
This library calculates margin liquidation prices and quantities for long and short positions in your strategies.
Usage example
// ############################################################
// # INVESTMENT SETTINGS / INPUT
// ############################################################
// Get the investment capital from the properties tab of the strategy settings.
investment_capital = strategy.initial_capital
// Get the leverage from the properties tab of the strategy settings.
// The leverage is calculated from the order size for example: (300% = x3 leverage)
investment_leverage = margin.leverage()
// The maintainance rate and amount.
investment_leverage_maintenance_rate = input.float(title='Maintanance Rate (%)', defval=default_investment_leverage_maintenance_rate, minval=0, maxval=100, step=0.1, tooltip=tt_investment_leverage_maintenance_rate, group='MARGIN') / 100
investment_leverage_maintenance_amount = input.float(title='Maintanance Amount (%)', defval=default_investment_leverage_maintenance_amount, minval=0, maxval=100, step=0.1, tooltip=tt_investment_leverage_maintenance_amount, group='MARGIN')
// ############################################################
// # LIQUIDATION PRICES
// ############################################################
leverage_liquidation_price_long = 0.0
leverage_liquidation_price_long := na(leverage_liquidation_price_long ) ? na : leverage_liquidation_price_long
leverage_liquidation_price_short = 0.0
leverage_liquidation_price_short := na(leverage_liquidation_price_short ) ? na : leverage_liquidation_price_short
leverage_liquidation_price_long := margin.liquidation_price_long(investment_capital, strategy.position_avg_price, investment_leverage, investment_leverage_maintenance_rate, investment_leverage_maintenance_amount)
leverage_liquidation_price_short := margin.liquidation_price_short(investment_capital, strategy.position_avg_price, investment_leverage, investment_leverage_maintenance_rate, investment_leverage_maintenance_amount)
Get the qty for margin long or short position.
margin.qty_long(investment_capital, strategy.position_avg_price, investment_leverage, investment_leverage_maintenance_rate, investment_leverage_maintenance_amount)
margin.qty_short(investment_capital, strategy.position_avg_price, investment_leverage, investment_leverage_maintenance_rate, investment_leverage_maintenance_amount)
Get the price and qty for margin long or short position.
= margin.qty_long(investment_capital, strategy.position_avg_price, investment_leverage, investment_leverage_maintenance_rate, investment_leverage_maintenance_amount)
= margin.qty_short(investment_capital, strategy.position_avg_price, investment_leverage, investment_leverage_maintenance_rate, investment_leverage_maintenance_amount)
[Library] VAccThis is the library version of VAcc (Velocity & Acceleration), a momentum indicator published by Scott Cong in Stocks & Commodities V. 41:09 (8–15). It applies concepts from physics, namely velocity and acceleration, to financial markets. VAcc functions similarly to the popular MACD (Moving Average Convergence Divergence) indicator when using a longer lookback period, but produces more responsive results. With shorter periods, VAcc exhibits characteristics reminiscent of the stochastic oscillator.
The indicator version of this algorithm is linked below:
🟠 Algorithm
The average velocity over the past n periods is defined as
((C - C_n) / n + (C - C_{n-1}) / (n - 1) + … + (C - C_i) / i + (C - C_1) / 1) / n
At its core, the velocity is a weighted average of the rate of change over the past n periods.
The calculation of the acceleration follows a similar process, where it’s defined as
((V - V_n) / n + (V - V_{n - 1}) / (n - 1) + … + (V - V_i) / i + (V - V_1) / 1) / n
🟠 Comparison with MACD
A comparison of VAcc and MACD on the daily Nasdaq 100 (NDX) chart from August 2022 helps demonstrate VAcc's improved sensitivity. Both indicators utilized a lookback period of 26 days and smoothing of 9 periods.
The VAcc histogram clearly shows a divergence forming, with momentum weakening as prices reached new highs. In contrast, the corresponding MACD histogram significantly lagged in confirming the divergence, highlighting VAcc's ability to identify subtle shifts in trend momentum more immediately than the traditional MACD.
XLibrary "X"
a collection of 'special' methods/functions ('special' at the time of conception)
Initial functions includes:
• count of a given number in a given array
• array.get() but option added to use negative index
• sum of all digits until the output < 10
• slope/angle calculation of lines
method count_num_in_array(arr, num)
counts how many times a given number is present in a given array (0 when not present)
Namespace types: int
Parameters:
arr (int ) : Array (int, float )
num (int) : Number that needs to be counted (int, float)
Returns: count of number in array (0 when not present)
method count_num_in_array(arr, num)
Namespace types: float
Parameters:
arr (float )
num (float)
method get_(arr, idx)
array.get() but you can use negative index (-1 is last of array, -2 is second last,...)
Namespace types: int
Parameters:
arr (int ) : Array (int, float, string, bool, label, line, box, color )
idx (int) : Index
Returns: value/object at index, 'na' if index is outside array
method get_(arr, idx)
Namespace types: float
Parameters:
arr (float )
idx (int)
method get_(arr, idx)
Namespace types: string
Parameters:
arr (string )
idx (int)
method get_(arr, idx)
Namespace types: bool
Parameters:
arr (bool )
idx (int)
method get_(arr, idx)
Namespace types: label
Parameters:
arr (label )
idx (int)
method get_(arr, idx)
Namespace types: line
Parameters:
arr (line )
idx (int)
method get_(arr, idx)
Namespace types: box
Parameters:
arr (box )
idx (int)
method get_(arr, idx)
Namespace types: color
Parameters:
arr (color )
idx (int)
method sumAllNumbers_till_under_10(num)
sums all separate digit numbers, it repeats the process until sum < 10
Namespace types: series int, simple int, input int, const int
Parameters:
num (int) : Number (int, float)
Returns: value between 0 and 9
method sumAllNumbers_till_under_10(num)
Namespace types: series float, simple float, input float, const float
Parameters:
num (float)
method XYaxis(width)
Global function to calculate Yaxis, which is used in calculate_slope() method
Namespace types: series int, simple int, input int, const int
Parameters:
width (int) : Amount of bars for reference X-axis
Returns: Yaxis
method calculate_slope(width, XYratio, Yaxis, x1, y1, x2, y2)
Returns a normalised slope
Namespace types: series int, simple int, input int, const int
Parameters:
width (int) : Amount of bars to calculate height
XYratio (float) : Ratio to calculate height (from width) normalised_slope calculation
Yaxis (float) : Y-axis from XYaxis() method
x1 (int) : x1 of line
y1 (float) : y1 of line
x2 (int) : x2 of line
y2 (float) : y2 of line
Returns: Tuple of -> slope = price difference per bar
ZigLibLibrary "ZigLib"
Calculate the points for ZigZag++.
You can use custom data and resolution for your ZigZag++.
Sample Usage
import DevLucem/ZigLib/1 as ZigZag
= ZigZag.zigzag(low, high)
bgcolor(direction<0? color.rgb(255, 82, 82, 80): color.rgb(0, 230, 119, 80))
line zz = line.new(z1.time, z1.price, z2.time, z2.price, xloc.bar_time, width=3)
if direction==direction
line.delete(zz )
zigzag(_low, _high, depth, deviation, backstep)
Get current zigzag points and direction
Parameters:
_low (float)
_high (float)
depth (int)
deviation (int)
backstep (int)
Returns direction, chart point 1 and chart point 2
lib_retracement_patternsLibrary "lib_retracement_patterns"
types and functions for XABCD pattern detection and plotting
method set_tolerances(this, tolerance_Bmin, tolerance_Bmax, tolerance_Cmin, tolerance_Cmax, tolerance_Dmin, tolerance_Dmax)
sets tolerances for B, C and D retracements. This creates another Pattern instance that is set as tolerances field on the original and will be used for detection instead of the original ratios.
Namespace types: Pattern
create_config(pattern_line_args, pattern_point_args, name_label_args, retracement_line_args, retracement_label_args, line_args_Dtarget, line_args_completion, line_args_tp1, line_args_tp2, line_args_sl, label_args_completion, label_args_tp1, label_args_tp2, label_args_sl, label_terminal, label_terminal_up_char, label_terminal_down_char, color_bull, color_bear, color_muted, fill_opacity, draw_point_labels, draw_retracements, draw_target_range, draw_levels, hide_shorter_if_shared_legs_greater_than_max, hide_engulfed_pattern, hide_engulfed_pattern_of_same_type, hide_longer_pattern_with_same_X, mute_previous_pattern_when_next_overlaps, keep_failed_patterns)
method direction(this)
Namespace types: Match
method length(this)
return the length of this pattern, determined by the distance between X and D point
Namespace types: Match
method height(this)
return the height of this pattern, determined by the distance between the biggest distance between A/C and X/D
Namespace types: Match
method is_forming(this)
returns true if not complete, not expired and not invalidated
Namespace types: Match
method tostring(this)
return a string representation of all Matches in this map
Namespace types: Match
method tostring(this)
Namespace types: map
remove_complete_and_expired(this)
method add(this, item)
Namespace types: map
method is_engulfed_by(this, other)
checks if this Match is engulfed by the other
Namespace types: Match
method update(tracking_matches, zigzag, patterns, max_age_idx, detect_dir, pattern_minlen, pattern_maxlen, max_sub_waves, max_shared_legs, max_XB_BD_ratio, debug_log)
checks this map of tracking Matches if any of them was completed or invalidated in
Namespace types: map
method mute(this, mute_color, mute_fill_color)
mute this pattern by making it all one color (lines and labels, for pattern fill there's another)
Namespace types: Match
method mute(this, mute_color, mute_fill_color)
mute all patterns in this map by making it all one color (lines and labels, for pattern fill there's another)
Namespace types: map
method hide(this)
hide this pattern by muting it with a transparent color
Namespace types: Match
method reset_styles(this)
reset the style of a muted or hidden match back to the preset configuration
Namespace types: Match
method delete(this)
remove the plot of this Match from the chart
Namespace types: Match
method delete(this)
remove all the plots of the Matches in this map from the chart
Namespace types: map
method draw(this)
draw this Match on the chart
Namespace types: Match
method draw(this, config, all_patterns, debug_log)
draw all Matches in this map, considering all other patterns for engulfing and overlapping
Namespace types: map
method check_hide_or_mute(this, all, config, debug_log)
checks if this pattern needs to be hidden or muted based on other plotted patterns and given configuration
Namespace types: Match
method add_if(id, item, condition)
convenience function to add a search pattern to a list, only if given condition (input.bool) is true
Namespace types: Pattern
Pattern
type to hold retracement ratios and tolerances for this pattern, as well as targets for trades
Config
allows control of pattern plotting shape and colors, as well as settings for hiding overlapped patterns etc.
Match
holds all information on a Pattern and a successful match in the chart. Includes XABCD pivot points as well as all Line and Label objects to draw it
RationalQuadraticKernelFunctionDescription:
An optimised library for non-repainting Rational Quadratic Kernel Library. Added lookbackperiod and a validation to prevent division by zero.
Thanks to original author jdehorty.
Usage:
1. Import the library into your Pine Script code using the library function.
import vinayakavajiraya/RationalQuadraticKernelFunction/1
2. Call the Main Function:
Use the rationalQuadraticKernel function to calculate the Rational Quadratic Kernel estimate.
Provide the following parameters:
`_src` (series float): The input series of float values, typically representing price data.
`_lookback` (simple int): The lookback period for the kernel calculation (an integer).
`_relativeWeight` (simple float): The relative weight factor for the kernel (a float).
`startAtBar` (simple int): The bar index to start the calculation from (an integer).
rationalQuadraticEstimate = rationalQuadraticKernel(_src, _lookback, _relativeWeight, startAtBar)
3. Plot the Estimate:
Plot the resulting estimate on your TradingView chart using the plot function.
plot(rationalQuadraticEstimate, color = color.red, title = "Rational Quadratic Kernel Estimate")
Parameter Explanation:
`_src`: The input series of price data, such as 'close' or any other relevant data.
`_lookback`: The number of previous bars to consider when calculating the estimate. Higher values capture longer-term trends.
`_relativeWeight`: A factor that controls the importance of each data point in the calculation. A higher value emphasizes recent data.
`startAtBar`: The bar index from which the calculation begins.
Example Usage:
Here's an example of how to use the library to calculate and plot the Rational Quadratic Kernel estimate for the 'close' price series:
//@version=5
library("RationalQuadraticKernelFunctions", true)
rationalQuadraticEstimate = rationalQuadraticKernel(close, 11, 1, 24)
plot(rationalQuadraticEstimate, color = color.orange, title = "Rational Quadratic Kernel Estimate")
This example calculates the estimate for the 'close' price series, considers the previous 11 bars, assigns equal weight to all data points, and starts the calculation from the 24th bar. The result is plotted as an orange line on the chart.
Highly recommend to customize the parameters to suit your analysis needs and adapt the library to your trading strategies.
lib_retracement_labelLibrary "lib_retracement_label"
creates a retracement label between the origin and target of a retracement, updating it's position (via update + draw) when the target moves.
create_tooltip(name, min, max, tol_min, tol_max)
Parameters:
name (string)
min (float)
max (float)
tol_min (float)
tol_max (float)
method update(this)
Namespace types: RetracementLabel
Parameters:
this (RetracementLabel)
method create_retracement_label(this, move_endpoint, args, tooltip)
Creates a new RetracementLabel object.
Namespace types: D.Line
Parameters:
this (Line type from robbatt/lib_plot_objects/23)
move_endpoint (Point type from robbatt/lib_plot_objects/23)
args (LabelArgs type from robbatt/lib_plot_objects/23)
tooltip (string)
method create_retracement_label(this, move_end, args, tooltip)
Creates a new RetracementLabel object.
Namespace types: D.Line
Parameters:
this (Line type from robbatt/lib_plot_objects/23)
move_end (Pivot type from robbatt/lib_pivot/43)
args (LabelArgs type from robbatt/lib_plot_objects/23)
tooltip (string)
method enqueue(id, item, max)
Namespace types: RetracementLabel
Parameters:
id (RetracementLabel )
item (RetracementLabel)
max (int)
method draw(this)
Namespace types: RetracementLabel
Parameters:
this (RetracementLabel)
method draw(this)
Namespace types: RetracementLabel
Parameters:
this (RetracementLabel )
method delete(this)
Namespace types: RetracementLabel
Parameters:
this (RetracementLabel)
method delete(this)
Namespace types: RetracementLabel
Parameters:
this (RetracementLabel )
RetracementLabel
Fields:
move_endpoint (|robbatt/lib_plot_objects/23;Point|#OBJ)
center_label (|robbatt/lib_plot_objects/23;CenterLabel|#OBJ)