ZigzagMethodsLibrary "ZigzagMethods"
Object oriented implementation of Zigzag methods. Please refer to ZigzagTypes library for User defined types used in this library
tostring(this, sortKeys, sortOrder, includeKeys)
Converts ZigzagTypes/Pivot object to string representation
Parameters:
this : ZigzagTypes/Pivot
sortKeys : If set to true, string output is sorted by keys.
sortOrder : 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 : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of ZigzagTypes/Pivot
tostring(this, sortKeys, sortOrder, includeKeys)
Converts Array of Pivot objects to string representation
Parameters:
this : Pivot object array
sortKeys : If set to true, string output is sorted by keys.
sortOrder : 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 : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of Pivot object array
tostring(this)
Converts ZigzagFlags object to string representation
Parameters:
this : ZigzagFlags object
Returns: string representation of ZigzagFlags
tostring(this, sortKeys, sortOrder, includeKeys)
Converts ZigzagTypes/Zigzag object to string representation
Parameters:
this : ZigzagTypes/Zigzagobject
sortKeys : If set to true, string output is sorted by keys.
sortOrder : 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 : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of ZigzagTypes/Zigzag
calculate(this, ohlc, indicators, indicatorNames)
Calculate zigzag based on input values and indicator values
Parameters:
this : Zigzag object
ohlc : Array containing OHLC values. Can also have custom values for which zigzag to be calculated
indicators : Array of indicator values
indicatorNames : Array of indicator names for which values are present. Size of indicators array should be equal to that of indicatorNames
Returns: current Zigzag object
calculate(this)
Calculate zigzag based on properties embedded within Zigzag object
Parameters:
this : Zigzag object
Returns: current Zigzag object
nextlevel(this)
Calculate Next Level Zigzag based on the current calculated zigzag object
Parameters:
this : Zigzag object
Returns: Next Level Zigzag object
clear(this)
Clears zigzag drawings array
Parameters:
this : array
Returns: void
drawfresh(this)
draws fresh zigzag based on properties embedded in ZigzagDrawing object
Parameters:
this : ZigzagDrawing object
Returns: ZigzagDrawing object
drawcontinuous(this)
draws zigzag based on the zigzagmatrix input
Parameters:
this : ZigzagDrawing object
Returns:
Trendoscope
ZigzagTypesLibrary "ZigzagTypes"
Zigzag related user defined types. Depends on DrawingTypes library for basic types
Indicator
Indicator is collection of indicator values applied on high, low and close
Fields:
indicatorHigh : Indicator Value applied on High
indicatorLow : Indicator Value applied on Low
PivotCandle
PivotCandle represents data of the candle which forms either pivot High or pivot low or both
Fields:
_high : High price of candle forming the pivot
_low : Low price of candle forming the pivot
length : Pivot length
pHighBar : represents number of bar back the pivot High occurred.
pLowBar : represents number of bar back the pivot Low occurred.
pHigh : Pivot High Price
pLow : Pivot Low Price
indicators : Array of Indicators - allows to add multiple
Pivot
Pivot refers to zigzag pivot. Each pivot can contain various data
Fields:
point : pivot point coordinates
dir : direction of the pivot. Valid values are 1, -1, 2, -2
level : is used for multi level zigzags. For single level, it will always be 0
ratio : Price Ratio based on previous two pivots
indicatorNames : Names of the indicators applied on zigzag
indicatorValues : Values of the indicators applied on zigzag
indicatorRatios : 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 : true if the calculation resulted in new pivot
doublePivot : true if the calculation resulted in two pivots on same bar
updateLastPivot : true if new pivot calculated replaces the old one.
Zigzag
Zigzag object which contains whole zigzag calculation parameters and pivots
Fields:
length : Zigzag length. Default value is 5
numberOfPivots : max number of pivots to hold in the calculation. Default value is 20
offset : Bar offset to be considered for calculation of zigzag. Default is 0 - which means calculation is done based on the latest bar.
level : Zigzag calculation level - used in multi level recursive zigzags
zigzagPivots : array which holds the last n pivots calculated.
flags : ZigzagFlags object which is required for continuous drawing of zigzag lines.
ZigzagObject
Zigzag Drawing Object
Fields:
zigzagLine : Line joining two pivots
zigzagLabel : 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 : Zigzag line color. Default is color.blue
lineWidth : Zigzag line width. Default is 1
lineStyle : Zigzag line style. Default is line.style_solid.
showLabel : If set, the drawing will show labels on each pivot. Default is false
textColor : Text color of the labels. Only applicable if showLabel is set to true.
maxObjects : Max number of zigzag lines to display. Default is 300
xloc : 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:
properties : ZigzagProperties object which is used for setting the display styles of zigzag
drawings : array which contains lines and labels of zigzag drawing.
zigzag : Zigzag object which holds the calculations.
DrawingMethodsLibrary "DrawingMethods"
tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Point object to string representation
Parameters:
this : DrawingTypes/Point object
sortKeys : If set to true, string output is sorted by keys.
sortOrder : 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 : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Point
tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/LineProperties object to string representation
Parameters:
this : DrawingTypes/LineProperties object
sortKeys : If set to true, string output is sorted by keys.
sortOrder : 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 : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/LineProperties
tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Line object to string representation
Parameters:
this : DrawingTypes/Line object
sortKeys : If set to true, string output is sorted by keys.
sortOrder : 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 : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Line
tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/LabelProperties object to string representation
Parameters:
this : DrawingTypes/LabelProperties object
sortKeys : If set to true, string output is sorted by keys.
sortOrder : 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 : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/LabelProperties
tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Label object to string representation
Parameters:
this : DrawingTypes/Label object
sortKeys : If set to true, string output is sorted by keys.
sortOrder : 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 : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Label
tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Linefill object to string representation
Parameters:
this : DrawingTypes/Linefill object
sortKeys : If set to true, string output is sorted by keys.
sortOrder : 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 : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Linefill
tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/BoxProperties object to string representation
Parameters:
this : DrawingTypes/BoxProperties object
sortKeys : If set to true, string output is sorted by keys.
sortOrder : 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 : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/BoxProperties
tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/BoxText object to string representation
Parameters:
this : DrawingTypes/BoxText object
sortKeys : If set to true, string output is sorted by keys.
sortOrder : 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 : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/BoxText
tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Box object to string representation
Parameters:
this : DrawingTypes/Box object
sortKeys : If set to true, string output is sorted by keys.
sortOrder : 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 : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Box
delete(this)
Deletes line from DrawingTypes/Line object
Parameters:
this : DrawingTypes/Line object
Returns: Line object deleted
delete(this)
Deletes label from DrawingTypes/Label object
Parameters:
this : DrawingTypes/Label object
Returns: Label object deleted
delete(this)
Deletes Linefill from DrawingTypes/Linefill object
Parameters:
this : DrawingTypes/Linefill object
Returns: Linefill object deleted
delete(this)
Deletes box from DrawingTypes/Box object
Parameters:
this : DrawingTypes/Box object
Returns: DrawingTypes/Box object deleted
delete(this)
Deletes lines from array of DrawingTypes/Line objects
Parameters:
this : Array of DrawingTypes/Line objects
Returns: Array of DrawingTypes/Line objects
delete(this)
Deletes labels from array of DrawingTypes/Label objects
Parameters:
this : Array of DrawingTypes/Label objects
Returns: Array of DrawingTypes/Label objects
delete(this)
Deletes linefill from array of DrawingTypes/Linefill objects
Parameters:
this : Array of DrawingTypes/Linefill objects
Returns: Array of DrawingTypes/Linefill objects
delete(this)
Deletes boxes from array of DrawingTypes/Box objects
Parameters:
this : Array of DrawingTypes/Box objects
Returns: Array of DrawingTypes/Box objects
clear(this)
clear items from array of DrawingTypes/Line while deleting underlying objects
Parameters:
this : array
Returns: void
clear(this)
clear items from array of DrawingTypes/Label while deleting underlying objects
Parameters:
this : array
Returns: void
clear(this)
clear items from array of DrawingTypes/Linefill while deleting underlying objects
Parameters:
this : array
Returns: void
clear(this)
clear items from array of DrawingTypes/Box while deleting underlying objects
Parameters:
this : array
Returns: void
draw(this)
Creates line from DrawingTypes/Line object
Parameters:
this : DrawingTypes/Line object
Returns: line created from DrawingTypes/Line object
draw(this)
Creates lines from array of DrawingTypes/Line objects
Parameters:
this : Array of DrawingTypes/Line objects
Returns: Array of DrawingTypes/Line objects
draw(this)
Creates label from DrawingTypes/Label object
Parameters:
this : DrawingTypes/Label object
Returns: label created from DrawingTypes/Label object
draw(this)
Creates labels from array of DrawingTypes/Label objects
Parameters:
this : Array of DrawingTypes/Label objects
Returns: Array of DrawingTypes/Label objects
draw(this)
Creates linefill object from DrawingTypes/Linefill
Parameters:
this : DrawingTypes/Linefill objects
Returns: linefill object created
draw(this)
Creates linefill objects from array of DrawingTypes/Linefill objects
Parameters:
this : Array of DrawingTypes/Linefill objects
Returns: Array of DrawingTypes/Linefill used for creating linefills
draw(this)
Creates box from DrawingTypes/Box object
Parameters:
this : DrawingTypes/Box object
Returns: box created from DrawingTypes/Box object
draw(this)
Creates labels from array of DrawingTypes/Label objects
Parameters:
this : Array of DrawingTypes/Label objects
Returns: Array of DrawingTypes/Label objects
createLabel(this, lblText, tooltip, properties)
Creates DrawingTypes/Label object from DrawingTypes/Point
Parameters:
this : DrawingTypes/Point object
lblText : Label text
tooltip : Tooltip text. Default is na
properties : DrawingTypes/LabelProperties object. Default is na - meaning default values are used.
Returns: DrawingTypes/Label object
createLine(this, other, properties)
Creates DrawingTypes/Line object from one DrawingTypes/Point to other
Parameters:
this : First DrawingTypes/Point object
other : Second DrawingTypes/Point object
properties : DrawingTypes/LineProperties object. Default set to na - meaning default values are used.
Returns: DrawingTypes/Line object
createLinefill(this, other, fillColor, transparency)
Creates DrawingTypes/Linefill object from DrawingTypes/Line object to other DrawingTypes/Line object
Parameters:
this : First DrawingTypes/Line object
other : Other DrawingTypes/Line object
fillColor : fill color of linefill. Default is color.blue
transparency : fill transparency for linefill. Default is 80
Returns: Array of DrawingTypes/Linefill object
createBox(this, other, properties, textProperties)
Creates DrawingTypes/Box object from one DrawingTypes/Point to other
Parameters:
this : First DrawingTypes/Point object
other : Second DrawingTypes/Point object
properties : DrawingTypes/BoxProperties object. Default set to na - meaning default values are used.
textProperties : DrawingTypes/BoxText object. Default is na - meaning no text will be drawn
Returns: DrawingTypes/Box object
createBox(this, properties, textProperties)
Creates DrawingTypes/Box object from DrawingTypes/Line as diagonal line
Parameters:
this : Diagonal DrawingTypes/PoLineint object
properties : DrawingTypes/BoxProperties object. Default set to na - meaning default values are used.
textProperties : DrawingTypes/BoxText object. Default is na - meaning no text will be drawn
Returns: DrawingTypes/Box object
DrawingTypesLibrary "DrawingTypes"
User Defined Types for basic drawing structure. Other types and methods will be built on these.
Point
Point refers to point on chart
Fields:
price : pivot price
bar : pivot bar
bartime : pivot bar time
LineProperties
Properties of line object
Fields:
xloc : X Reference - can be either xloc.bar_index or xloc.bar_time. Default is xloc.bar_index
extend : Property which sets line to extend towards either right or left or both. Valid values are extend.right, extend.left, extend.both, extend.none. Default is extend.none
color : Line color
style : Line style, valid values are line.style_solid, line.style_dashed, line.style_dotted, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both. Default is line.style_solid
width : Line width. Default is 1
Line
Line object created from points
Fields:
start : Starting point of the line
end : Ending point of the line
properties : LineProperties object which defines the style of line
object : Derived line object
LabelProperties
Properties of label object
Fields:
xloc : X Reference - can be either xloc.bar_index or xloc.bar_time. Default is xloc.bar_index
yloc : Y reference - can be yloc.price, yloc.abovebar, yloc.belowbar. Default is yloc.price
color : Label fill color
style : Label style as defined in www.tradingview.com Default is label.style_none
textcolor : text color. Default is color.black
size : Label text size. Default is size.normal. Other values are size.auto, size.tiny, size.small, size.normal, size.large, size.huge
textalign : Label text alignment. Default if text.align_center. Other allowed values - text.align_right, text.align_left, text.align_top, text.align_bottom
text_font_family : The font family of the text. Default value is font.family_default. Other available option is font.family_monospace
Label
Label object
Fields:
point : Point where label is drawn
lblText : label text
tooltip : Tooltip text. Default is na
properties : LabelProperties object
object : Pine label object
Linefill
Linefill object
Fields:
line1 : First line to create linefill
line2 : Second line to create linefill
fillColor : Fill color
transparency : Fill transparency range from 0 to 100
object : linefill object created from wrapper
BoxProperties
BoxProperties object
Fields:
border_color : Box border color. Default is color.blue
bgcolor : box background color
border_width : Box border width. Default is 1
border_style : Box border style. Default is line.style_solid
extend : Extend property of box. default is extend.none
xloc : defines if drawing needs to be done based on bar index or time. default is xloc.bar_index
BoxText
Box Text properties.
Fields:
boxText : Text to be printed on the box
text_size : Text size. Default is size.auto
text_color : Box text color. Default is color.yellow.
text_halign : horizontal align style - default is text.align_center
text_valign : vertical align style - default is text.align_center
text_wrap : text wrap style - default is text.wrap_auto
text_font_family : Text font. Default is
Box
Box object
Fields:
p1 : Diagonal point one
p2 : Diagonal point two
properties : Box properties
textProperties : Box text properties
object : Box object created
eHarmonicpatternsLogScaleLibrary "eHarmonicpatternsLogScale"
Library provides functions to scan harmonic patterns both or normal and log scale
getSupportedPatterns()
get_prz_range(x, a, b, c, patternArray, errorPercent, start_adj, end_adj, logScale)
Provides PRZ range based on BCD and XAD ranges
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
patternArray : Pattern flags for which PRZ range needs to be calculated
errorPercent : Error threshold
start_adj : - Adjustments for entry levels
end_adj : - Adjustments for stop levels
logScale : - calculate on log scale. Default is false
Returns: Start and end of consolidated PRZ range
get_prz_range_xad(x, a, b, c, patternArray, errorPercent, start_adj, end_adj, logScale)
Provides PRZ range based on XAD range only
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
patternArray : Pattern flags for which PRZ range needs to be calculated
errorPercent : Error threshold
start_adj : - Adjustments for entry levels
end_adj : - Adjustments for stop levels
logScale : - calculate on log scale. Default is false
Returns: Start and end of consolidated PRZ range
get_projection_range(x, a, b, c, patternArray, errorPercent, start_adj, end_adj, logScale)
Provides Projection range based on BCD and XAD ranges
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
patternArray : Pattern flags for which PRZ range needs to be calculated
errorPercent : Error threshold
start_adj : - Adjustments for entry levels
end_adj : - Adjustments for stop levels
logScale : - calculate on log scale. Default is false
Returns: Array containing start and end ranges
isHarmonicPattern(x, a, b, c, d, flags, defaultEnabled, errorPercent, logScale)
Checks for harmonic patterns
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
d : D coordinate value
flags : flags to check patterns. Send empty array to enable all
defaultEnabled
errorPercent : Error threshold
logScale : - calculate on log scale. Default is false
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
isHarmonicProjection(x, a, b, c, flags, defaultEnabled, errorPercent, logScale)
Checks for harmonic pattern projection
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
flags : flags to check patterns. Send empty array to enable all
defaultEnabled
errorPercent : Error threshold
logScale : - calculate on log scale. Default is false
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names.
FibRatiosLibrary "FibRatios"
Library with calculation logic for fib retracement, extension and ratios
retracement(a, b, ratio, logScale, precision)
Calculates the retracement for points a, b with given ratio and scale
Parameters:
a : Starting point a
b : Second point b
ratio : Ratio for which we need to calculate retracement c
logScale : Flag to get calculations in log scale. Default is false
precision : rounding precision. If set to netagive number, round_to_mintick is applied. Default is -1
Returns: retracement point c for points a,b with given ratio and scale
retracementRatio(a, b, c, logScale, precision)
Calculates the retracement ratio for points a, b, c with given scale
Parameters:
a : Starting point a
b : Second point b
c : Retracement point. c should be placed between a and b
logScale : Flag to get calculations in log scale. Default is false
precision : rounding precision. If set to netagive number, round_to_mintick is applied. Default is 3
Returns: retracement ratio for points a,b,c on given scale
extension(a, b, c, ratio, logScale, precision)
Calculates the extensions for points a, b, c with given ratio and scale
Parameters:
a : Starting point a
b : Second point b
c : Retracement point. c should be placed between a and b
ratio : Ratio for which we need to calculate extension d
logScale : Flag to get calculations in log scale. Default is false
precision : rounding precision. If set to netagive number, round_to_mintick is applied. Default is -1
Returns: extensoin point d for points a,b,c with given ratio and scale
extensionRatio(a, b, c, d, logScale, precision)
Calculates the extension ratio for points a, b, c, d with given scale
Parameters:
a : Starting point a
b : Second point b
c : Retracement point. c should be placed between a and b
d : Extension point. d should be placed beyond a, c. But, can be with b,c or beyond b
logScale : Flag to get calculations in log scale. Default is false
precision : rounding precision. If set to netagive number, round_to_mintick is applied. Default is 3
Returns: extension ratio for points a,b,c,d on given scale
DataCorrelationLibrary "DataCorrelation"
Implementation of functions related to data correlation calculations. Formulas have been transformed in such a way that we avoid running loops and instead make use of time series to gradually build the data we need to perform calculation. This allows the calculations to run on unbound series, and/or higher number of samples
🎲 Simplifying Covariance
Original Formula
//For Sample
Covₓᵧ = ∑ ((xᵢ-x̄)(yᵢ-ȳ)) / (n-1)
//For Population
Covₓᵧ = ∑ ((xᵢ-x̄)(yᵢ-ȳ)) / n
Now, if we look at numerator, this can be simplified as follows
∑ ((xᵢ-x̄)(yᵢ-ȳ))
=> (x₁-x̄)(y₁-ȳ) + (x₂-x̄)(y₂-ȳ) + (x₃-x̄)(y₃-ȳ) ... + (xₙ-x̄)(yₙ-ȳ)
=> (x₁y₁ + x̄ȳ - x₁ȳ - y₁x̄) + (x₂y₂ + x̄ȳ - x₂ȳ - y₂x̄) + (x₃y₃ + x̄ȳ - x₃ȳ - y₃x̄) ... + (xₙyₙ + x̄ȳ - xₙȳ - yₙx̄)
=> (x₁y₁ + x₂y₂ + x₃y₃ ... + xₙyₙ) + (x̄ȳ + x̄ȳ + x̄ȳ ... + x̄ȳ) - (x₁ȳ + x₂ȳ + x₃ȳ ... xₙȳ) - (y₁x̄ + y₂x̄ + y₃x̄ + yₙx̄)
=> ∑xᵢyᵢ + n(x̄ȳ) - ȳ∑xᵢ - x̄∑yᵢ
So, overall formula can be simplified to be used in pine as
//For Sample
Covₓᵧ = (∑xᵢyᵢ + n(x̄ȳ) - ȳ∑xᵢ - x̄∑yᵢ) / (n-1)
//For Population
Covₓᵧ = (∑xᵢyᵢ + n(x̄ȳ) - ȳ∑xᵢ - x̄∑yᵢ) / n
🎲 Simplifying Standard Deviation
Original Formula
//For Sample
σ = √(∑(xᵢ-x̄)² / (n-1))
//For Population
σ = √(∑(xᵢ-x̄)² / n)
Now, if we look at numerator within square root
∑(xᵢ-x̄)²
=> (x₁² + x̄² - 2x₁x̄) + (x₂² + x̄² - 2x₂x̄) + (x₃² + x̄² - 2x₃x̄) ... + (xₙ² + x̄² - 2xₙx̄)
=> (x₁² + x₂² + x₃² ... + xₙ²) + (x̄² + x̄² + x̄² ... + x̄²) - (2x₁x̄ + 2x₂x̄ + 2x₃x̄ ... + 2xₙx̄)
=> ∑xᵢ² + nx̄² - 2x̄∑xᵢ
=> ∑xᵢ² + x̄(nx̄ - 2∑xᵢ)
So, overall formula can be simplified to be used in pine as
//For Sample
σ = √(∑xᵢ² + x̄(nx̄ - 2∑xᵢ) / (n-1))
//For Population
σ = √(∑xᵢ² + x̄(nx̄ - 2∑xᵢ) / n)
🎲 Using BinaryInsertionSort library
Chatterjee Correlation and Spearman Correlation functions make use of BinaryInsertionSort library to speed up sorting. The library in turn implements mechanism to insert values into sorted order so that load on sorting is reduced by higher extent allowing the functions to work on higher sample size.
🎲 Function Documentation
chatterjeeCorrelation(x, y, sampleSize, plotSize)
Calculates chatterjee correlation between two series. Formula is - ξnₓᵧ = 1 - (3 * ∑ |rᵢ₊₁ - rᵢ|)/ (n²-1)
Parameters:
x : First series for which correlation need to be calculated
y : Second series for which correlation need to be calculated
sampleSize : number of samples to be considered for calculattion of correlation. Default is 20000
plotSize : How many historical values need to be plotted on chart.
Returns: float correlation - Chatterjee correlation value if falls within plotSize, else returns na
spearmanCorrelation(x, y, sampleSize, plotSize)
Calculates spearman correlation between two series. Formula is - ρ = 1 - (6∑dᵢ²/n(n²-1))
Parameters:
x : First series for which correlation need to be calculated
y : Second series for which correlation need to be calculated
sampleSize : number of samples to be considered for calculattion of correlation. Default is 20000
plotSize : How many historical values need to be plotted on chart.
Returns: float correlation - Spearman correlation value if falls within plotSize, else returns na
covariance(x, y, include, biased)
Calculates covariance between two series of unbound length. Formula is Covₓᵧ = ∑ ((xᵢ-x̄)(yᵢ-ȳ)) / (n-1) for sample and Covₓᵧ = ∑ ((xᵢ-x̄)(yᵢ-ȳ)) / n for population
Parameters:
x : First series for which covariance need to be calculated
y : Second series for which covariance need to be calculated
include : boolean flag used for selectively including sample
biased : boolean flag representing population covariance instead of sample covariance
Returns: float covariance - covariance of selective samples of two series x, y
stddev(x, include, biased)
Calculates Standard Deviation of a series. Formula is σ = √( ∑(xᵢ-x̄)² / n ) for sample and σ = √( ∑(xᵢ-x̄)² / (n-1) ) for population
Parameters:
x : Series for which Standard Deviation need to be calculated
include : boolean flag used for selectively including sample
biased : boolean flag representing population covariance instead of sample covariance
Returns: float stddev - standard deviation of selective samples of series x
correlation(x, y, include)
Calculates pearson correlation between two series of unbound length. Formula is r = Covₓᵧ / σₓσᵧ
Parameters:
x : First series for which correlation need to be calculated
y : Second series for which correlation need to be calculated
include : boolean flag used for selectively including sample
Returns: float correlation - correlation between selective samples of two series x, y
HSupertrendLibrary "HSupertrend"
Supertrend implementation based on harmonic patterns
hsupertrend(zProperties, pProperties, errorPercent, showPatterns, patternColor)
derives supertrend based on harmonic patterns
Parameters:
zProperties : ZigzagProperties containing Zigzag length and source array
pProperties : PatternProperties used for calculation
errorPercent : Error threshold for scanning patterns
showPatterns : Draw identified patterns structure on chart
patternColor : Color of the pattern lines to be drawn
Returns:
ZigzagProperties
ZigzagProperties contains values required for zigzag calculation
Fields:
length : Zigzag length
source : Array containing custom OHLC. If not set, array.from(high, low) is used
PatternProperties
PatternProperties are essential pattern parameters used for calculation of bullish and bearish zones
Fields:
base : Base for calculating entry and stop of pattern. Can be CD, minmax or correction. Default is CD
entryPercent : Distance from D in terms of percent of Base in the direction of pattern
stopPercent : Distance from D in terms of percent of Base in the opposite direction of pattern
useClosePrices : When set uses close price for calculation of supertrend breakout
BinaryInsertionSortLibrary "BinaryInsertionSort"
Library containing functions which can help create sorted array based on binary insertion sort.
This sorting will be quicker than array.sort function if the sorting needs to be done on every bar and the size of the array is comparatively big.
This is created with the intention of using this to solve a bigger problem posted by @lejmer. Wish me luck!!
binary_insertion_sort(sortedArray, item, order)
binary insertion sort - inserts item into sorted array while maintaining sort order
Parameters:
sortedArray : array which is assumed to be sorted in the requested order
item : float|int item which needs to be inserted into sorted array
order : Sort order - positive number means ascending order whereas negative number represents descending order
Returns: int index at which the item is inserted into sorted array
update_sort_indices(sortIndices, newItemIndex)
adds the sort index of new item added to sorted array and also updates existing sort indices.
Parameters:
sortIndices : array containing sort indices of an array.
newItemIndex : sort index of new item added to sorted array
Returns: void
get_array_of_series(item, order)
Converts series into array and sorted array.
Parameters:
item : float|int series
order : Sort order - positive number means ascending order whereas negative number represents descending order
Returns:
get_sorted_arrays(item, order)
Converts series into array and sorted array. Also calculates the sort order of the value array
Parameters:
item : float|int series
order : Sort order - positive number means ascending order whereas negative number represents descending order
Returns:
taLibrary "ta"
Collection of all custom and enhanced TA indicators. Same as enhanced_ta. But, removed all the displays to make it faster.
ma(source, maType, length)
returns custom moving averages
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
Returns: moving average for the given type and length
atr(maType, length)
returns ATR with custom moving average
Parameters:
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
Returns: ATR for the given moving average type and length
atrpercent(maType, length)
returns ATR as percentage of close price
Parameters:
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
Returns: ATR as percentage of close price for the given moving average type and length
bb(source, maType, length, multiplier, sticky)
returns Bollinger band for custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Bollinger band with custom moving average for given source, length and multiplier
bbw(source, maType, length, multiplier, sticky)
returns Bollinger bandwidth for custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Bollinger Bandwidth for custom moving average for given source, length and multiplier
bpercentb(source, maType, length, multiplier, sticky)
returns Bollinger Percent B for custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Bollinger Percent B for custom moving average for given source, length and multiplier
kc(source, maType, length, multiplier, useTrueRange, sticky)
returns Keltner Channel for custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
useTrueRange : - if set to false, uses high-low.
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Keltner Channel for custom moving average for given souce, length and multiplier
kcw(source, maType, length, multiplier, useTrueRange, sticky)
returns Keltner Channel Width with custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
useTrueRange : - if set to false, uses high-low.
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Keltner Channel Width for custom moving average
kpercentk(source, maType, length, multiplier, useTrueRange, sticky)
returns Keltner Channel Percent K Width with custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
useTrueRange : - if set to false, uses high-low.
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Keltner Percent K for given moving average, source, length and multiplier
dc(length, useAlternateSource, alternateSource, sticky)
returns Custom Donchian Channel
Parameters:
length : - donchian channel length
useAlternateSource : - Custom source is used only if useAlternateSource is set to true
alternateSource : - Custom source
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Donchian channel
dcw(length, useAlternateSource, alternateSource, sticky)
returns Donchian Channel Width
Parameters:
length : - donchian channel length
useAlternateSource : - Custom source is used only if useAlternateSource is set to true
alternateSource : - Custom source
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Donchian channel width
dpercentd(useAlternateSource, alternateSource, length, sticky)
returns Donchian Channel Percent of price
Parameters:
useAlternateSource : - Custom source is used only if useAlternateSource is set to true
alternateSource : - Custom source
length : - donchian channel length
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Donchian channel Percent D
oscillatorRange(source, method, highlowLength, rangeLength, sticky)
oscillatorRange - returns Custom overbought/oversold areas for an oscillator input
Parameters:
source : - Osillator source such as RSI, COG etc.
method : - Valid values for method are : sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
highlowLength : - length on which highlow of the oscillator is calculated
rangeLength : - length used for calculating oversold/overbought range - usually same as oscillator length
sticky : - overbought, oversold levels won't change unless crossed
Returns: Dynamic overbought and oversold range for oscillator input
oscillator(type, length, shortLength, longLength, source, highSource, lowSource, method, highlowLength, sticky)
oscillator - returns Choice of oscillator with custom overbought/oversold range
Parameters:
type : - oscillator type. Valid values : cci, cmo, cog, mfi, roc, rsi, stoch, tsi, wpr
length : - Oscillator length - not used for TSI
shortLength : - shortLength only used for TSI
longLength : - longLength only used for TSI
source : - custom source if required
highSource : - custom high source for stochastic oscillator
lowSource : - custom low source for stochastic oscillator
method : - Valid values for method are : sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
highlowLength : - length on which highlow of the oscillator is calculated
sticky : - overbought, oversold levels won't change unless crossed
Returns: Oscillator value along with dynamic overbought and oversold range for oscillator input
multibands(bandType, source, maType, length, useTrueRange, sticky, numberOfBands, multiplierStart, multiplierStep)
multibands - returns Choice of oscillator with custom overbought/oversold range
Parameters:
bandType : - Band type - can be either bb or kc
source : - custom source if required
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : - Oscillator length - not used for TSI
useTrueRange : - if set to false, uses high-low.
sticky : - for sticky borders which only change upon source crossover/crossunder
numberOfBands : - Number of bands to generate
multiplierStart : - Starting ATR or Standard deviation multiplier for first band
multiplierStep : - Incremental value for multiplier for each band
Returns: array of band values sorted in ascending order
mbandoscillator(bandType, source, maType, length, useTrueRange, stickyBands, numberOfBands, multiplierStart, multiplierStep)
mbandoscillator - Multiband oscillator created on the basis of bands
Parameters:
bandType : - Band type - can be either bb or kc
source : - custom source if required
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : - Oscillator length - not used for TSI
useTrueRange : - if set to false, uses high-low.
stickyBands : - for sticky borders which only change upon source crossover/crossunder for band detection
numberOfBands : - Number of bands to generate
multiplierStart : - Starting ATR or Standard deviation multiplier for first band
multiplierStep : - Incremental value for multiplier for each band
Returns: oscillator currentStates - Array containing states for last n bars
strategyLibrary "strategy"
Library containing few key calculations for strategy involving leveraged limit and stop orders
getQty(entry, stop, riskPercentage)
calculate qty and leverage based on entry and stop price for given risk percentage.
Parameters:
entry : Entry Price
stop : Stop Price
riskPercentage : risk percentage per trade
Returns: - Quantity based on the risk and calculated leverage on position including existing positions
bracketOrder(entry, stop, target, maxLeverage, isLimitOrder, riskPercentage)
Calculates position size based on risk and creates bracket orders for given entry/stop/target
Parameters:
entry : Entry Price
stop : Stop Price
target : Target Price
maxLeverage : Maximum leverage allowed
isLimitOrder : if true, places limit order for entry, else places stop order.
riskPercentage : risk percentage per trade
Returns: orderPlaced - true if orders successfully placed, false otherwise.
order(entry, stop, maxLeverage, isLimitOrder, riskPercentage)
Calculates position size based on risk and creates order for given entry/stop
Parameters:
entry : Entry Price
stop : Stop Price
maxLeverage : Maximum leverage allowed
isLimitOrder : if true, places limit order for entry, else places stop order.
riskPercentage : risk percentage per trade
Returns: orderPlaced - true if orders successfully placed, false otherwise.
ahpuhelperLibrary "ahpuhelper"
Helper Library for Auto Harmonic Patterns UltimateX. It is not meaningful for others. This is supposed to be private library. But, publishing it to make sure that I don't delete accidentally. Some functions may be useful for coders.
insert_open_trades_table_column(showOpenTrades, table_id, column, colors, values, intStatus, harmonicTrailingStartState, lblSizeOpenTrades)
add data to open trades table column
Parameters:
showOpenTrades : flag to show open trades table
table_id : Table Id
column : refers to pattern data
colors : backgroud and text color array
values : cell values
intStatus : status as integer
harmonicTrailingStartState : trailing Start state as per configs
lblSizeOpenTrades : text size
Returns: nextColumn
populate_closed_stats(ClosedStatsPosition, bullishCounts, bearishCounts, bullishRetouchCounts, bearishRetouchCounts, bullishSizeMatrix, bearishSizeMatrix, bullishRR, bearishRR, allPatternLabels, flags, rowMain, rowHeaders)
populate closed stats for harmonic patterns
Parameters:
ClosedStatsPosition : Table position for closed stats
bullishCounts : Matrix containing bullish trade stats
bearishCounts : Matrix containing bearish trade stats
bullishRetouchCounts : Matrix containing bullish trade stats for those which retouched entry
bearishRetouchCounts : Matrix containing bearish trade stats for those which retouched entry
bullishSizeMatrix : Matrix containing data about size of bullish patterns
bearishSizeMatrix : Matrix containing data about size of bearish patterns
bullishRR : Matrix containing Risk Reward data of bullish patterns
bearishRR : Matrix containing Risk Reward data of bearish patterns
allPatternLabels : array containing pattern labels
flags : display flags
rowMain : Pattern header data
rowHeaders : header grouping data
Returns: void
get_rr_details(patternTradeDetails, harmonicTrailingStartState, disableTrail, breakEvenTrail)
calculate and return risk reward based on targets and stops
Parameters:
patternTradeDetails : array containing stop, entry and targets
harmonicTrailingStartState : trailing point
disableTrail : If set, ignores trailing point
breakEvenTrail : If set, trailing does not go beyond breakeven.
Returns: nextColumn
drawcandlesLibrary "drawcandles"
simple utility to draw different candles using box and lines. Quite useful for drawing candles such as zigzag candles or MTF candles
draw(o, h, l, c, oBar, cBar)
draws candles based on ohlc values
Parameters:
o : Open Price
h : High Price
l : Low Price
c : Close Price
oBar : Open Time
cBar : Close Time
Returns: void
arraysLibrary "arrays"
Library contains utility functions using arrays.
delete( arr , index)
remove an item from array at specific index. Also deletes the item
Parameters:
arr: - array from which the item needs to be deleted
index: - index of item to be deleted
Returns: void
pop( arr )
remove the last item from array. Also deletes the item
Parameters:
arr: - array from which the last item needs to be removed and deleted
Returns: void
shift( arr )
remove an item from array at index 0. Also deletes the item
Parameters:
arr: - array from which the first item needs to be removed and deleted
Returns: void
unshift( arr , val, maxItems)
add an item to the beginning of an array with max items cap
Parameters:
arr: - array to which the item needs to be added at the beginning
val: - value of item which needs to be added
maxItems: - max items array can hold. After that, items are removed from the other end
Returns: resulting array
clear( arr )
remove and delete all items in an array
Parameters:
arr: - array which needs to be cleared
Returns: void
push( arr , val, maxItems)
add an item to the end of an array with max items cap
Parameters:
arr: - array to which the item needs to be added at the beginning
val: - value of item which needs to be added
maxItems: - max items array can hold. After that, items are removed from the starting index
Returns: resulting array
mZigzagLibrary "mZigzag"
Matrix implementation of zigzag to allow further possibilities.
Main advantage of this library over previous zigzag methods is that you can attach any number of indicator/oscillator information to zigzag
calculate(length, ohlc, indicatorHigh, indicatorLow, numberOfPivots) calculates zigzag and related information
Parameters:
length : is zigzag length
ohlc : array of OHLC values to be used for zigzag calculation
indicatorHigh : Array of indicator values calculated based on high price of OHLC
indicatorLow : Array of indicators values calculated based on low price of OHLC
numberOfPivots : Number of pivots to be returned
Returns: pivotMatrix Matrix containing zigzag pivots, pivot bars, direction, ratio, and indicators added via indicatorHigh/indicatorLow
newZG is true if a new pivot is added to array
doubleZG is true if last calculation returned two new pivots (Happens on extreme price change)
draw(length, ohlc, indicatorLabels, indicatorHigh, indicatorLow, numberOfPivots, lineColor, lineWidth, lineStyle, showHighLow, showRatios, showIndicators) draws zigzag and related information
Parameters:
length : is zigzag length
ohlc : array of OHLC values to be used for zigzag calculation
indicatorLabels : Array of name of indicators passed
indicatorHigh : Array of indicator values calculated based on high price of OHLC
indicatorLow : Array of indicators values calculated based on low price of OHLC
numberOfPivots : Number of pivots to be returned
lineColor : zigzag line color. set to blue by default
lineWidth : zigzag line width. set to 1 by default
lineStyle : zigzag line style. set to line.style_solid by default
showHighLow : show HH, HL, LH, LL labels
showRatios : show pivot retracement ratios from previous zigzag
showIndicators : show indicator values
Returns: pivotMatrix Matrix containing zigzag pivots, pivot bars, direction, ratio, and indicators added via indicatorHigh/indicatorLow
zigzaglines array of zigzag lines
zigzaglabels array of zigzag labels
eHarmonicpatternsExtendedLibrary "eHarmonicpatternsExtended"
Library provides an alternative method to scan harmonic patterns. This is helpful in reducing iterations. Republishing as new library instead of existing eHarmonicpatterns because I need that copy for existing scripts.
scan_xab(bcdRatio, err_min, err_max, patternArray) Checks if bcd ratio is in range of any harmonic pattern
Parameters:
bcdRatio : AB/XA ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_abc_axc(abcRatio, axcRatio, err_min, err_max, patternArray) Checks if abc or axc ratio is in range of any harmonic pattern
Parameters:
abcRatio : BC/AB ratio
axcRatio : XC/AX ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_bcd(bcdRatio, err_min, err_max, patternArray) Checks if bcd ratio is in range of any harmonic pattern
Parameters:
bcdRatio : CD/BC ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_xad_xcd(xadRatio, xcdRatio, err_min, err_max, patternArray) Checks if xad or xcd ratio is in range of any harmonic pattern
Parameters:
xadRatio : AD/XA ratio
xcdRatio : CD/XC ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
isHarmonicPattern(x, a, b, c, d, flags, errorPercent) Checks for harmonic patterns
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
d : D coordinate value
flags : flags to check patterns. Send empty array to enable all
errorPercent : Error threshold
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
isHarmonicProjection(x, a, b, c, flags, errorPercent) Checks for harmonic pattern projection
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
flags : flags to check patterns. Send empty array to enable all
errorPercent : Error threshold
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names.
get_prz_range(x, a, b, c, patternArray, errorPercent, start_adj, end_adj) Provides PRZ range based on BCD and XAD ranges
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
patternArray : Pattern flags for which PRZ range needs to be calculated
errorPercent : Error threshold
start_adj : - Adjustments for entry levels
end_adj : - Adjustments for stop levels
Returns: Start and end of consolidated PRZ range
get_prz_range_xad(x, a, b, c, patternArray, errorPercent, start_adj, end_adj) Provides PRZ range based on XAD range only
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
patternArray : Pattern flags for which PRZ range needs to be calculated
errorPercent : Error threshold
start_adj : - Adjustments for entry levels
end_adj : - Adjustments for stop levels
Returns: Start and end of consolidated PRZ range
eStrategyLibrary "eStrategy"
Library contains methods which can help build custom strategy for continuous investment plans and also compare it with systematic buy and hold.
sip(startYear, initialDeposit, depositFrequency, recurringDeposit, buyPrice) Depicts systematic buy and hold over period of time
Parameters:
startYear : Year on which SIP is started
initialDeposit : Initial one time investment at the start
depositFrequency : Frequency of recurring deposit - can be monthly or weekly
recurringDeposit : Recurring deposit amount
buyPrice : Indicatinve buy price. Use high to be conservative. low, close, open, hl2, hlc3, ohlc4, hlcc4 are other options.
Returns: totalInvestment - initial + recurring deposits
totalQty - Quantity of units held for given instrument
totalEquity - Present equity
customStrategy(startYear, initialDeposit, depositFrequency, recurringDeposit, buyPrice, sellPrice, initialInvestmentPercent, recurringInvestmentPercent, signal, tradePercent) Allows users to define custom strategy and enhance systematic buy and hold by adding take profit and reloads
Parameters:
startYear : Year on which SIP is started
initialDeposit : Initial one time investment at the start
depositFrequency : Frequency of recurring deposit - can be monthly or weekly
recurringDeposit : Recurring deposit amount
buyPrice : Indicatinve buy price. Use high to be conservative. low, close, open, hl2, hlc3, ohlc4, hlcc4 are other options.
sellPrice : Indicatinve sell price. Use low to be conservative. high, close, open, hl2, hlc3, ohlc4, hlcc4 are other options.
initialInvestmentPercent : percent of amount to invest from the initial depost. Keep rest of them as cash
recurringInvestmentPercent : percent of amount to invest from recurring deposit. Keep rest of them as cash
signal : can be 1, -1 or 0. 1 means buy/reload. -1 means take profit and 0 means neither.
tradePercent : percent of amount to trade when signal is not 0. If taking profit, it will sell the percent from existing position. If reloading, it will buy with percent from cash reserve
Returns: totalInvestment - initial + recurring deposits
totalQty - Quantity of units held for given instrument
totalCash = Amount of cash held
totalEquity - Overall equity = totalQty*close + totalCash
historicalrangeLibrary "historicalrange"
Library provices a method to calculate historical percentile range of series.
hpercentrank(source) calculates historical percentrank of the source
Parameters:
source : Source for which historical percentrank needs to be calculated. Source should be ranging between 0-100. If using a source which can beyond 0-100, use short term percentrank to baseline them.
Returns: pArray - percentrank array which contains how many instances of source occurred at different levels.
upperPercentile - percentile based on higher value
lowerPercentile - percentile based on lower value
median - median value of the source
max - max value of the source
distancefromath(source) returns stats on historical distance from ath in terms of percentage
Parameters:
source : for which stats are calculated
Returns: percentile and related historical stats regarding distance from ath
distancefromma(maType, length, source) returns stats on historical distance from moving average in terms of percentage
Parameters:
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
source : for which stats are calculated
Returns: percentile and related historical stats regarding distance from ath
bpercentb(source, maType, length, multiplier, sticky) returns percentrank and stats on historical bpercentb levels
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: percentile and related historical stats regarding Bollinger Percent B
kpercentk(source, maType, length, multiplier, useTrueRange, sticky) returns percentrank and stats on historical kpercentk levels
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
useTrueRange : - if set to false, uses high-low.
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: percentile and related historical stats regarding Keltener Percent K
dpercentd(useAlternateSource, alternateSource, length, sticky) returns percentrank and stats on historical dpercentd levels
Parameters:
useAlternateSource : - Custom source is used only if useAlternateSource is set to true
alternateSource : - Custom source
length : - donchian channel length
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: percentile and related historical stats regarding Donchian Percent D
oscillator(type, length, shortLength, longLength, source, highSource, lowSource, method, highlowLength, sticky) oscillator - returns Choice of oscillator with custom overbought/oversold range
Parameters:
type : - oscillator type. Valid values : cci, cmo, cog, mfi, roc, rsi, stoch, tsi, wpr
length : - Oscillator length - not used for TSI
shortLength : - shortLength only used for TSI
longLength : - longLength only used for TSI
source : - custom source if required
highSource : - custom high source for stochastic oscillator
lowSource : - custom low source for stochastic oscillator
method : - Valid values for method are : sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
highlowLength : - length on which highlow of the oscillator is calculated
sticky : - overbought, oversold levels won't change unless crossed
Returns: percentile and related historical stats regarding oscillator
eHarmonicpatternsLibrary "eHarmonicpatterns"
Library provides an alternative method to scan harmonic patterns. This is helpful in reducing iterations
scan_xab(bcdRatio, err_min, err_max, patternArray) Checks if bcd ratio is in range of any harmonic pattern
Parameters:
bcdRatio : AB/XA ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_abc_axc(abcRatio, axcRatio, err_min, err_max, patternArray) Checks if abc or axc ratio is in range of any harmonic pattern
Parameters:
abcRatio : BC/AB ratio
axcRatio : XC/AX ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_bcd(bcdRatio, err_min, err_max, patternArray) Checks if bcd ratio is in range of any harmonic pattern
Parameters:
bcdRatio : CD/BC ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_xad_xcd(xadRatio, xcdRatio, err_min, err_max, patternArray) Checks if xad or xcd ratio is in range of any harmonic pattern
Parameters:
xadRatio : AD/XA ratio
xcdRatio : CD/XC ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
isHarmonicPattern(x, a, c, c, d, flags, errorPercent) Checks for harmonic patterns
Parameters:
x : X coordinate value
a : A coordinate value
c : B coordinate value
c : C coordinate value
d : D coordinate value
flags : flags to check patterns. Send empty array to enable all
errorPercent : Error threshold
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
isHarmonicProjection(x, a, c, c, flags, errorPercent) Checks for harmonic pattern projection
Parameters:
x : X coordinate value
a : A coordinate value
c : B coordinate value
c : C coordinate value
flags : flags to check patterns. Send empty array to enable all
errorPercent : Error threshold
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names