PitchforkTypesLibrary "PitchforkTypes"
User Defined Types to be used for Pitchfork and Drawing elements of Pitchfork. Depends on DrawingTypes for Point, Line, and LineProperties objects
PitchforkDrawingProperties
Pitchfork Drawing Properties object
Fields:
extend : If set to true, forks are extended towards right. Default is true
fill : Fill forklines with transparent color. Default is true
fillTransparency : Transparency at which fills are made. Only considered when fill is set. Default is 80
forceCommonColor : Force use of common color for forks and fills. Default is false
commonColor : common fill color. Used only if ratio specific fill colors are not available or if forceCommonColor is set to true.
PitchforkDrawing
Pitchfork drawing components
Fields:
medianLine : Median line of the pitchfork
baseLine : Base line of the pitchfork
forkLines : fork lines of the pitchfork
linefills : Linefills between forks
Fork
Fork object property
Fields:
ratio : Fork ratio
forkColor : color of fork. Default is blue
include : flag to include the fork in drawing. Default is true
PitchforkProperties
Pitchfork Properties
Fields:
forks : Array of Fork objects
type : Pitchfork type. Supported values are "regular", "schiff", "mschiff", Default is regular
inside : Flag to identify if to draw inside fork. If set to true, inside fork will be drawn
Pitchfork
Pitchfork object
Fields:
a : Pivot Point A of pitchfork
b : Pivot Point B of pitchfork
c : Pivot Point C of pitchfork
properties : PitchforkProperties object which determines type and composition of pitchfork
dProperties : Drawing properties for pitchfork
lProperties : Common line properties for Pitchfork lines
drawing : PitchforkDrawing object
Techindicator
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:
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
Liquidation_linesLibrary "Liquidationline"
f_calculateLeverage(_leverage, _maintainance, _value, _direction)
Parameters:
_leverage
_maintainance
_value
_direction
f_liqline_update(_Liqui_Line, _killonlowhigh)
Parameters:
_Liqui_Line
_killonlowhigh
f_liqline_draw(_Liqui_Line, _priceorliq)
Parameters:
_Liqui_Line
_priceorliq
f_liqline_add(_Liqui_Line, linetoadd, _limit)
Parameters:
_Liqui_Line
linetoadd
_limit
Liquidationline
Fields:
creationtime
stoptime
price
leverage
maintainance
line_active
line_color
line_thickness
line_style
line_direction
line_finished
text_active
text_size
text_color
this library can draw typical liquidation lines, which can be called e.g. by indicator signals
You can see the default implementation in the lower part of the code, starting with RUNTIME
Don't forget to increase max lines to 500 in your script.
It can look like this screenshot here, with only minor changes to your executing script.
The base is the same
AntaresLibrary "Antares"
this library contains some utility functions that I use in my open source scripts including moving average helpers, candlstick helpers, money management, formatters, convertors, webhook integration, analysis, filters and drawing helpers
ma(type, length, source)
Wraps all ma functions
Parameters:
type : Either SMA or EMA or RMA or WMA or VWMA
length : Number of bars (length).
source : Series of values to process.
Returns: Moving average of `source` for `length` bars back by the of MA.
bb(ma, length, mult, source)
Overwrites `ta.bb` duo to limitations of simple int.float mult. Bollinger Bands. A Bollinger Band is a technical analysis tool defined by a set of lines plotted two standard deviations (positively and negatively) away from a simple moving average (SMA) of the security's price, but can be adjusted to user preferences.
Parameters:
ma : Either SMA or EMA or RMA or WMA or VWMA
length : Number of bars (length).
mult : Standard deviation factor.
source : Series of values to process.
Returns: Bollinger Bands.
atr(length, h, l, c)
Overwrites `ta.atr` duo to limitations of simple int length. Function atr (average true range) returns the RMA of true range. True range is max(high - low, abs(high - close ), abs(low - close )).
Parameters:
length : Number of bars (length).
h : High price high price.
l : low price.
c : Close price close price.
Returns: Average true range.
rsi(length, source)
Overwrites `ta.rsi` duo to limitations of simple int length. Relative strength index. It is calculated using the `ta.rma()` of upward and downward changes of `source` over the last `length` bars.
Parameters:
length : Number of bars (length).
source : Series of values to process.
Returns: Relative strength index.
lowest(length, source, start)
Lowest value for a given number of bars back.
Parameters:
length : Number of bars (length).
source : Series of values to process.
start : Series number of bars that should be skipped before process.
Returns: Lowest value in the series.
highest(length, source, start)
Highest value for a given number of bars back.
Parameters:
length : Number of bars (length).
source : Series of values to process.
start : Series number of bars that should be skipped before process.
Returns: Highest value in the series.
atr_multiplier(rsi, atr_max_multiplier)
Dynamic atr multiplier calculated by RSI.
Parameters:
rsi : Relative strength index.
atr_max_multiplier : The maximum multiplier of atr
Returns: Dynamic multiplier of ATR
offset(atr, atr_multiplier)
Safe dynamic offset you need to use in your stoploss, stop buy/sell, etc.
Parameters:
atr : Average true range.
atr_multiplier : ATR multiplier got from `atr_multiplier(rsi, atr_max_multiplier)`
Returns: Dynamic offset
rsi_emotional(rsi, bottom, top)
Tells you if RSI is in emotional zone.
Parameters:
rsi : Relative Strength Index
bottom : The zone that below it market reacts emotionally
top : The zone that above it market reacts emotionally
Returns: false if RSI was between `bottom` and `top` otherwise true
rsi_signal(rsi, bottom, top)
Tells you if RSI is in good point to check your other strategy conditions.
Parameters:
rsi : Relative Strength Index
bottom : The zone that below it market reacts emotionally
top : The zone that above it market reacts emotionally
Returns: 1 if RSI crossed out 30, 50 or 70. -1 if RSI crossed under 70, 50, 30. otherwise is 0
MLExtensionsLibrary "MLExtensions"
normalizeDeriv(src, quadraticMeanLength)
Returns the smoothed hyperbolic tangent of the input series.
Parameters:
src : The input series (i.e., the first-order derivative for price).
quadraticMeanLength : The length of the quadratic mean (RMS).
Returns: nDeriv The normalized derivative of the input series.
normalize(src, min, max)
Rescales a source value with an unbounded range to a target range.
Parameters:
src : The input series
min : The minimum value of the unbounded range
max : The maximum value of the unbounded range
Returns: The normalized series
rescale(src, oldMin, oldMax, newMin, newMax)
Rescales a source value with a bounded range to anther bounded range
Parameters:
src : The input series
oldMin : The minimum value of the range to rescale from
oldMax : The maximum value of the range to rescale from
newMin : The minimum value of the range to rescale to
newMax : The maximum value of the range to rescale to
Returns: The rescaled series
color_green(prediction)
Assigns varying shades of the color green based on the KNN classification
Parameters:
prediction : Value (int|float) of the prediction
Returns: color
color_red(prediction)
Assigns varying shades of the color red based on the KNN classification
Parameters:
prediction : Value of the prediction
Returns: color
tanh(src)
Returns the the hyperbolic tangent of the input series. The sigmoid-like hyperbolic tangent function is used to compress the input to a value between -1 and 1.
Parameters:
src : The input series (i.e., the normalized derivative).
Returns: tanh The hyperbolic tangent of the input series.
dualPoleFilter(src, lookback)
Returns the smoothed hyperbolic tangent of the input series.
Parameters:
src : The input series (i.e., the hyperbolic tangent).
lookback : The lookback window for the smoothing.
Returns: filter The smoothed hyperbolic tangent of the input series.
tanhTransform(src, smoothingFrequency, quadraticMeanLength)
Returns the tanh transform of the input series.
Parameters:
src : The input series (i.e., the result of the tanh calculation).
smoothingFrequency
quadraticMeanLength
Returns: signal The smoothed hyperbolic tangent transform of the input series.
n_rsi(src, n1, n2)
Returns the normalized RSI ideal for use in ML algorithms.
Parameters:
src : The input series (i.e., the result of the RSI calculation).
n1 : The length of the RSI.
n2 : The smoothing length of the RSI.
Returns: signal The normalized RSI.
n_cci(src, n1, n2)
Returns the normalized CCI ideal for use in ML algorithms.
Parameters:
src : The input series (i.e., the result of the CCI calculation).
n1 : The length of the CCI.
n2 : The smoothing length of the CCI.
Returns: signal The normalized CCI.
n_wt(src, n1, n2)
Returns the normalized WaveTrend Classic series ideal for use in ML algorithms.
Parameters:
src : The input series (i.e., the result of the WaveTrend Classic calculation).
n1
n2
Returns: signal The normalized WaveTrend Classic series.
n_adx(highSrc, lowSrc, closeSrc, n1)
Returns the normalized ADX ideal for use in ML algorithms.
Parameters:
highSrc : The input series for the high price.
lowSrc : The input series for the low price.
closeSrc : The input series for the close price.
n1 : The length of the ADX.
regime_filter(src, threshold, useRegimeFilter)
Parameters:
src
threshold
useRegimeFilter
filter_adx(src, length, adxThreshold, useAdxFilter)
filter_adx
Parameters:
src : The source series.
length : The length of the ADX.
adxThreshold : The ADX threshold.
useAdxFilter : Whether to use the ADX filter.
Returns: The ADX.
filter_volatility(minLength, maxLength, useVolatilityFilter)
filter_volatility
Parameters:
minLength : The minimum length of the ATR.
maxLength : The maximum length of the ATR.
useVolatilityFilter : Whether to use the volatility filter.
Returns: Boolean indicating whether or not to let the signal pass through the filter.
backtest(high, low, open, startLongTrade, endLongTrade, startShortTrade, endShortTrade, isStopLossHit, maxBarsBackIndex, thisBarIndex)
Performs a basic backtest using the specified parameters and conditions.
Parameters:
high : The input series for the high price.
low : The input series for the low price.
open : The input series for the open price.
startLongTrade : The series of conditions that indicate the start of a long trade.`
endLongTrade : The series of conditions that indicate the end of a long trade.
startShortTrade : The series of conditions that indicate the start of a short trade.
endShortTrade : The series of conditions that indicate the end of a short trade.
isStopLossHit : The stop loss hit indicator.
maxBarsBackIndex : The maximum number of bars to go back in the backtest.
thisBarIndex : The current bar index.
Returns: A tuple containing backtest values
init_table()
init_table()
Returns: tbl The backtest results.
update_table(tbl, tradeStatsHeader, totalTrades, totalWins, totalLosses, winLossRatio, winrate, stopLosses)
update_table(tbl, tradeStats)
Parameters:
tbl : The backtest results table.
tradeStatsHeader : The trade stats header.
totalTrades : The total number of trades.
totalWins : The total number of wins.
totalLosses : The total number of losses.
winLossRatio : The win loss ratio.
winrate : The winrate.
stopLosses : The total number of stop losses.
Returns: Updated backtest results table.
BasicVisibleChartBasic library for the visible range chart; with functions to allow plotting Fibs from body high/low as well as wick high/low
-Thanks to code from @PineCoders Visible Chart library (PineCoders/VisibleChart/4), which is a much more comprehensive library than this, but which does not include some functions that I find useful:
-Added the following exportable functions: highest/lowest body, highest/lowest close, highest/lowest open. These allow one to anchor fibs from bodies rather than wicks
-Added a Fib Box function in the example code
The above chart shows the example code plotting a Fib range drawn from bodies and a highlighted retracement zone (61.8 % - 78.6% )
~~All Exportable Functions~~
barIsVisible()
highestClose()
highestOpen()
highestBody()
lowestClose()
lowestOpen()
lowestBody()
high()
highBarTime()
low()
lowBarTime()
open()
close()
MyLibraryLibrary "MyLibrary"
TODO: add library description here
isHammer(fib, colorMatch)
TODO: add function description here
Parameters:
fib
colorMatch
Returns: TODO: add what function returns
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.
E5TradingLibrary
This library replaces the previous MetaWorldEngineFilterLibrary3.
Library "E5TradingLibrary"
GetCandleStickSize(_src_high, _src_low)
returns size of the candle
Parameters:
_src_high
_src_low
Returns: candlestick size
GetCandleStickBodySize(_src_open, _src_close)
returns size of the candle body
Parameters:
_src_open
_src_close
Returns: candlestick body size
FilterLongerLowerWickCandles(_src_open, _src_close, _src_low)
Alters Candlestick Value to Magnify Candles with Long Wicks
Parameters:
_src_open
_src_close
_src_low
Returns: Midpoint of the candle body less the lower wick. If value returned has a large delta from midpoint of the body, then it is short wick
IsBullish(_src_open, _src_close)
Determine if Candle is Bullish or Bearish
Parameters:
_src_open
_src_close
Returns: True is Bullish
IsDoji(_candleIndex, _precision)
Determine if Candle is a Doji
Parameters:
_candleIndex
_precision
Returns: True if a Doji
MACD(_src, _fastLength, _slowLength, _signalLength)
Computes MACD
Parameters:
_src
_fastLength
_slowLength
_signalLength
Returns: Returns MACD and Signal Line
isFastSlowCrossed(SeriesA, SeriesB)
Computes if SeriesA crosses SeriesB
Parameters:
SeriesA
SeriesB
Returns: if SeriesA crosses SeriesB then true else false
isReversalUpTrend(SeriesA, SeriesB)
Computes if SeriesA crosses over SeriesB to determine reversal uptrend
Parameters:
SeriesA
SeriesB
Returns: if SeriesA crosses over SeriesB then true else false
isReversalDownTrend(SeriesA, SeriesB)
Computes if SeriesA crosses over SeriesB to determine reversal uptrend
Parameters:
SeriesA
SeriesB
Returns: if SeriesA crosses over SeriesB then true else false
SSMA(_src, smalength)
Computes smoothed SMA
Parameters:
_src
smalength
Returns: a single concatenated string for evaluation
GetTimeFrame()
Get Current timeframe in minutes
Returns: an integer value in minutes
getMA(_src, length, maType)
Gets a Moving Average based on type
Parameters:
_src
length
maType
Returns: A moving average with the given parameters
ATRSwitch(_src, _ATRMult, _ATRLength)
Average True Range Trailing Stops by Sylvain Vervoort
Parameters:
_src
_ATRMult
_ATRLength
Returns: upper ATR Line, lower ATR Line and the switch point
HiveLibraryLibrary "HiveLibrary"
: Custom library
RoundDown(number, decimals)
RoundDown() rounds the specified number down to the given number
of decimal places.
Parameters:
number : is the argument for rounding down & decimals is the number of digits after dot
decimals
Returns: return is the rounded down value of the number
Library_SmoothersLibrary "Library_Smoothers"
CorrectedMA(Src, Len)
CorrectedMA The strengths of the corrected Average (CA) is that the current value of the time series must exceed a the current volatility-dependent threshold, so that the filter increases or falls, avoiding false signals when the trend is in a weak phase.
Parameters:
Src
Len
Returns: The Corrected source.
EHMA(src, len)
EMA Exponential Moving Average.
Parameters:
src : Source to act upon
len
Returns: EMA of source
FRAMA(src, len, FC, SC)
FRAMA Fractal Adaptive Moving Average
Parameters:
src : Source to act upon
len : Length of moving average
FC : Fast moving average
SC : Slow moving average
Returns: FRAMA of source
Jurik(src, length, phase, power)
Jurik A low lag filter
Parameters:
src : Source
length : Length for smoothing
phase : Phase range is ±100
power : Mathematical power to use. Doesn't need to be whole numbers
Returns: Jurik of source
SMMA(src, len)
SMMA Smoothed moving average. Think of the SMMA as a hybrid of its better-known siblings — the simple moving average (SMA) and the exponential moving average (EMA).
Parameters:
src : Source
len
Returns: SMMA of source
SuperSmoother(src, len)
SuperSmoother
Parameters:
src : Source to smooth
len
Returns: SuperSmoother of the source
TMA(src, len)
TMA Triangular Moving Average
Parameters:
src : Source
len
Returns: TMA of source
TSF(src, len)
TSF Time Series Forecast. Uses linear regression.
Parameters:
src : Source
len
Returns: TSF of source
VIDYA(src, len)
VIDYA Chande's Variable Index Dynamic Average. See www.fxcorporate.com
Parameters:
src : Source
len
Returns: VIDYA of source
VAWMA(src, len, startingWeight, volumeDefault)
VAWMA = VWMA and WMA combined. Simply put, this attempts to determine the average price per share over time weighted heavier for recent values. Uses a triangular algorithm to taper off values in the past (same as WMA does).
Parameters:
src : Source
len : Length
startingWeight
volumeDefault : The default value to use when a chart has no volume.
Returns: The VAWMA of the source.
WWMA(src, len)
WWMA Welles Wilder Moving Average
Parameters:
src : Source
len
Returns: The WWMA of the source
ZLEMA(src, len)
ZLEMA Zero Lag Expotential Moving Average
Parameters:
src : Source
len
Returns: The ZLEMA of the source
SmootherType(mode, src, len, fastMA, slowMA, offset, phase, power, startingWeight, volumeDefault, Corrected)
Performs the specified moving average
Parameters:
mode : Name of moving average
src : the source to apply the MA type
len
fastMA : FRAMA fast moving average
slowMA : FRAMA slow moving average
offset : Linear regression offset
phase : Jurik phase
power : Jurik power
startingWeight : VAWMA starting weight
volumeDefault : VAWMA default volume
Corrected
Returns: The MA smoothed source
HendrixLIBRARY - utilsLibrary "HendrixLIBRARY"
getVolumeData()
getLTF(customTimeframe, ltf)
Parameters:
customTimeframe
ltf
sumArray(a)
Parameters:
a
arrs2vals(upVolumeArray, downVolumeArray, volArr)
Parameters:
upVolumeArray
downVolumeArray
volArr
getVolumesFromUpDownArrays(upVolumeArray, downVolumeArray)
Parameters:
upVolumeArray
downVolumeArray
getDeltaFromVolumes(upVolume, downVolume)
Parameters:
upVolume
downVolume
getDeltaFromUpDownArrays(upVolumeArray, downVolumeArray)
Parameters:
upVolumeArray
downVolumeArray
getUpColor()
getDownColor()
getBlackColor()
getColors()
printTableTR(txt)
Parameters:
txt
printTableBR(txt)
Parameters:
txt
printTableMR(txt)
Parameters:
txt
print(txt, lbl)
Parameters:
txt
lbl
printSyminfo(sym)
Parameters:
sym
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
ChasinAlts_LibraryLibrary "ChasinAlts_Library"
rci(_BCgtg, _Tgtg, _close, _smaLen, _bar_index)
Parameters:
_BCgtg
_Tgtg
_close
_smaLen
_bar_index
printedBC(_time, _minPerc, _Tgtg, _lkbk)
Parameters:
_time
_minPerc
_Tgtg
_lkbk
form123(_ppLen, _BCgtg, _Tgtg, _high, _low, _close, _bar_index)
Parameters:
_ppLen
_BCgtg
_Tgtg
_high
_low
_close
_bar_index
obosCnt(_BCgtg, _Tgtg, _rci, _obosMin, _obosMax, _thresh)
Parameters:
_BCgtg
_Tgtg
_rci
_obosMin
_obosMax
_thresh
div(_thresh, _HLestLen, _Tgtg, _BCgtg, _rci, _time, _price, _LSL, _SSL, _LTP, _STP, _colorid, _long, _short)
Parameters:
_thresh
_HLestLen
_Tgtg
_BCgtg
_rci
_time
_price
_LSL
_SSL
_LTP
_STP
_colorid
_long
_short
tradeSim(_SL, _TP, _BCgtg, _Tgtg, _ppLen, _high, _low, _close, _bar_index, _time, _bull_rev, _bear_rev, _bull_obosCnt_gtg, _bear_obosCnt_gtg)
Parameters:
_SL
_TP
_BCgtg
_Tgtg
_ppLen
_high
_low
_close
_bar_index
_time
_bull_rev
_bear_rev
_bull_obosCnt_gtg
_bear_obosCnt_gtg
TrailingStopsLibrary "TrailingStops"
This library contains functions to output trailing stop lines.
f_marketStructureStop(_restartMode, _flipMode, _restartLowIn, _restartHighIn)
Parameters:
_restartMode - Defines how the stop lines persist. Allowed values are:
"Always On" - The stop lines are always present and they just reset when they're crossed.
"Flip" - The stop lines flip when they're crossed.
"Manual" - The stop lines turn off when they're crossed, and turn back on again when _restartLowIn or _restartHighIn are passed into the function as true.
_flipMode - Defines whether the stop lines are broken by wicks or closes. Allowed values are "Wick", and "Close".
_restartLowIn - If _restartMode is "Manual", passing this parameter as true restarts the Low stop line.
_restartHighIn - If _restartMode is "Manual", passing this parameter as true restarts the High stop line.
@returns - floats for the Low and High stop line.
MarketStructureLibrary "MarketStructure"
This library contains functions for identifying Lows and Highs in a rule-based way, and deriving useful information from them.
f_simpleLowHigh()
This function finds Local Lows and Highs, but NOT in order. A Local High is any candle that has its Low taken out on close by a subsequent candle (and vice-versa for Local Lows).
The Local High does NOT have to be the candle with the highest High out of recent candles. It does NOT have to be a Williams High. It is not necessarily a swing high or a reversal or anything else.
It doesn't have to be "the" high, so don't be confused.
By the rules, Local Lows and Highs must alternate. In this function they do not, so I'm calling them Simple Lows and Highs.
Simple Highs and Lows, by the above definition, can be useful for entries and stops. Because I intend to use them for stops, I want them all, not just the ones that alternate in strict order.
@param - there are no parameters. The function uses the chart OHLC.
@returns boolean values for whether this bar confirms a Simple Low/High, and ints for the bar_index of that Low/High.
f_localLowHigh()
This function finds Local Lows and Highs, in order. A Local High is any candle that has its Low taken out on close by a subsequent candle (and vice-versa for Local Lows).
The Local High does NOT have to be the candle with the highest High out of recent candles. It does NOT have to be a Williams High. It is not necessarily a swing high or a reversal or anything else.
By the rules, Local Lows and Highs must alternate, and in this function they do.
@param - there are no parameters. The function uses the chart OHLC.
@returns boolean values for whether this bar confirms a Local Low/High, and ints for the bar_index of that Low/High.
f_enhancedSimpleLowHigh()
This function finds Local Lows and Highs, but NOT in order. A Local High is any candle that has its Low taken out on close by a subsequent candle (and vice-versa for Local Lows).
The Local High does NOT have to be the candle with the highest High out of recent candles. It does NOT have to be a Williams High. It is not necessarily a swing high or a reversal or anything else.
By the rules, Local Lows and Highs must alternate. In this function they do not, so I'm calling them Simple Lows and Highs.
Simple Highs and Lows, by the above definition, can be useful for entries and stops. Because I intend to use them for trailing stops, I want them all, not just the ones that alternate in strict order.
The difference between this function and f_simpleLowHigh() is that it also tracks the lowest/highest recent level. This level can be useful for trailing stops.
In effect, these are like more "normal" highs and lows that you would pick by eye, but confirmed faster in many cases than by waiting for the low/high of that particular candle to be taken out on close,
because they are instead confirmed by ANY subsequent candle having its low/high exceeded. Hence, I call these Enhanced Simple Lows/Highs.
The levels are taken from the extreme highs/lows, but the bar indexes are given for the candles that were actually used to confirm the Low/High.
This is by design, because it might be misleading to label the extreme, since we didn't use that candle to confirm the Low/High..
@param - there are no parameters. The function uses the chart OHLC.
@returns - boolean values for whether this bar confirms an Enhanced Simple Low/High
ints for the bar_index of that Low/High
floats for the values of the recent high/low levels
floats for the trailing high/low levels (for debug/post-processing)
bools for market structure bias
f_trueLowHigh()
This function finds True Lows and Highs.
A True High is the candle with the highest recent high, which then has its low taken out on close by a subsequent candle (and vice-versa for True Lows).
The difference between this and an Enhanced High is that confirmation requires not just any Simple High, but confirmation of the very candle that has the highest high.
Because of this, confirmation is often later, and multiple Simple Highs and Lows can develop within ranges formed by a single big candle without any of them being confirmed. This is by design.
A True High looks like the intuitive "real high" when you look at the chart. True Lows and Highs must alternate.
@param - there are no parameters. The function uses the chart OHLC.
@returns - boolean values for whether this bar confirms an Enhanced Simple Low/High
ints for the bar_index of that Low/High
floats for the values of the recent high/low levels
floats for the trailing high/low levels (for debug/post-processing)
bools for market structure bias
TechnicalRating█ OVERVIEW
This library is a Pine Script™ programmer’s tool for incorporating TradingView's well-known technical ratings within their scripts. The ratings produced by this library are the same as those from the speedometers in the technical analysis summary and the "Rating" indicator in the Screener , which use the aggregate biases of 26 technical indicators to calculate their results.
█ CONCEPTS
Ensemble analysis
Ensemble analysis uses multiple weaker models to produce a potentially stronger one. A common form of ensemble analysis in technical analysis is the usage of aggregate indicators together in hopes of gaining further market insight and reinforcing trading decisions.
Technical ratings
Technical ratings provide a simplified way to analyze financial markets by combining signals from an ensemble of indicators into a singular value, allowing traders to assess market sentiment more quickly and conveniently than analyzing each constituent separately. By consolidating the signals from multiple indicators into a single rating, traders can more intuitively and easily interpret the "technical health" of the market.
Calculating the rating value
Using a variety of built-in TA functions and functions from our ta library, this script calculates technical ratings for moving averages, oscillators, and their overall result within the `calcRatingAll()` function.
The function uses the script's `calcRatingMA()` function to calculate the moving average technical rating from an ensemble of 15 moving averages and filters:
• Six Simple Moving Averages and six Exponential Moving Averages with periods of 10, 20, 30, 50, 100, and 200
• A Hull Moving Average with a period of 9
• A Volume-Weighted Moving Average with a period of 20
• An Ichimoku Cloud with a conversion line length of 9, base length of 26, and leading span B length of 52
The function uses the script's `calcRating()` function to calculate the oscillator technical rating from an ensemble of 11 oscillators:
• RSI with a period of 14
• Stochastic with a %K period of 14, a smoothing period of 3, and a %D period of 3
• CCI with a period of 20
• ADX with a DI length of 14 and an ADX smoothing period of 14
• Awesome Oscillator
• Momentum with a period of 10
• MACD with fast, slow, and signal periods of 12, 26, and 9
• Stochastic RSI with an RSI period of 14, a %K period of 14, a smoothing period of 3, and a %D period of 3
• Williams %R with a period of 14
• Bull Bear Power with a period of 50
• Ultimate Oscillator with fast, middle, and slow lengths of 7, 14, and 28
Each indicator is assigned a value of +1, 0, or -1, representing a bullish, neutral, or bearish rating. The moving average rating is the mean of all ratings that use the `calcRatingMA()` function, and the oscillator rating is the mean of all ratings that use the `calcRating()` function. The overall rating is the mean of the moving average and oscillator ratings, which ranges between +1 and -1. This overall rating, along with the separate MA and oscillator ratings, can be used to gain insight into the technical strength of the market. For a more detailed breakdown of the signals and conditions used to calculate the indicators' ratings, consult our Help Center explanation.
Determining rating status
The `ratingStatus()` function produces a string representing the status of a series of ratings. The `strongBound` and `weakBound` parameters, with respective default values of 0.5 and 0.1, define the bounds for "strong" and "weak" ratings.
The rating status is determined as follows:
Rating Value Rating Status
< -strongBound Strong Sell
< -weakBound Sell
-weakBound to weakBound Neutral
> weakBound Buy
> strongBound Strong Buy
By customizing the `strongBound` and `weakBound` values, traders can tailor the `ratingStatus()` function to fit their trading style or strategy, leading to a more personalized approach to evaluating ratings.
Look first. Then leap.
█ FUNCTIONS
This library contains the following functions:
calcRatingAll()
Calculates 3 ratings (ratings total, MA ratings, indicator ratings) using the aggregate biases of 26 different technical indicators.
Returns: A 3-element tuple: ( [(float) ratingTotal, (float) ratingOther, (float) ratingMA ].
countRising(plot)
Calculates the number of times the values in the given series increase in value up to a maximum count of 5.
Parameters:
plot : (series float) The series of values to check for rising values.
Returns: (int) The number of times the values in the series increased in value.
ratingStatus(ratingValue, strongBound, weakBound)
Determines the rating status of a given series based on its values and defined bounds.
Parameters:
ratingValue : (series float) The series of values to determine the rating status for.
strongBound : (series float) The upper bound for a "strong" rating.
weakBound : (series float) The upper bound for a "weak" rating.
Returns: (string) The rating status of the given series ("Strong Buy", "Buy", "Neutral", "Sell", or "Strong Sell").
TurntLibraryLibrary "TurntLibrary"
Collection of functions created for simplification/easy referencing. Includes variations of moving averages, length value oscillators, and a few other simple functions based upon HH/LL values.
ma(source, length, type)
Apply a moving average to a float value
Parameters:
source : Value to be used
length : Number of bars to include in calculation
type : Moving average type to use ("SMA","EMA","RMA","WMA","VWAP","SWMA","LRC")
Returns: Smoothed value of initial float value
curve(src, len, lb1, lb2)
Exaggerates curves of a float value designed for use as an exit signal.
Parameters:
src : Initial value to curve
len : Number of bars to include in calculation
lb1 : (Default = 1) First lookback length
lb2 : (Default = 2) Second lookback length
Returns: Curved Average
fragma(src, len, space, str)
Average of a moving average and the previous value of the moving average
Parameters:
src : Initial float value to use
len : Number of bars to include in calculation
space : Lookback integer for second half of average
str : Moving average type to use ("SMA","EMA","RMA","WMA","VWAP","SWMA","LRC")
Returns: Fragmented Average
maxmin(x, y)
Difference of 2 float values, subtracting the lowest from the highest
Parameters:
x : Value 1
y : Value 2
Returns: The +Difference between 2 float values
oscLen(val, type)
Variable Length using a oscillator value and a corresponding slope shape ("Incline",Decline","Peak","Trough")
Parameters:
val : Oscillator Value to use
type : Slope of length curve ("Incline",Decline","Peak","Trough")
Returns: Variable Length Integer
hlAverage(val, smooth, max, min, type, include)
Average of HH,LL with variable lengths based on the slope shape ("Incline","Decline","Trough") value relative to highest and lowest
Parameters:
val : Source Value to use
smooth
max
min
type
include : Add "val" to the averaging process, instead of more weight to highest or lowest value
Returns: Variable Length Average of Highest Lowest "val"
pct(val)
Convert a positive float / price to a percentage of it's highest value on record
Parameters:
val : Value To convert to a percentage of it's highest value ever
Returns: Percentage
hlrange(x, len)
Difference between Highest High and Lowest Low of float value
Parameters:
x : Value to use in calculation
len : Number of bars to include in calculation
Returns: Difference
midpoint(x, len, smooth)
The average value of the float's Highest High and Lowest Low in a number of bars
Parameters:
x : Value to use in calculation
len
smooth : (Default=na) Optional smoothing type to use ("SMA","EMA","RMA","WMA","VWAP","SWMA","LRC")
Returns: Midpoint
Obj_XABCD_HarmonicLibrary "Obj_XABCD_Harmonic"
Harmonic XABCD Pattern object and associated methods. Easily validate, draw, and get information about harmonic patterns. See example code at the end of the script for details.
init_params(pct_error, pct_asym, types, w_e, w_p, w_d)
Create a harmonic parameters object (used by xabcd_harmonic object for pattern validation and scoring).
Parameters:
pct_error : Allowed % error of leg retracement ratio versus the defined harmonic ratio
pct_asym : Allowed leg length/period asymmetry % (a leg is considered invalid if it is this % longer or shorter than the average length of the other legs)
types : Array of pattern types to validate (1=Gartley, 2=Bat, 3=Butterfly, 4=Crab, 5=Shark, 6=Cypher)
w_e : Weight of ratio % error (used in score calculation, dft = 1)
w_p : Weight of PRZ confluence (used in score calculation, dft = 1)
w_d : Weight of Point D / PRZ confluence (used in score calculation, dft = 1)
Returns: harmonic_params object instance. It is recommended to store and reuse this object for multiple xabcd_harmonic objects rather than creating new params objects unnecessarily.
init(xX, xY, aX, aY, bX, bY, cX, cY, dX, dY, params, tp, p)
Initialize an xabcd_harmonic object instance.
If the pattern is valid, an xabcd_harmonic object instance is returned. If you want to specify your
own validation and scoring parameters, you can do so by passing a harmonic_params object (params).
Or, if you prefer to do your own validation, you can explicitly pass the harmonic pattern type (tp)
and validation will be skipped. You can also pass in an existing xabcd_harmonic instance if you wish
to re-initialize it (e.g. for re-validation and/or re-scoring).
Parameters:
xX : Point X bar index
xY : Point X price/level
aX : Point A bar index
aY : Point A price/level
bX : Point B bar index
bY : Point B price/level
cX : Point C bar index
cY : Point C price/level
dX : Point D bar index
dY : Point D price/level
params : harmonic_params used to validate and score the pattern. Validation will be skipped if a type (tp) is explicitly passed in.
tp : Pattern type
p : xabcd_harmonic object instance to initialize (optional, for re-validation/re-scoring)
Returns: xabcd_harmonic object instance if a valid harmonic, else na
get_name(p)
Get the pattern name
Parameters:
p : Instance of xabcd_harmonic object
Returns: Pattern name (string)
get_symbol(p)
Get the pattern symbol
Parameters:
p : Instance of xabcd_harmonic object
Returns: Pattern symbol (1 byte string)
get_pid(p)
Get the Pattern ID. Patterns of the same type with the same coordinates will have the same Pattern ID.
Parameters:
p : Instance of xabcd_harmonic object
Returns: Pattern ID (string)
set_target(p, target, target_lvl, calc_target)
Set value for a target. Use the calc_target parameter to automatically calculate the target for a specific harmonic ratio.
Parameters:
p : Instance of xabcd_harmonic object
target : Target (1 or 2)
target_lvl : Target price/level (required if calc_target is not specified)
calc_target : Target to auto calculate (required if target is not specified)
Options:
Returns: Target price/level (float)
erase_pattern(p)
Erase the pattern
Parameters:
p : Instance of xabcd_harmonic object
Returns: p
draw_pattern(p)
Draw the pattern
Parameters:
p : Instance of xabcd_harmonic object
Returns: Pattern lines
erase_label(p)
Erase the pattern label
Parameters:
p : Instance of xabcd_harmonic object
Returns: p
draw_label(p, txt, tooltip, clr, txt_clr)
Draw the pattern label. Default text is the pattern name.
Parameters:
p : Instance of xabcd_harmonic object
txt : Label text
tooltip : Tooltip text
clr : Label color
txt_clr : Text color
Returns: Label
harmonic_params
Validation and scoring parameters for a Harmonic Pattern object (xabcd_harmonic)
Fields:
pct_error : Allowed % error of leg retracement ratio versus the defined harmonic ratio
pct_asym
types
w_e
w_p
w_d
xabcd_harmonic
Harmonic Pattern object
Fields:
bull : Bullish pattern flag
tp
xX
xY
aX
aY
bX
bY
cX
cY
dX
dY
r_xb
re_xb
r_ac
re_ac
r_bd
re_bd
r_xd
re_xd
score
score_eAvg
score_prz
score_eD
prz_bN
prz_bF
prz_xN
prz_xF
t1Hit : Target 1 flag
t1
t2Hit
t2
sHit : Stop flag
stop : Stop level
entry : Entry level
eHit
eX
eY
pLines
pLabel
pid
params
ZigZag█ OVERVIEW
This library is a Pine Script™ programmer’s tool containing custom user-defined types and functions to calculate Zig Zag indicators within their scripts. It is not a stand-alone indicator.
Pine Script™ libraries are publications that contain reusable code for importing into Pine Script™ indicators, strategies, and other libraries. For more information on libraries and incorporating them into your scripts, see the Libraries section of the Pine Script™ User Manual .
█ CONCEPTS
Zig Zag
Zig Zag is a popular indicator that filters out minor price fluctuations to denoise data and emphasize trends. Traders commonly use Zig Zag for trend confirmation, identifying potential support and resistance, and pattern detection. It is formed by identifying significant local high and low points in alternating order and connecting them with straight lines, omitting all other data points from their output. There are several ways to calculate the Zig Zag's data points and the conditions by which its direction changes. This script uses pivots as the data points, which are the highest or lowest values over a defined number of bars before and after them. The direction only reverses when a newly formed pivot deviates from the last Zig Zag point in the opposite direction by an amount greater than or equal to a specified percentage.
To learn more about Zig Zag and how to calculate it, see this entry from the Help Center.
█ FOR Pine Script™ CODERS
Notes
This script's architecture utilizes user-defined types (UDTs) to create custom objects which are the equivalent of variables containing multiple parts, each able to hold independent values of different types . UDTs are the newest addition to Pine Script™ and the most advanced feature the language has seen to date. The feature's introduction creates a new runway for experienced coders to push the boundaries of Pine. We recommend that newcomers to the language explore the basics first before diving into UDTs and objects.
Demonstration Code
Our example code shows a simple use case by displaying a Zig Zag with user-defined settings. A new ZigZag object is instantiated on the first bar using a Settings object to control its attributes. The fields for the Settings object are declared using variables assigned to input.* functions, allowing control of the field values from the script's settings. The `update()` function is invoked on each bar to update the ZigZag object's fields and create new lines and labels when required.
Look first. Then leap.
█ TYPES
This library contains the following types:
Settings
Provides calculation and display attributes to ZigZag objects.
Fields:
devThreshold : The minimum percentage deviation from a point before the ZigZag will change direction.
depth : The number of bars required for pivot detection.
lineColor : Line color.
extendLast : Condition allowing a line to connect the most recent pivot with the current close.
displayReversalPrice : Condition to display the pivot price in the pivot label.
displayCumulativeVolume : Condition to display the cumulative volume for the pivot segment in the pivot label.
displayReversalPriceChange : Condition to display the change in price or percent from the previous pivot in the pivot label.
differencePriceMode : Reversal change display mode. Options are "Absolute" or "Percent".
draw : Condition to display lines and labels.
Point
A coordinate containing time and price information.
Fields:
tm : A value in UNIX time.
price : A value on the Y axis (price).
Pivot
A level of significance used to determine directional movement or potential support and resistance.
Fields:
ln : A line object connecting the `start` and `end` Point objects.
lb : A label object to display pivot values.
isHigh : A condition to determine if the pivot is a pivot high.
vol : Volume for the pivot segment.
start : The coordinate of the previous Point.
end : The coordinate of the current Point.
ZigZag
An object to maintain Zig Zag settings, pivots, and volume.
Fields:
settings : Settings object to provide calculation and display attributes.
pivots : An array of Pivot objects.
sumVol : The volume sum for the pivot segment.
extend : Pivot object used to project a line from the last pivot to the last bar.
█ FUNCTIONS
This library contains the following functions:
lastPivot(this)
Returns the last Pivot of `this` ZigZag if there is at least one Pivot to return, and `na` otherwise.
Parameters:
this : (series ZigZag) A ZigZag object.
Returns: (Pivot) The last Pivot in the ZigZag.
update(this)
Updates `this` ZigZag object with new pivots, volume, lines, labels.
Parameters:
this : (series ZigZag) a ZigZag object.
Returns: (bool) true if a new Zig Zag line is found or the last Zig Zag line has changed.
newInstance(settings)
Instantiates a new ZigZag object with `settings`. If no settings are provided, a default ZigZag object is created.
Parameters:
settings : (series Settings) A Settings object.
Returns: (ZigZag) A new ZigZag instance.