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()
Market Geometry
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
PatternLibrary "Pattern"
Pattern object definitions and functions. Easily draw and keep track of patterns, legs, and points.
Supported pattern types (as of Version 1):
Type Leg validation # legs
"xabcd" Direction 3 or 4 (point D not required)
"zigzag" Direction >= 2
"free" None >= 2
erase_label(this)
Delete the point label
Parameters:
this : Point
Returns: Void
draw_label(this, position, clr, transp, txt_clr, txt, tooltip, size)
Draw the point label
Parameters:
this : Point
position
clr
transp
txt_clr
txt
tooltip
size
Returns: line
leg_init(a, b, prev, next, line)
Initialize a pattern leg
Parameters:
a : Point A (required)
b : Point B (required)
prev : Previous leg
next : Next leg
line : Line
Returns: New instance of leg object
erase(this)
Delete the pattern leg
Parameters:
this : Leg
Returns: Void
erase(this)
Parameters:
this
draw(this, clr, style, transp, width)
Draw the pattern leg
Parameters:
this : Leg
clr : Color
style : Style ("solid", "dotted", "dashed", "arrowleft", "arrowright")
transp : Transparency
width : Width
Returns: line
draw(this, clr, style, transp, width)
Parameters:
this
clr
style
transp
width
leg_getLineTerms(this)
Get the slope and y-intercept of a leg
Parameters:
this : Leg
Returns:
leg_getPrice(this, index)
Get the price (Y) at a given bar index (X) within the leg
Parameters:
this : Leg
index : Bar index
Returns: Price (float)
pattern_init(legs, tp, name, subType, pid)
Initialize a pattern object from a given set of legs
Parameters:
legs : Array of pattern legs (required)
tp : Pattern type ("zigzag", "xabcd", or "free". dft = "free")
name : Pattern name
subType : Pattern subtype
pid : Pattern Identifier string
Returns: New instance of pattern object, if one was successfully created
pattern_init(points, tp, name, subType, pid)
Initialize a pattern object from a given set of points
Parameters:
points
tp : Pattern type ("zigzag", "xabcd", or "free". dft = "free")
name : Pattern name
subType : Pattern subtype
pid : Pattern Identifier string
Returns: New instance of pattern object, if one was successfully created
point
A point on the chart (x,y)
Fields:
x : Bar index (x coordinate)
y
label
leg
A pattern leg (point A to point B)
Fields:
a : Point A
b
deltaX
deltaY
prev
next
retrace
line
pattern
A pattern (set of at least 2 connected legs)
Fields:
legs
type
subType
name
pid
BpaLibrary "Bpa"
TODO: library of Brooks Price Action concepts
isBreakoutBar(atr, high, low, close, open, tail, size)
TODO: check if the bar is a breakout based on the specified conditions
Parameters:
atr : TODO: atr value
high : TODO: high price
low : TODO: low price
close : TODO: close price
open : TODO: open price
tail : TODO: decimal value for a percent that represent the size of the tail of the bar that cant be preceeded to be considered strong close
size : TODO: decimal value for a percent that represents by how much the breakout bar should be bigger than others to be considered one
Returns: TODO: boolean value, true if breakout bar, false otherwise
intersectLibrary "intersect"
Find Line Intersection X/Y coordinates.
Simple to use, will find intersection if it exists on the segments
if the line segments do not cross on segment, an 'na' value will be returned
if you plot new items with the output coords, they still plot.
avoid this by setting a na(x) condition before plotting new items
get(l1, l2, ( optional _round) )
line intersection coordinates
Parameters:
l1 : (line) first line
l2 : (line) second line
_round : True to make an INT for plotting
if not used, will not round ( overload loophole)
Returns: with x as int if bool is used
TrigLibrary "Trig"
Trigonometric functions
rt_get_angleAlpha(a, b, c, deg)
Get angle α of a right triangle, given the lengths of its sides
Parameters:
a : length of leg a (float)
b : length of leg b (float)
c : length of hypotenuse (float)
deg : flag to return angle in degrees (bool - default = false)
Returns: angle α in radians (or degrees if deg == true)
rt_get_angleAlphaFromLine(x1, y1, x2, y2, l, deg)
Get angle α of a right triangle formed by the given line
Parameters:
x1 : x coordinate 1 (int - optional, required if argument l is not specified)
y1 : y coordinate 1 (float - optional, required if argument l is not specified)
x2 : x coordinate 2 (int - optional, required if argument l is not specified)
y2 : y coordinate 2 (float - optional, required if argument l is not specified)
l : line object (line - optional, required if x1, y1, x2, and y2 agruments are not specified)
deg : flag to return angle in degrees (bool - default = false)
Returns: angle α in radians (or degrees if deg == true)
rt_get_angleBeta(a, b, c, deg)
Get angle β of a right triangle, given the lengths of its sides
Parameters:
a : length of leg a (float)
b : length of leg b (float)
c : length of hypotenuse (float)
deg : flag to return angle in degrees (bool - default = false)
Returns: angle β in radians (or degrees if deg == true)
rt_get_angleBetaFromLine(x1, y1, x2, y2, l, deg)
Get angle β of a right triangle formed by the given line
Parameters:
x1 : x coordinate 1 (int - optional, required if argument l is not specified)
y1 : y coordinate 1 (float - optional, required if argument l is not specified)
x2 : x coordinate 2 (int - optional, required if argument l is not specified)
y2 : y coordinate 2 (float - optional, required if argument l is not specified)
l : line object (line - optional, required if x1, y1, x2, and y2 agruments are not specified)
deg : flag to return angle in degrees (bool - default = false)
Returns: angle β in radians (or degrees if deg == true)
HelperFunctionsLibrary "HelperFunctions"
A collection of my most used functions
apply_smoothing()
Apply one of Pine Script's built-in smoothing functions to a series
rzigzagLibrary "rzigzag"
Recursive Zigzag Using Matrix allows to create zigzags recursively on multiple levels. After bit of consideration, decided to make this public.
zigzag(length, ohlc, numberOfPivots, offset)
calculates plain zigzag based on input
Parameters:
length : Zigzag Length
ohlc : Array containing ohlc values. Can also contain custom series
numberOfPivots : Number of max pivots to be returned
offset : Offset from current bar. Can be used for calculations based on confirmed bars
Returns:
nextlevel(zigzagmatrix, numberOfPivots)
calculates next level zigzag based on present zigzag coordinates
Parameters:
zigzagmatrix : Matrix containing zigzag pivots, bars, bar time, direction and level
numberOfPivots : Number of max pivots to be returned
Returns: matrix zigzagmatrix
draw(zigzagmatrix, newPivot, doublePivot, lineColor, lineWidth, lineStyle, showLabel, xloc)
draws zigzag based on the zigzagmatrix input
Parameters:
zigzagmatrix : Matrix containing zigzag pivots, bars, bar time, direction and level
newPivot : Flag indicating there is update in the pivots
doublePivot : Flag containing there is double pivot update on same bar
lineColor : Zigzag line color
lineWidth : Zigzag line width
lineStyle : Zigzag line style
showLabel : Flag to indicate display pivot labels
xloc : xloc preference for drawing lines/labels
Returns:
draw(length, ohlc, numberOfPivots, offset, lineColor, lineWidth, lineStyle, showLabel, xloc)
calculates and draws zigzag based on zigzag length and source input
Parameters:
length : Zigzag Length
ohlc : Array containing ohlc values. Can also contain custom series
numberOfPivots : Number of max pivots to be returned
offset : Offset from current bar. Can be used for calculations based on confirmed bars
lineColor : Zigzag line color
lineWidth : Zigzag line width
lineStyle : Zigzag line style
showLabel : Flag to indicate display pivot labels
xloc : xloc preference for drawing lines/labels
Returns:
drawfresh(zigzagmatrix, zigzaglines, zigzaglabels, lineColor, lineWidth, lineStyle, showLabel, xloc)
draws fresh zigzag for all pivots in the input matrix.
Parameters:
zigzagmatrix : Matrix containing zigzag pivots, bars, bar time, direction and level
zigzaglines : array to which all newly created lines will be added
zigzaglabels : array to which all newly created lables will be added
lineColor : Zigzag line color
lineWidth : Zigzag line width
lineStyle : Zigzag line style
showLabel : Flag to indicate display pivot labels
xloc : xloc preference for drawing lines/labels
Returns:
CommonMarkupLibrary "CommonMarkup"
Provides functions for chart markup, such as indicating recession bands.
markRecessionBands(showBands, lineY, labelY)
Mark vertical bands and show recession band labels if argument showBands is true. Example "markRecessionBands(bar_index ,3.0"
Parameters:
showBands : - show vertical recession bands when true. Functionally equiv to no op when false
lineY : - y-axis value for line positioning
labelY : - y-axis value for label positioning
@return true - always answers the value of showBands
divergenceLibrary "divergence"
divergence: divergence algorithm with top and bottom kline tolerance
regular_bull(series, series, simple, simple, simple, simple, simple) regular_bull: regular bull divergence, lower low src but higher low osc
Parameters:
series : float src: the source series
series : float osc: the oscillator index
simple : int lbL: look back left
simple : int lbR: look back right
simple : int rangeL: min look back range
simple : int rangeU: max look back range
simple : int tolerance: the number of tolerant klines
Returns: array:
hidden_bull(series, series, simple, simple, simple, simple, simple) hidden_bull: hidden bull divergence, higher low src but lower low osc
Parameters:
series : float src: the source series
series : float osc: the oscillator index
simple : int lbL: look back left
simple : int lbR: look back right
simple : int rangeL: min look back range
simple : int rangeU: max look back range
simple : int tolerance: the number of tolerant klines
Returns: array:
regular_bear(series, series, simple, simple, simple, simple, simple) regular_bear: regular bear divergence, higher high src but lower high osc
Parameters:
series : float src: the source series
series : float osc: the oscillator index
simple : int lbL: look back left
simple : int lbR: look back right
simple : int rangeL: min look back range
simple : int rangeU: max look back range
simple : int tolerance: the number of tolerant klines
Returns: array:
hidden_bear(series, series, simple, simple, simple, simple, simple) hidden_bear: hidden bear divergence, lower high src but higher high osc
Parameters:
series : float src: the source series
series : float osc: the oscillator index
simple : int lbL: look back left
simple : int lbR: look back right
simple : int rangeL: min look back range
simple : int rangeU: max look back range
simple : int tolerance: the number of tolerant klines
Returns: array:
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
[e2] Drawing Library :: Horizontal Ray█ OVERVIEW
Library "e2hray"
A drawing library that contains the hray() function, which draws a horizontal ray/s with an initial point determined by a specified condition. It plots a ray until it reached the price. The function let you control the visibility of historical levels and setup the alerts.
█ HORIZONTAL RAY FUNCTION
hray(condition, level, color, extend, hist_lines, alert_message, alert_delay, style, hist_style, width, hist_width)
Parameters:
condition : Boolean condition that defines the initial point of a ray
level : Ray price level.
color : Ray color.
extend : (optional) Default value true, current ray levels extend to the right, if false - up to the current bar.
hist_lines : (optional) Default value true, shows historical ray levels that were revisited, default is dashed lines. To avoid alert problems set to 'false' before creating alerts.
alert_message : (optional) Default value string(na), if declared, enables alerts that fire when price revisits a line, using the text specified
alert_delay : (optional) Default value int(0), number of bars to validate the level. Alerts won't trigger if the ray is broken during the 'delay'.
style : (optional) Default value 'line.style_solid'. Ray line style.
hist_style : (optional) Default value 'line.style_dashed'. Historical ray line style.
width : (optional) Default value int(1), ray width in pixels.
hist_width : (optional) Default value int(1), historical ray width in pixels.
Returns: void
█ EXAMPLES
• Example 1. Single horizontal ray from the dynamic input.
//@version=5
indicator("hray() example :: Dynamic input ray", overlay = true)
import e2e4mfck/e2hray/1 as e2draw
inputTime = input.time(timestamp("20 Jul 2021 00:00 +0300"), "Date", confirm = true)
inputPrice = input.price(54, 'Price Level', confirm = true)
e2draw.hray(time == inputTime, inputPrice, color.blue, alert_message = 'Ray level re-test!')
var label mark = label.new(inputTime, inputPrice, 'Selected point to start the ray', xloc.bar_time)
• Example 2. Multiple horizontal rays on the moving averages cross.
//@version=5
indicator("hray() example :: MA Cross", overlay = true)
import e2e4mfck/e2hray/1 as e2draw
float sma1 = ta.sma(close, 20)
float sma2 = ta.sma(close, 50)
bullishCross = ta.crossover( sma1, sma2)
bearishCross = ta.crossunder(sma1, sma2)
plot(sma1, 'sma1', color.purple)
plot(sma2, 'sma2', color.blue)
// 1a. We can use 2 function calls to distinguish long and short sides.
e2draw.hray(bullishCross, sma1, color.green, alert_message = 'Bullish Cross Level Broken!', alert_delay = 10)
e2draw.hray(bearishCross, sma2, color.red, alert_message = 'Bearish Cross Level Broken!', alert_delay = 10)
// 1b. Or a single call for both.
// e2draw.hray(bullishCross or bearishCross, sma1, bullishCross ? color.green : color.red)
• Example 3. Horizontal ray at the all time highs with an alert.
//@version=5
indicator("hray() example :: ATH", overlay = true)
import e2e4mfck/e2hray/1 as e2draw
var float ath = 0, ath := math.max(high, ath)
bool newAth = ta.change(ath)
e2draw.hray(nz(newAth ), high , color.orange, alert_message = 'All Time Highs Tested!', alert_delay = 10)
FunctionCosineSimilarityLibrary "FunctionCosineSimilarity"
Cosine Similarity method.
function(sample_a, sample_b) Measure the similarity of 2 vectors.
Parameters:
sample_a : float array, values.
sample_b : float array, values.
Returns: float.
diss(cosim) Dissimilarity helper function.
Parameters:
cosim : float, cosine similarity value (0 > 1)
Returns: float
FunctionPatternDecompositionLibrary "FunctionPatternDecomposition"
Methods for decomposing price into common grid/matrix patterns.
series_to_array(source, length) Helper for converting series to array.
Parameters:
source : float, data series.
length : int, size.
Returns: float array.
smooth_data_2d(data, rate) Smooth data sample into 2d points.
Parameters:
data : float array, source data.
rate : float, default=0.25, the rate of smoothness to apply.
Returns: tuple with 2 float arrays.
thin_points(data_x, data_y, rate) Thin the number of points.
Parameters:
data_x : float array, points x value.
data_y : float array, points y value.
rate : float, default=2.0, minimum threshold rate of sample stdev to accept points.
Returns: tuple with 2 float arrays.
extract_point_direction(data_x, data_y) Extract the direction each point faces.
Parameters:
data_x : float array, points x value.
data_y : float array, points y value.
Returns: float array.
find_corners(data_x, data_y, rate) ...
Parameters:
data_x : float array, points x value.
data_y : float array, points y value.
rate : float, minimum threshold rate of data y stdev.
Returns: tuple with 2 float arrays.
grid_coordinates(data_x, data_y, m_size) transforms points data to a constrained sized matrix format.
Parameters:
data_x : float array, points x value.
data_y : float array, points y value.
m_size : int, default=10, size of the matrix.
Returns: flat 2d pseudo matrix.
FunctionGenerateRandomPointsInShapeLibrary "FunctionGenerateRandomPointsInShape"
Generate random vector points in geometric shape (parallelogram, triangle)
random_parallelogram(vector_a, vector_b) Generate random vector point in a parallelogram shape.
Parameters:
vector_a : float array, vector of (x, y) shape.
vector_b : float array, vector of (x, y) shape.
Returns: float array, vector of (x, y) shape.
random_triangle(vector_a, vector_b) Generate random vector point in a triangle shape.
Parameters:
vector_a : float array, vector of (x, y) shape.
vector_b : float array, vector of (x, y) shape.
Returns: float array, vector of (x, y) shape.
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
FunctionZigZagMultipleMethodsLibrary "FunctionZigZagMultipleMethods"
ZigZag Multiple Methods.
method(idx) Helper methods enumeration.
Parameters:
idx : int, index of method, range 0 to 4.
Returns: string
function(method, value_x, value_y) Multiple method ZigZag.
Parameters:
method : string, default='(MANUAL) Percent price move over X * Y', method for zigzag.
value_x : float, x value in method.
value_y : float, y value in method.
Returns: tuple with:
zigzag float
direction
reverse_line float
realtimeofpivot int
harmonicpatternsLibrary "harmonicpatterns"
harmonicpatterns: methods required for calculation of harmonic patterns. These are customised to be used in my scripts. But, also simple enough for others to make use of :)
isGartleyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isGartleyPattern: Checks for harmonic pattern Gartley
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Gartley. False otherwise.
isBatPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isBatPattern: Checks for harmonic pattern Bat
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Bat. False otherwise.
isButterflyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isButterflyPattern: Checks for harmonic pattern Butterfly
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Butterfly. False otherwise.
isCrabPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isCrabPattern: Checks for harmonic pattern Crab
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Crab. False otherwise.
isDeepCrabPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isDeepCrabPattern: Checks for harmonic pattern DeepCrab
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is DeepCrab. False otherwise.
isCypherPattern(xabRatio, axcRatio, xadRatio, err_min, err_max) isCypherPattern: Checks for harmonic pattern Cypher
Parameters:
xabRatio : AB/XA
axcRatio : XC/AX
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Cypher. False otherwise.
isSharkPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isSharkPattern: Checks for harmonic pattern Shark
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Shark. False otherwise.
isNenStarPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isNenStarPattern: Checks for harmonic pattern Nenstar
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Nenstar. False otherwise.
isAntiNenStarPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiNenStarPattern: Checks for harmonic pattern Anti NenStar
Parameters:
xabRatio : - AB/XA
abcRatio : - BC/AB
bcdRatio : - CD/BC
xadRatio : - AD/XA
err_min : - Minumum error threshold
err_max : - Maximum error threshold
Returns: True if the pattern is Anti NenStar. False otherwise.
isAntiSharkPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiSharkPattern: Checks for harmonic pattern Anti Shark
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Shark. False otherwise.
isAntiCypherPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiCypherPattern: Checks for harmonic pattern Anti Cypher
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Cypher. False otherwise.
isAntiCrabPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiCrabPattern: Checks for harmonic pattern Anti Crab
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Crab. False otherwise.
isAntiBatPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiBatPattern: Checks for harmonic pattern Anti Bat
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Bat. False otherwise.
isAntiGartleyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiGartleyPattern: Checks for harmonic pattern Anti Gartley
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Gartley. False otherwise.
isNavarro200Pattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isNavarro200Pattern: Checks for harmonic pattern Navarro200
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Navarro200. False otherwise.
isHarmonicPattern(x, a, c, c, d, flags, errorPercent) isHarmonicPattern: 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
LinearRegressionLibraryLibrary "LinearRegressionLibrary" contains functions for fitting a regression line to the time series by means of different models, as well as functions for estimating the accuracy of the fit.
Linear regression algorithms:
RepeatedMedian(y, n, lastBar) applies repeated median regression (robust linear regression algorithm) to the input time series within the selected interval.
Parameters:
y :: float series, source time series (e.g. close)
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
Output:
mSlope :: float, slope of the regression line
mInter :: float, intercept of the regression line
TheilSen(y, n, lastBar) applies the Theil-Sen estimator (robust linear regression algorithm) to the input time series within the selected interval.
Parameters:
y :: float series, source time series
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
Output:
tsSlope :: float, slope of the regression line
tsInter :: float, intercept of the regression line
OrdinaryLeastSquares(y, n, lastBar) applies the ordinary least squares regression (non-robust) to the input time series within the selected interval.
Parameters:
y :: float series, source time series
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
Output:
olsSlope :: float, slope of the regression line
olsInter :: float, intercept of the regression line
Model performance metrics:
metricRMSE(y, n, lastBar, slope, intercept) returns the Root-Mean-Square Error (RMSE) of the regression. The better the model, the lower the RMSE.
Parameters:
y :: float series, source time series (e.g. close)
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
slope :: float, slope of the evaluated linear regression line
intercept :: float, intercept of the evaluated linear regression line
Output:
rmse :: float, RMSE value
metricMAE(y, n, lastBar, slope, intercept) returns the Mean Absolute Error (MAE) of the regression. MAE is is similar to RMSE but is less sensitive to outliers. The better the model, the lower the MAE.
Parameters:
y :: float series, source time series
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
slope :: float, slope of the evaluated linear regression line
intercept :: float, intercept of the evaluated linear regression line
Output:
mae :: float, MAE value
metricR2(y, n, lastBar, slope, intercept) returns the coefficient of determination (R squared) of the regression. The better the linear regression fits the data (compared to the sample mean), the closer the value of the R squared is to 1.
Parameters:
y :: float series, source time series
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
slope :: float, slope of the evaluated linear regression line
intercept :: float, intercept of the evaluated linear regression line
Output:
Rsq :: float, R-sqared score
Usage example:
//@version=5
indicator('ExampleLinReg', overlay=true)
// import the library
import tbiktag/LinearRegressionLibrary/1 as linreg
// define the studied interval: last 100 bars
int Npoints = 100
int lastBar = bar_index
int firstBar = bar_index - Npoints
// apply repeated median regression to the closing price time series within the specified interval
{square bracket}slope, intercept{square bracket} = linreg.RepeatedMedian(close, Npoints, lastBar)
// calculate the root-mean-square error of the obtained linear fit
rmse = linreg.metricRMSE(close, Npoints, lastBar, slope, intercept)
// plot the line and print the RMSE value
float y1 = intercept
float y2 = intercept + slope * (Npoints - 1)
if barstate.islast
{indent} line.new(firstBar,y1, lastBar,y2)
{indent} label.new(lastBar,y2,text='RMSE = '+str.format("{0,number,#.#}", rmse))
FunctionGeometricLineDrawingsLibrary "FunctionGeometricLineDrawings"
array_delete_all_lines(lines) deletes all lines in array.
Parameters:
lines : line array, array with line objects to delete.
Returns: void.
triangle(sample_x, sample_y, xloc, extend, color, style, width) Draw a Triangle with 3 vector2D(x, y) coordinates.
Parameters:
sample_x : int array, triangle sample data X coordinate values.
sample_y : float array, triangle sample data Y coordinate values.
xloc : string, defaultoptions=xloc.bar_index, xloc.bar_time.
extend : string, default=extend.none, options=(extend.none, extend.right, extend.left, extend.both).
color : color, default=
style : options line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both
width : width in pixels.
Returns: line array
trapezoid(sample_x, sample_y, xloc, extend, color, style, width) Draw a Trapezoid with 4 vector2D(x, y) coordinates:
Parameters:
sample_x : int array, trapezoid sample data X coordinate values.
sample_y : float array, trapezoid sample data Y coordinate values.
xloc : string, defaultoptions=xloc.bar_index, xloc.bar_time.
extend : string, default=extend.none, options=(extend.none, extend.right, extend.left, extend.both).
color : color, default=
style : options line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both
width : width in pixels.
Returns: line array
CreateAndShowZigzagLibrary "CreateAndShowZigzag"
Functions in this library creates/updates zigzag array and shows the zigzag
getZigzag(zigzag, prd, max_array_size) calculates zigzag using period
Parameters:
zigzag : is the float array for the zigzag (should be defined like "var zigzag = array.new_float(0)"). each zigzag points contains 2 element: 1. price level of the zz point 2. bar_index of the zz point
prd : is the length to calculate zigzag waves by highest(prd)/lowest(prd)
max_array_size : is the maximum number of elements in zigzag, keep in mind each zigzag point contains 2 elements, so for example if it's 10 then zigzag has 10/2 => 5 zigzag points
Returns: dir that is the current direction of the zigzag
showZigzag(zigzag, oldzigzag, dir, upcol, dncol) this function shows zigzag
Parameters:
zigzag : is the float array for the zigzag (should be defined like "var zigzag = array.new_float(0)"). each zigzag points contains 2 element: 1. price level of the zz point 2. bar_index of the zz point
oldzigzag : is the float array for the zigzag, you get copy the zigzag array to oldzigzag by "oldzigzag = array.copy(zigzay)" before calling get_zigzag() function
dir : is the direction of the zigzag wave
upcol : is the color of the line if zigzag direction is up
dncol : is the color of the line if zigzag direction is down
Returns: null
LineGetPriceOnLogScaleLibrary "LineGetPriceOnLogScale"
This library provides a way to calculate the y-coordinate of a line on a specified bar when the chart scale is Log.
The built-in `line.get_price()` function only works with linear scale and gives incorrect results when the chart is in Log scale.
The library only works with `bar_index` values and `xloc.bar_index`-based lines, `time`-based lines will cause errors to appear.
coordGetPriceLog(x1, y1, x2, y2, xi) Calculates the y-coordinate on the specified bar on the logarithmic scale.
Only coordinates based on bar index are applicable, bar time will throw an error.
Parameters:
x1 : First X coordinate of a line, index of the bar where the line starts.
y1 : First Y coordinate of a line, price on the price scale.
x2 : Second X coordinate of a line, index of the bar where the line ends.
y2 : Second Y coordinate of a line, price on the price scale.
xi : Index of the bar for which the price should be calculated.
Returns: Price of the line on the bar specified in `xi`, on the logarithmic scale.
lineGetPriceLog(_line, xi) Calculates the y-coordinate on the specified bar for the logarithmic scale. Takes a line.
Only lines drawn based on `xloc.bar_index` are applicable, `xloc.bar_time` will throw and error.
Parameters:
_line : The line for which the price is calculated.
xi : Index of the bar for which the bar should calculate the price.
Returns: Price of the line on the bar specified in `xi`, on the logarithmic scale.