drawcandlesLibrary "drawcandles"
simple utility to draw different candles using box and lines. Quite useful for drawing candles such as zigzag candles or MTF candles
draw(o, h, l, c, oBar, cBar)
draws candles based on ohlc values
Parameters:
o : Open Price
h : High Price
l : Low Price
c : Close Price
oBar : Open Time
cBar : Close Time
Returns: void
Arrays
curveLibrary "curve"
Regression array Creator. Handy for weights, Auto Normalizes array while holding curves.
curve(_size, _power)
Curve Regression Values Tool
Parameters:
_size : (float) Number of Steps required (float works, future consideration)
_power : (float) Strength of value decrease
Returns: (float ) Array of multipliers from 1 downwards to 0.
Object: object oriented programming made possible! Hash map's in Pinescript?? Absolutely
This Library is the first step towards bringing a much needed data structure to the Pine Script community.
"Object" allows Pine coders to finally create objects full or unique key:value pairs, which are converted to strings and stored in an array. Data can be stored and accessed using dedicated get and set methods.
The workflow is simple, but has a few nuances:
0. Import this library into your project; you can give it whatever alias you'd like (I'll be using obj)
1. Create your first object using the obj.new() method and assign it a variable or "ID".
2. Use the object's ID as the first argument into the obj.set() method, for the key and value there's one extra step required. They must be added as arguments to the appropriate prop_() method.
Note: While objects in this library technically only store data as strings, any primitive data type can be converted to a string before being stored, meaning that one object can hold data from multiple types at once. There's a trade off though..Pine Script requires that all exported function parameters have pre-defined types, meaning that as convenient as it would be to have a single method for storing and returning data of every type, it's not currently possible. Instead there are functions to add properties for each individual type, which are then converted to strings automatically (the original type is flagged and stored along with the data). Furthermore, since switch/if statements can only return values of the same type, there must also be "get" methods which correspond with each type. Again, a single "get" method which auto-detects the returned value's type was the goal but it's just not currently possible. Instead each get method is only allowed to return a value of its own type. No worries though, all the "get" methods will throw errors if they can't access the data you're trying to access. In that error message, you'll be informed exactly which "get" method you need to use if you ever lose track of what type of data you should be returning.
3. The second argument for obj.set() method is the obj.prop_() method. You just plug in your key as a string and your value and you're done. Easy as that.
Please do not skip this step, properties must be formatted correctly for data to be stored and accessed correctly
4. Obj.get_ (s: string, f: float, b: bool, i: int) methods are even easier, just choose whichever method will return the data type you need, then plug in your ID, and key and that's it. Objects will output data of the same type they were stored as!
There's a short example at the end of the script if you'd like to see more!
prop_string(string: key, string: value)
returns property formatted to string and flagged as string type
prop_float(string: key, float: value)
returns property formatted to string and flagged as float type
prop_bool(string: key, bool: value)
returns property formatted to string and flagged as bool type
prop_int(string: key, int: value)
returns property formatted to string and flagged as int type
Support for lines and shapes coming soon!
new()
returns an empty object
set(string : ID, string: property)
adds new property to object
get_f(string : ID, string: key)
returns float values
get_s(string : ID, string: key)
returns string values
get_b(string : ID, string: key)
returns boolean values
get_i(string : ID, string: key)
returns int values
More methods like Obj.remove(), Obj.size(), Obj.fromString, Obj.fromArray, Obj.toJSON, Obj.keys, & Obj.values coming very soon!!
arraysLibrary "arrays"
Library contains utility functions using arrays.
delete( arr , index)
remove an item from array at specific index. Also deletes the item
Parameters:
arr: - array from which the item needs to be deleted
index: - index of item to be deleted
Returns: void
pop( arr )
remove the last item from array. Also deletes the item
Parameters:
arr: - array from which the last item needs to be removed and deleted
Returns: void
shift( arr )
remove an item from array at index 0. Also deletes the item
Parameters:
arr: - array from which the first item needs to be removed and deleted
Returns: void
unshift( arr , val, maxItems)
add an item to the beginning of an array with max items cap
Parameters:
arr: - array to which the item needs to be added at the beginning
val: - value of item which needs to be added
maxItems: - max items array can hold. After that, items are removed from the other end
Returns: resulting array
clear( arr )
remove and delete all items in an array
Parameters:
arr: - array which needs to be cleared
Returns: void
push( arr , val, maxItems)
add an item to the end of an array with max items cap
Parameters:
arr: - array to which the item needs to be added at the beginning
val: - value of item which needs to be added
maxItems: - max items array can hold. After that, items are removed from the starting index
Returns: resulting array
HarmonicCalculation█ OVERVIEW
This library is complementary for XABCD Harmonic Pattern Custom Range Interactive
PriceDiff()
: Price Difference
Parameters:
: : price_1, price_2
Returns: : PriceDiff
TimeDiff()
: Time Difference
Parameters:
: : time_1, time_2
Returns: : TimeDiff
ReturnIndexOf3Arrays()
: Return Index Of 3 Arrays
Parameters:
: : id1, id2, id3, _int
Returns: : ReturnIndexOf3Arrays
AbsoluteRange()
: Price Difference
Parameters:
: : price, y, point
Returns: : AbsoluteRange
PriceAverage()
: To calculate average of 2 prices
Parameters:
: : price_1, price_2
Returns: : PriceAverage
TimeAverage()
: To calculate average of 2 times
Parameters:
: : time_1, time_2
Returns: : TimeAverage
StringBool()
: To show ratio in 3 decimals format
Parameters:
: : _value, _bool, _text
Returns: : StringBool
PricePercent()
: To show Price in percent format
Parameters:
: : _price, PriceRef, str_dir
Returns: : PricePercent
BoolCurrency()
: To show syminfo.currency
Parameters:
: : _bool
Returns: : BoolCurrency
RatioText()
: To show RatioText in 3 decimals format
Parameters:
: : _value, _text
Returns: : RatioText
RangeText()
: To display RangeText in Harmonic Range Format
Parameters:
: : _id1, _id2, _int, _text
Returns: : RangeText
PriceCurrency()
: To show Currency in Price Format
Parameters:
: : _bool, _value
Returns: : PriceCurrency
HarmonicDB█ OVERVIEW
This library was to showcase database for specifications of Harmonic Patterns using arrays.
█ CREDITS
Scott M Carney, author of Harmonic Trading : Volume Three
animal_db(x)
TODO: export animal_db
Parameters:
x : TODO: float value is set to default if not necessary
Returns: TODO:
DeleteArrayObject█ OVERVIEW
Delete array object according to array size such as label, line, linefill, box and table.
█ CREDITS
HeWhoMustNotBeNamed
"Swap" - Bool/Position/Value : Array / Matrix / Var AutoswapLibrary "swap"
Side / Boundary Based All Types Swapper
- three automagical types for Arrays, Matrixes, and Variables
-- no signal : Long/ Short position autoswap
-- true / false : Boolean based side choice
-- Src / Thresh : if source is above or below the threshold
- two operating modes for variables, Holding mode only for arrays/matrixes
-- with two items, will automatically change between the two caveat is it does not delete table/box/line(fill VAR items automatically)
-- with three items, a neutral is available for NA input or neutral
- one function name for all of them. One import name that's easy to type/remember
-- make life easy for your conditional items.
side(source, thresh, _a, _b, _c)
side Change outputs based on position or a crossing level
Parameters:
source : (float) OPTIONAL value input
thresh : (float) OPTIONAL boundary line to cross
_a : (any) if Long/True/Above
_b : (any) if Short/False/Below
_c : (any) OPTIONAL NOT FOR MTX OR ARR... Neutral Item, if var/varip on a/b it will leave behind, ie, a table or box or line will not erase , if it's a varip you're sending in.
Returns: first, second, or third items based on input conditions
Please notify if bugs found.
Thanks.
[LIB] Array / Matrix DisplayLibrary "ArrayMatrixHUD"
Show Array or Matrix Elements In Table
For Arrays: Set the number of rows you want the data displayed in and it will generate a table, calculating the columns based on the size of the array being displayed.
For Matrix: It will automatically match the Rows and Columns to the values in the matrix.
Note: On the left, the table shows the index of the array/matrix value starting at 1. So, to call that value from inside the array, subtract 1 from the index value to the left. For matrices, keep in mind that the row and column are also starting at one when trying to call a value from the matrix. The numbering of the values on the left is for display purposes only.
viewArray(_arrayName, _pos, _txtSize, _tRows)
Array Element Display (Supports float, int, string, and bool)
Parameters:
_arrayName : ID of Array to be Displayed
_pos : Position for Table
_txtSize : Size of Table Cell Text
_tRows : Number of Rows to Display Data In (columns will be calculated accordingly)
Returns: A Display of Array Values in a Table
viewMatrix(_matrixName, _pos, _txtSize)
Matrix Element Display (Supports float, int, string, and bool)
Parameters:
_matrixName : ID of Matrix to be Displayed
_pos : Position for Table
_txtSize : Size of Table Cell Text
Returns: A Display of Matrix Values in a Table
RecursiveAlertsLibrary "RecursiveAlerts"
The library provides options to run alert() calls in loop without worrying about limitations of frequency options.
When an alert statement is called within a loop,
it will fire just once per bar irrespective of how many iterations allowed when fequency is set to alert.freq_once_per_bar or alert.freq_once_per_bar_close
it will fire continuously till it breaks when frequency is set to alert.freq_all
The function helps overcome this issue by using varip key array which resets on every bar
rAlert(message, key) Enhanced alert which can be used in loops
Parameters:
message : Alert message to be fired
key : Key to be checked to avoid repetitive alerts
Returns: array containing id of already fired alerts
Thanks to @theheirophant, @JohnBaron and @LucF for discussions and suggestion which eventually lead to this solution :)
ColorArrayLibrary "ColorArray"
Simple color array gradient tool.
makeGradient(size, _col1, _col2, _col3, _col4, _col5) Color Gradient Array from 5 colors.
Parameters:
size : : default 10
_col1 : : default #ff0000
_col2 : : default #ffff00
_col3 : : default #00ff00
_col4 : : default #00ffff
_col5 : : default #0000ff
Returns: array of colors to specified size.
PivotThis library was designed to create three different datasets using Bill Williams fractals. The goal is to spot trends in reversal data and ultimately use these datasets to help predict future price reversals.
First, the pivot() function is used to initialize and populate three separate arrays (high pivot , low pivot , all pivots ). Since each high/low price depends on the bar_index, the bar_index, pivot direction(high/low), and high/low values are compressed into a string to maintain the data's integrity ("__"). Once each string array is populated and organized by bar_index, all three are returned inside a tuple. The return value must be deconstructed H,L,A =pivot() for each array's values to be accessed using getPivot() . This boilerplate allows for data to be accessed more efficiently in a recursive environment. getPivot() was designed to be used inside of a for or while block to populate matrices for further analyses. Again, getPivot() return values must be exposed through deconstruction. x,d,y =getPivot(). See code for more details.
pivot(int XLR) initializes and populates arrays
Parameters
XLR - number of bars to the left and right that must be lower for a high to be considered a pivotHigh, or vice versa. This number will drastically change the size and scope of the returned datasets. smaller values will produce much larger datasets, which might model short term price activity well. In contrast, larger values will produce smaller datasets which might model longer term price activity well.
Returns - tuple [string ]
getPivot(string arrayID, int index) accesses array data
Parameters
arrayID - the variable name for one of the three arrays returned by pivot().
index - the index of the provided array, with 0 being the most recent pivot point. can be set to " i " in a loop to access values recursively
Returns - tuple
FunctionIntrabarCrossValueLibrary "FunctionIntrabarCrossValue"
intrabar_cross_value(a, b, step) Find the minimum difference of a intrabar cross and return its median value.
Parameters:
a : float, series a.
b : float, series b.
step : float, step to iterate x axis, default=0.01
Returns: float
BitcoinHalvingLibrary "BitcoinHalving"
Displays where Bitcoin's halvings have been
getDates() List of Bitcoin halving dates
Returns: array with timestamp dates
isHalvingDay() Checks if the current day is a halving day
Returns: bool
matrixautotableLibrary "matrixautotable"
Automatic Table from Matrixes with pseudo correction for na values and default color override for missing values. uses overloads in cases of cheap float only, with additional addon for strings next, then cell colors, then text colors, and tooltips last.. basic size and location are auto, include the template to speed this up...
TODO : make bools version
var string group_table = ' Table'
var int _tblssizedemo = input.int ( 10 )
string tableYpos = input.string ( 'middle' , '↕' , inline = 'place' , group = group_table, options= )
string tableXpos = input.string ( 'center' , '↔' , inline = 'place' , group = group_table, options= , tooltip='Position on the chart.')
int _textSize = input.int ( 1 , 'Table Text Size' , inline = 'place' , group = group_table)
var matrix _floatmatrix = matrix.new (_tblssizedemo, _tblssizedemo, 0 )
var matrix _stringmatrix = matrix.new (_tblssizedemo, _tblssizedemo, 'test' )
var matrix _bgcolormatrix = matrix.new (_tblssizedemo, _tblssizedemo, color.white )
var matrix _textcolormatrix = matrix.new (_tblssizedemo, _tblssizedemo, color.black )
var matrix _tooltipmatrix = matrix.new (_tblssizedemo, _tblssizedemo, 'tool' )
// basic table ready to go with the aboec matrixes (replace in your code)
// for demo purpose, random colors, random nums, random na vals
if barstate.islast
varip _xsize = matrix.rows (_floatmatrix) -1
varip _ysize = matrix.columns (_floatmatrix) -1
for _xis = 0 to _xsize -1 by 1
for _yis = 0 to _ysize -1 by 1
_randomr = int(math.random(50,250))
_randomg = int(math.random(50,250))
_randomb = int(math.random(50,250))
_randomt = int(math.random(10,90 ))
bgcolor = color.rgb(250 - _randomr, 250 - _randomg, 250 - _randomb, 100 - _randomt )
txtcolor = color.rgb(_randomr, _randomg, _randomb, _randomt )
matrix.set(_bgcolormatrix ,_yis,_xis, bgcolor )
matrix.set(_textcolormatrix ,_yis,_xis, txtcolor)
matrix.set(_floatmatrix ,_yis,_xis, _randomr)
// random na
_ymiss = math.floor(math.random(0, _yis))
_xmiss = math.floor(math.random(0, _xis))
matrix.set( _floatmatrix ,_ymiss, _xis, na)
matrix.set( _stringmatrix ,_ymiss, _xis, na)
matrix.set( _bgcolormatrix ,_ymiss, _xis, na)
matrix.set( _textcolormatrix ,_ymiss, _xis, na)
matrix.set( _tooltipmatrix ,_ymiss, _xis, na)
// import here
import kaigouthro/matrixautotable/1 as mtxtbl
// and render table..
mtxtbl.matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix, _textSize ,tableYpos ,tableXpos)
matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix, _textSize, tableYpos, tableXpos) matrixtable
Parameters:
_floatmatrix : float vals
_stringmatrix : string
_bgcolormatrix : color
_textcolormatrix : color
_tooltipmatrix : string
_textSize : int
tableYpos : string
tableXpos : string
matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _textSize, tableYpos, tableXpos) matrixtable
Parameters:
_floatmatrix : float vals
_stringmatrix : string
_bgcolormatrix : color
_textcolormatrix : color
_textSize : int
tableYpos : string
tableXpos : string
matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _txtdefcol, _textSize, tableYpos, tableXpos) matrixtable
Parameters:
_floatmatrix : float vals
_stringmatrix : string
_bgcolormatrix : color
_txtdefcol : color
_textSize : int
tableYpos : string
tableXpos : string
matrixtable(_floatmatrix, _stringmatrix, _txtdefcol, _bgdefcol, _textSize, tableYpos, tableXpos) matrixtable
Parameters:
_floatmatrix : float vals
_stringmatrix : string
_txtdefcol : color
_bgdefcol : color
_textSize : int
tableYpos : string
tableXpos : string
matrixtable(_floatmatrix, _txtdefcol, _bgdefcol, _textSize, tableYpos, tableXpos) matrixtable
Parameters:
_floatmatrix : float vals
_txtdefcol : color
_bgdefcol : color
_textSize : int
tableYpos : string
tableXpos : string
mZigzagLibrary "mZigzag"
Matrix implementation of zigzag to allow further possibilities.
Main advantage of this library over previous zigzag methods is that you can attach any number of indicator/oscillator information to zigzag
calculate(length, ohlc, indicatorHigh, indicatorLow, numberOfPivots) calculates zigzag and related information
Parameters:
length : is zigzag length
ohlc : array of OHLC values to be used for zigzag calculation
indicatorHigh : Array of indicator values calculated based on high price of OHLC
indicatorLow : Array of indicators values calculated based on low price of OHLC
numberOfPivots : Number of pivots to be returned
Returns: pivotMatrix Matrix containing zigzag pivots, pivot bars, direction, ratio, and indicators added via indicatorHigh/indicatorLow
newZG is true if a new pivot is added to array
doubleZG is true if last calculation returned two new pivots (Happens on extreme price change)
draw(length, ohlc, indicatorLabels, indicatorHigh, indicatorLow, numberOfPivots, lineColor, lineWidth, lineStyle, showHighLow, showRatios, showIndicators) draws zigzag and related information
Parameters:
length : is zigzag length
ohlc : array of OHLC values to be used for zigzag calculation
indicatorLabels : Array of name of indicators passed
indicatorHigh : Array of indicator values calculated based on high price of OHLC
indicatorLow : Array of indicators values calculated based on low price of OHLC
numberOfPivots : Number of pivots to be returned
lineColor : zigzag line color. set to blue by default
lineWidth : zigzag line width. set to 1 by default
lineStyle : zigzag line style. set to line.style_solid by default
showHighLow : show HH, HL, LH, LL labels
showRatios : show pivot retracement ratios from previous zigzag
showIndicators : show indicator values
Returns: pivotMatrix Matrix containing zigzag pivots, pivot bars, direction, ratio, and indicators added via indicatorHigh/indicatorLow
zigzaglines array of zigzag lines
zigzaglabels array of zigzag labels
_matrixLibrary "_matrix"
Library helps visualize matrix as array of arrays and enables users to use array methods such as push, pop, shift, unshift etc along with cleanup activities on drawing objects wherever required
unshift(mtx, row) unshift array of lines to first row of the matrix
Parameters:
mtx : matrix of lines
row : array of lines to be inserted in row
Returns: resulting matrix of lines
unshift(mtx, row) unshift array of labels to first row of the matrix
Parameters:
mtx : matrix of labels
row : array of labels to be inserted in row
Returns: resulting matrix labels
unshift(mtx, row) unshift array of boxes to first row of the matrix
Parameters:
mtx : matrix of boxes
row : array of boxes to be inserted in row
Returns: resulting matrix of boxes
unshift(mtx, row) unshift array of linefill to first row of the matrix
Parameters:
mtx : matrix of linefill
row : array of linefill to be inserted in row
Returns: resulting matrix of linefill
unshift(mtx, row) unshift array of tables to first row of the matrix
Parameters:
mtx : matrix of tables
row : array of tables to be inserted in row
Returns: resulting matrix of tables
unshift(mtx, row) unshift array of int to first row of the matrix
Parameters:
mtx : matrix of int
row : array of int to be inserted in row
Returns: resulting matrix of int
unshift(mtx, row) unshift array of float to first row of the matrix
Parameters:
mtx : matrix of float
row : array of float to be inserted in row
Returns: resulting matrix of float
unshift(mtx, row) unshift array of bool to first row of the matrix
Parameters:
mtx : matrix of bool
row : array of bool to be inserted in row
Returns: resulting matrix of bool
unshift(mtx, row) unshift array of string to first row of the matrix
Parameters:
mtx : matrix of string
row : array of string to be inserted in row
Returns: resulting matrix of string
unshift(mtx, row) unshift array of color to first row of the matrix
Parameters:
mtx : matrix of colors
row : array of colors to be inserted in row
Returns: resulting matrix of colors
push(mtx, row) push array of lines to end of the matrix row
Parameters:
mtx : matrix of lines
row : array of lines to be inserted in row
Returns: resulting matrix of lines
push(mtx, row) push array of labels to end of the matrix row
Parameters:
mtx : matrix of labels
row : array of labels to be inserted in row
Returns: resulting matrix of labels
push(mtx, row) push array of boxes to end of the matrix row
Parameters:
mtx : matrix of boxes
row : array of boxes to be inserted in row
Returns: resulting matrix of boxes
push(mtx, row) push array of linefill to end of the matrix row
Parameters:
mtx : matrix of linefill
row : array of linefill to be inserted in row
Returns: resulting matrix of linefill
push(mtx, row) push array of tables to end of the matrix row
Parameters:
mtx : matrix of tables
row : array of tables to be inserted in row
Returns: resulting matrix of tables
push(mtx, row) push array of int to end of the matrix row
Parameters:
mtx : matrix of int
row : array of int to be inserted in row
Returns: resulting matrix of int
push(mtx, row) push array of float to end of the matrix row
Parameters:
mtx : matrix of float
row : array of float to be inserted in row
Returns: resulting matrix of float
push(mtx, row) push array of bool to end of the matrix row
Parameters:
mtx : matrix of bool
row : array of bool to be inserted in row
Returns: resulting matrix of bool
push(mtx, row) push array of string to end of the matrix row
Parameters:
mtx : matrix of string
row : array of string to be inserted in row
Returns: resulting matrix of string
push(mtx, row) push array of colors to end of the matrix row
Parameters:
mtx : matrix of colors
row : array of colors to be inserted in row
Returns: resulting matrix of colors
shift(mtx) shift removes first row from matrix of lines
Parameters:
mtx : matrix of lines from which the shift operation need to be performed
Returns: void
shift(mtx) shift removes first row from matrix of labels
Parameters:
mtx : matrix of labels from which the shift operation need to be performed
Returns: void
shift(mtx) shift removes first row from matrix of boxes
Parameters:
mtx : matrix of boxes from which the shift operation need to be performed
Returns: void
shift(mtx) shift removes first row from matrix of linefill
Parameters:
mtx : matrix of linefill from which the shift operation need to be performed
Returns: void
shift(mtx) shift removes first row from matrix of tables
Parameters:
mtx : matrix of tables from which the shift operation need to be performed
Returns: void
shift(mtx) shift removes first row from matrix of int
Parameters:
mtx : matrix of int from which the shift operation need to be performed
Returns: void
shift(mtx) shift removes first row from matrix of float
Parameters:
mtx : matrix of float from which the shift operation need to be performed
Returns: void
shift(mtx) shift removes first row from matrix of bool
Parameters:
mtx : matrix of bool from which the shift operation need to be performed
Returns: void
shift(mtx) shift removes first row from matrix of string
Parameters:
mtx : matrix of string from which the shift operation need to be performed
Returns: void
shift(mtx) shift removes first row from matrix of colors
Parameters:
mtx : matrix of colors from which the shift operation need to be performed
Returns: void
pop(mtx) pop removes last row from matrix of lines
Parameters:
mtx : matrix of lines from which the pop operation need to be performed
Returns: void
pop(mtx) pop removes last row from matrix of labels
Parameters:
mtx : matrix of labels from which the pop operation need to be performed
Returns: void
pop(mtx) pop removes last row from matrix of boxes
Parameters:
mtx : matrix of boxes from which the pop operation need to be performed
Returns: void
pop(mtx) pop removes last row from matrix of linefill
Parameters:
mtx : matrix of linefill from which the pop operation need to be performed
Returns: void
pop(mtx) pop removes last row from matrix of tables
Parameters:
mtx : matrix of tables from which the pop operation need to be performed
Returns: void
pop(mtx) pop removes last row from matrix of int
Parameters:
mtx : matrix of int from which the pop operation need to be performed
Returns: void
pop(mtx) pop removes last row from matrix of float
Parameters:
mtx : matrix of float from which the pop operation need to be performed
Returns: void
pop(mtx) pop removes last row from matrix of bool
Parameters:
mtx : matrix of bool from which the pop operation need to be performed
Returns: void
pop(mtx) pop removes last row from matrix of string
Parameters:
mtx : matrix of string from which the pop operation need to be performed
Returns: void
pop(mtx) pop removes last row from matrix of colors
Parameters:
mtx : matrix of colors from which the pop operation need to be performed
Returns: void
clear(mtx) clear clears the matrix of lines
Parameters:
mtx : matrix of lines which needs to be cleared
Returns: void
clear(mtx) clear clears the matrix of labels
Parameters:
mtx : matrix of labels which needs to be cleared
Returns: void
clear(mtx) clear clears the matrix of boxes
Parameters:
mtx : matrix of boxes which needs to be cleared
Returns: void
clear(mtx) clear clears the matrix of linefill
Parameters:
mtx : matrix of linefill which needs to be cleared
Returns: void
clear(mtx) clear clears the matrix of tables
Parameters:
mtx : matrix of tables which needs to be cleared
Returns: void
clear(mtx) clear clears the matrix of int
Parameters:
mtx : matrix of int which needs to be cleared
Returns: void
clear(mtx) clear clears the matrix of float
Parameters:
mtx : matrix of float which needs to be cleared
Returns: void
clear(mtx) clear clears the matrix of bool
Parameters:
mtx : matrix of bool which needs to be cleared
Returns: void
clear(mtx) clear clears the matrix of string
Parameters:
mtx : matrix of string which needs to be cleared
Returns: void
clear(mtx) clear clears the matrix of colors
Parameters:
mtx : matrix of colors which needs to be cleared
Returns: void
FunctionMatrixSolveLibrary "FunctionMatrixSolve"
Matrix Equation solution for Ax = B, finds the value of x.
solve(A, B) Solves Matrix Equation for Ax = B, finds value for x.
Parameters:
A : matrix, Square matrix with data values.
B : matrix, One column matrix with data values.
Returns: matrix with X, x = A^-1 b, assuming A is square and has full rank
introcs.cs.princeton.edu
FunctionPolynomialFitLibrary "FunctionPolynomialFit"
Performs Polynomial Regression fit to data.
In statistics, polynomial regression is a form of regression analysis in which
the relationship between the independent variable x and the dependent variable
y is modelled as an nth degree polynomial in x.
reference:
en.wikipedia.org
www.bragitoff.com
gauss_elimination(A, m, n) Perform Gauss-Elimination and returns the Upper triangular matrix and solution of equations.
Parameters:
A : float matrix, data samples.
m : int, defval=na, number of rows.
n : int, defval=na, number of columns.
Returns: float array with coefficients.
polyfit(X, Y, degree) Fits a polynomial of a degree to (x, y) points.
Parameters:
X : float array, data sample x point.
Y : float array, data sample y point.
degree : int, defval=2, degree of the polynomial.
Returns: float array with coefficients.
note:
p(x) = p * x**deg + ... + p
interpolate(coeffs, x) interpolate the y position at the provided x.
Parameters:
coeffs : float array, coefficients of the polynomial.
x : float, position x to estimate y.
Returns: float.
InitialiseArraysLibrary "InitialiseArrays"
@description: Efficiently create arrays, populating them with an arbitrary number of elements and setting their starting values. Works with a mix of typed and na values.
A limitation of the built-in functions to create arrays is that while you can create and populate arrays with a single command, you can only set all elements to the same value in this way.
Or, you can create an array from a set of values or variables, but you can't include any na values.
Now, it's easy enough to work around this, but I wanted to make something more efficient (because I want to use lots of arrays), hence this library.
Calling a function from here is more efficient because you only do it once (assuming it's a var) and don't evaluate an if condition each run, and don't create unnecessary variables.
It's also easier to read and takes less space.
f_initialiseBoolArray()
@function f_initialiseBoolArray(string _values) Creates a boolean array, populated with the values that you specify in the input string.
@param _values is a string that contains a comma-separated list of the values that you want to initialise the boolean array with. Values other than true, false, and na are disregarded. Spaces are disregarded.
@returns Returns a boolean array of arbitrary length.
f_initialiseFloatArray()
@function f_initialiseFloatArray(string _values) Creates a float array, populated with the values that you specify in the input string.
@param _values is a string that contains a comma-separated list of the values that you want to initialise the float array with. Non-numerical entries are converted to NaN values. Spaces are disregarded.
@returns Returns a float array of arbitrary length.
f_initialiseIntArray()
@function f_initialiseIntArray(string _values) Creates an int array, populated with the values that you specify in the input string.
@param _values is a string that contains a comma-separated list of the values that you want to initialise the int array with. Floating-point numbers are rounded down to the nearest integer. Any na values are preserved. Spaces are disregarded.
@returns Returns a float array of arbitrary length.
V1 includes functions for bools, floats, and ints. I might extend it if people want.
drawingutilsLibrary "drawingutils"
Private methods used in my scripts for some basic and customized drawings. No documentation provided as these are meant for private use only.
draw_line()
draw_label()
draw_linefill()
draw_labelled_line()
draw_labelled_box()
runTimer()
ConditionalAverages█ OVERVIEW
This library is a Pine Script™ programmer’s tool containing functions that average values selectively.
█ CONCEPTS
Averaging can be useful to smooth out unstable readings in the data set, provide a benchmark to see the underlying trend of the data, or to provide a general expectancy of values in establishing a central tendency. Conventional averaging techniques tend to apply indiscriminately to all values in a fixed window, but it can sometimes be useful to average values only when a specific condition is met. As conditional averaging works on specific elements of a dataset, it can help us derive more context-specific conclusions. This library offers a collection of averaging methods that not only accomplish these tasks, but also exploit the efficiencies of the Pine Script™ runtime by foregoing unnecessary and resource-intensive for loops.
█ NOTES
To Loop or Not to Loop
Though for and while loops are essential programming tools, they are often unnecessary in Pine Script™. This is because the Pine Script™ runtime already runs your scripts in a loop where it executes your code on each bar of the dataset. Pine Script™ programmers who understand how their code executes on charts can use this to their advantage by designing loop-less code that will run orders of magnitude faster than functionally identical code using loops. Most of this library's function illustrate how you can achieve loop-less code to process past values. See the User Manual page on loops for more information. If you are looking for ways to measure execution time for you scripts, have a look at our LibraryStopwatch library .
Our `avgForTimeWhen()` and `totalForTimeWhen()` are exceptions in the library, as they use a while structure. Only a few iterations of the loop are executed on each bar, however, as its only job is to remove the few elements in the array that are outside the moving window defined by a time boundary.
Cumulating and Summing Conditionally
The ta.cum() or math.sum() built-in functions can be used with ternaries that select only certain values. In our `avgWhen(src, cond)` function, for example, we use this technique to cumulate only the occurrences of `src` when `cond` is true:
float cumTotal = ta.cum(cond ? src : 0) We then use:
float cumCount = ta.cum(cond ? 1 : 0) to calculate the number of occurrences where `cond` is true, which corresponds to the quantity of values cumulated in `cumTotal`.
Building Custom Series With Arrays
The advent of arrays in Pine has enabled us to build our custom data series. Many of this library's functions use arrays for this purpose, saving newer values that come in when a condition is met, and discarding the older ones, implementing a queue .
`avgForTimeWhen()` and `totalForTimeWhen()`
These two functions warrant a few explanations. They operate on a number of values included in a moving window defined by a timeframe expressed in milliseconds. We use a 1D timeframe in our example code. The number of bars included in the moving window is unknown to the programmer, who only specifies the period of time defining the moving window. You can thus use `avgForTimeWhen()` to calculate a rolling moving average for the last 24 hours, for example, that will work whether the chart is using a 1min or 1H timeframe. A 24-hour moving window will typically contain many more values on a 1min chart that on a 1H chart, but their calculated average will be very close.
Problems will arise on non-24x7 markets when large time gaps occur between chart bars, as will be the case across holidays or trading sessions. For example, if you were using a 24H timeframe and there is a two-day gap between two bars, then no chart bars would fit in the moving window after the gap. The `minBars` parameter mitigates this by guaranteeing that a minimum number of bars are always included in the calculation, even if including those bars requires reaching outside the prescribed timeframe. We use a minimum value of 10 bars in the example code.
Using var in Constant Declarations
In the past, we have been using var when initializing so-called constants in our scripts, which as per the Style Guide 's recommendations, we identify using UPPER_SNAKE_CASE. It turns out that var variables incur slightly superior maintenance overhead in the Pine Script™ runtime, when compared to variables initialized on each bar. We thus no longer use var to declare our "int/float/bool" constants, but still use it when an initialization on each bar would require too much time, such as when initializing a string or with a heavy function call.
Look first. Then leap.
█ FUNCTIONS
avgWhen(src, cond)
Gathers values of the source when a condition is true and averages them over the total number of occurrences of the condition.
Parameters:
src : (series int/float) The source of the values to be averaged.
cond : (series bool) The condition determining when a value will be included in the set of values to be averaged.
Returns: (float) A cumulative average of values when a condition is met.
avgWhenLast(src, cond, cnt)
Gathers values of the source when a condition is true and averages them over a defined number of occurrences of the condition.
Parameters:
src : (series int/float) The source of the values to be averaged.
cond : (series bool) The condition determining when a value will be included in the set of values to be averaged.
cnt : (simple int) The quantity of last occurrences of the condition for which to average values.
Returns: (float) The average of `src` for the last `x` occurrences where `cond` is true.
avgWhenInLast(src, cond, cnt)
Gathers values of the source when a condition is true and averages them over the total number of occurrences during a defined number of bars back.
Parameters:
src : (series int/float) The source of the values to be averaged.
cond : (series bool) The condition determining when a value will be included in the set of values to be averaged.
cnt : (simple int) The quantity of bars back to evaluate.
Returns: (float) The average of `src` in last `cnt` bars, but only when `cond` is true.
avgSince(src, cond)
Averages values of the source since a condition was true.
Parameters:
src : (series int/float) The source of the values to be averaged.
cond : (series bool) The condition determining when the average is reset.
Returns: (float) The average of `src` since `cond` was true.
avgForTimeWhen(src, ms, cond, minBars)
Averages values of `src` when `cond` is true, over a moving window of length `ms` milliseconds.
Parameters:
src : (series int/float) The source of the values to be averaged.
ms : (simple int) The time duration in milliseconds defining the size of the moving window.
cond : (series bool) The condition determining which values are included. Optional.
minBars : (simple int) The minimum number of values to keep in the moving window. Optional.
Returns: (float) The average of `src` when `cond` is true in the moving window.
totalForTimeWhen(src, ms, cond, minBars)
Sums values of `src` when `cond` is true, over a moving window of length `ms` milliseconds.
Parameters:
src : (series int/float) The source of the values to be summed.
ms : (simple int) The time duration in milliseconds defining the size of the moving window.
cond : (series bool) The condition determining which values are included. Optional.
minBars : (simple int) The minimum number of values to keep in the moving window. Optional.
Returns: (float) The sum of `src` when `cond` is true in the moving window.
harmonicpatternsarraysLibrary "harmonicpatternsarrays"
Library provides an alternative method to scan harmonic patterns and contains utility functions using arrays.
These are mostly customized for personal use. Hence, will not add documentation for arrays. All credit to @HeWhoMustNotBeNamed
getLabel()
delete()
delete()
delete()
delete()
delete()
pop()
pop()
pop()
pop()
pop()
shift()
shift()
shift()
shift()
shift()
unshift()
unshift()
unshift()
unshift()
unshift()
unshift()
unshift()
unshift()
unshift()
unshift()
clear()
clear()
clear()
clear()
clear()
push()
push()
push()
push()
push()
push()
push()
push()
push()
push()
get_trend_series()
getrange()
getSupportedPatterns()
scan_xab()
scan_abc_axc()
scan_bcd()
scan_xad_xcd()
get_prz_range()
isHarmonicPattern()