_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
Indicators and strategies
OrdinaryLeastSquaresLibrary "OrdinaryLeastSquares"
One of the most common ways to estimate the coefficients for a linear regression is to use the Ordinary Least Squares (OLS) method.
This library implements OLS in pine. This implementation can be used to fit a linear regression of multiple independent variables onto one dependent variable,
as long as the assumptions behind OLS hold.
solve_xtx_inv(x, y) Solve a linear system of equations using the Ordinary Least Squares method.
This function returns both the estimated OLS solution and a matrix that essentially measures the model stability (linear dependence between the columns of 'x').
NOTE: The latter is an intermediate step when estimating the OLS solution but is useful when calculating the covariance matrix and is returned here to save computation time
so that this step doesn't have to be calculated again when things like standard errors should be calculated.
Parameters:
x : The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
y : The matrix containing the dependent variable. This matrix can only contain one dependent variable and can therefore only contain one column. The row count of 'x' and 'y' must match.
Returns: Returns both the estimated OLS solution and a matrix that essentially measures the model stability (xtx_inv is equal to (X'X)^-1).
solve(x, y) Solve a linear system of equations using the Ordinary Least Squares method.
Parameters:
x : The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
y : The matrix containing the dependent variable. This matrix can only contain one dependent variable and can therefore only contain one column. The row count of 'x' and 'y' must match.
Returns: Returns the estimated OLS solution.
standard_errors(x, y, beta_hat, xtx_inv) Calculate the standard errors.
Parameters:
x : The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
y : The matrix containing the dependent variable. This matrix can only contain one dependent variable and can therefore only contain one column. The row count of 'x' and 'y' must match.
beta_hat : The Ordinary Least Squares (OLS) solution provided by solve_xtx_inv() or solve().
xtx_inv : This is (X'X)^-1, which means we take the transpose of the X matrix, multiply that the X matrix and then take the inverse of the result.
This essentially measures the linear dependence between the columns of the X matrix.
Returns: The standard errors.
estimate(x, beta_hat) Estimate the next step of a linear model.
Parameters:
x : The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
beta_hat : The Ordinary Least Squares (OLS) solution provided by solve_xtx_inv() or solve().
Returns: Returns the new estimate of Y based on the linear model.
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.
TPCThemeBlackAndBlue_PublicLibrary "TPCThemeBlackAndBlue_Public"
Provides calculated colors.
colorPrimary()
colorSecondary()
colorTertiary()
labelBgColor()
lHP()
lHS()
lHT()
lV()
TPCColors_PublicLibrary "TPCColors_Public"
Provides calculated colors.
get(colorKey, colorModifier) Returns the length in ms for the given amount of the given interval.
Parameters:
colorKey : Color name, for example "black", "red", or "greenDark"
colorModifier : Color modifier, for example "lightX", "light", or "dark"
Returns: The calculated color.
TPCLines_PublicLibrary "TPCLines_Public"
Helpers for lines
lineVA(start, lines, labels, lineColor, labelBgColor, labelTextColor, highPrice, lowPrice, extend, style, width, labelText, labelSize, labelStyle, labelTextAlign, bi) Draws a vertical line and optional label on the chart.
Parameters:
start : The start bar index or time.
lines : Line array to which the created line will be pushed.
labels : Label array to which the created label will be pushed.
lineColor : The color for the line and label.
labelBgColor : The background color for the label.
labelTextColor : The text color for the label.
highPrice : The upper price for the line.
lowPrice : The lower price for the line.
extend : Options for toggline line extend (extend.right, extend.left, extend.both, or extend.none). If none is provided, provides a best guess.
style : The line's style. Defaults to line.style_dotted.
width : The line's width. Defaults to 1.
labelText : Optional text to display next to the line.
labelSize : The label's size. Defaults to size.tiny.
labelStyle : The label's style. Defaults to label.style_label_left.
labelTextAlign : The label's text alignment. Defaults to text.align_center.
bi : Set true to use bar indices, set false to use time. Defaults to true (use bar indices).
Returns: Nothing. Draws a line and optional label on the chart.
lineHA(price, lines, labels, lineColor, labelBgColor, extend, labelTextColor, labelText, end, start, bi, showPrice, pips, style, width, labelAlign, labelSize, labelStyle, labelTextAlign) Draws a horizontal line and optional label on the chart.
Parameters:
price : The price at which to draw the lie.
lines : Line array to which the created line will be pushed.
labels : Label array to which the created label will be pushed.
lineColor : The color for the line and label.
labelBgColor : The background color for the label.
extend : Options for toggline line extend (extend.right, extend.left, extend.both, or extend.none). Defaults to extend.none.
labelTextColor : The text color for the label.
labelText : Optional text to display next to the line.
end : The time or bar index to end the line at.
start : The time or bar index to start the line at.
bi : Set true to use bar indices, set false to use time. Defaults to true (use bar indices).
showPrice : Option to show the price on the label.
pips : If a value is provided, will be displayed on the label.
style : The line's style. Defaults to line.style_solid.
width : The line's width. Defaults to 1.
labelAlign : Which side of the line to align the label on. Can be r for right, l for left, c for center, or t for the current time.
labelSize : The label's size. Defaults to size.tiny.
labelStyle : The label's style. Defaults to label.style_none.
labelTextAlign : The label's text alignment. Defaults to text.align_center.
Returns: Nothing. Draws a line and optional label on the chart.
lineH()
lineV()
TPCTime_PublicLibrary "TPCTime_Public"
Helpers for calculating time
getTimeOffset(interval, amount) Returns the length in ms for the given amount of the given interval.
Parameters:
interval : Interval to calculate, for example "D" or "60".
amount : Number of intervals for which to calculate the time range in ms.
Returns: The number of ms in the amount of the given interval.
isInTimeRange()
Library CommonLibrary "LibraryCommon"
A collection of custom tools & utility functions commonly used with my scripts
@description TODO: add library description here
getDecimals() Calculates how many decimals are on the quote price of the current market
Returns: The current decimal places on the market quote price
truncate(float, float) Truncates (cuts) excess decimal places
Parameters:
float : number The number to truncate
float : decimalPlaces (default=2) The number of decimal places to truncate to
Returns: The given number truncated to the given decimalPlaces
toWhole(float) Converts pips into whole numbers
Parameters:
float : number The pip number to convert into a whole number
Returns: The converted number
toPips(float) Converts whole numbers back into pips
Parameters:
float : number The whole number to convert into pips
Returns: The converted number
getPctChange(float, float, int) Gets the percentage change between 2 float values over a given lookback period
Parameters:
float : value1 The first value to reference
float : value2 The second value to reference
int : lookback The lookback period to analyze
av_getPositionSize(float, float, float, float) Calculates OANDA forex position size for AutoView based on the given parameters
Parameters:
float : balance The account balance to use
float : risk The risk percentage amount (as a whole number - eg. 1 = 1% risk)
float : stopPoints The stop loss distance in POINTS (not pips)
float : conversionRate The conversion rate of our account balance currency
Returns: The calculated position size (in units - only compatible with OANDA)
bullFib(priceLow, priceHigh, fibRatio) Calculates a bullish fibonacci value
Parameters:
priceLow : The lowest price point
priceHigh : The highest price point
fibRatio : The fibonacci % ratio to calculate
Returns: The fibonacci value of the given ratio between the two price points
bearFib(priceLow, priceHigh, fibRatio) Calculates a bearish fibonacci value
Parameters:
priceLow : The lowest price point
priceHigh : The highest price point
fibRatio : The fibonacci % ratio to calculate
Returns: The fibonacci value of the given ratio between the two price points
getMA(int, string) Gets a Moving Average based on type (MUST BE CALLED ON EVERY CALCULATION)
Parameters:
int : length The MA period
string : maType The type of MA
Returns: A moving average with the given parameters
getEAP(float) Performs EAP stop loss size calculation (eg. ATR >= 20.0 and ATR < 30, returns 20)
Parameters:
float : atr The given ATR to base the EAP SL calculation on
Returns: The EAP SL converted ATR size
getEAP2(float) Performs secondary EAP stop loss size calculation (eg. ATR < 40, add 5 pips, ATR between 40-50, add 10 pips etc)
Parameters:
float : atr The given ATR to base the EAP SL calculation on
Returns: The EAP SL converted ATR size
barsAboveMA(int, float) Counts how many candles are above the MA
Parameters:
int : lookback The lookback period to look back over
float : ma The moving average to check
Returns: The bar count of how many recent bars are above the MA
barsBelowMA(int, float) Counts how many candles are below the MA
Parameters:
int : lookback The lookback period to look back over
float : ma The moving average to reference
Returns: The bar count of how many recent bars are below the EMA
barsCrossedMA(int, float) Counts how many times the EMA was crossed recently
Parameters:
int : lookback The lookback period to look back over
float : ma The moving average to reference
Returns: The bar count of how many times price recently crossed the EMA
getPullbackBarCount(int, int) Counts how many green & red bars have printed recently (ie. pullback count)
Parameters:
int : lookback The lookback period to look back over
int : direction The color of the bar to count (1 = Green, -1 = Red)
Returns: The bar count of how many candles have retraced over the given lookback & direction
getBodySize() Gets the current candle's body size (in POINTS, divide by 10 to get pips)
Returns: The current candle's body size in POINTS
getTopWickSize() Gets the current candle's top wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's top wick size in POINTS
getBottomWickSize() Gets the current candle's bottom wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's bottom wick size in POINTS
getBodyPercent() Gets the current candle's body size as a percentage of its entire size including its wicks
Returns: The current candle's body size percentage
isHammer(float, bool) Checks if the current bar is a hammer candle based on the given parameters
Parameters:
float : fib (default=0.382) The fib to base candle body on
bool : colorMatch (default=false) Does the candle need to be green? (true/false)
Returns: A boolean - true if the current bar matches the requirements of a hammer candle
isStar(float, bool) Checks if the current bar is a shooting star candle based on the given parameters
Parameters:
float : fib (default=0.382) The fib to base candle body on
bool : colorMatch (default=false) Does the candle need to be red? (true/false)
Returns: A boolean - true if the current bar matches the requirements of a shooting star candle
isDoji(float, bool) Checks if the current bar is a doji candle based on the given parameters
Parameters:
float : wickSize (default=2) The maximum top wick size compared to the bottom (and vice versa)
bool : bodySize (default=0.05) The maximum body size as a percentage compared to the entire candle size
Returns: A boolean - true if the current bar matches the requirements of a doji candle
isBullishEC(float, float, bool) Checks if the current bar is a bullish engulfing candle
Parameters:
float : allowance (default=0) How many POINTS to allow the open to be off by (useful for markets with micro gaps)
float : rejectionWickSize (default=disabled) The maximum rejection wick size compared to the body as a percentage
bool : engulfWick (default=false) Does the engulfing candle require the wick to be engulfed as well?
Returns: A boolean - true if the current bar matches the requirements of a bullish engulfing candle
isBearishEC(float, float, bool) Checks if the current bar is a bearish engulfing candle
Parameters:
float : allowance (default=0) How many POINTS to allow the open to be off by (useful for markets with micro gaps)
float : rejectionWickSize (default=disabled) The maximum rejection wick size compared to the body as a percentage
bool : engulfWick (default=false) Does the engulfing candle require the wick to be engulfed as well?
Returns: A boolean - true if the current bar matches the requirements of a bearish engulfing candle
isInsideBar() Detects inside bars
Returns: Returns true if the current bar is an inside bar
isOutsideBar() Detects outside bars
Returns: Returns true if the current bar is an outside bar
barInSession(string, bool) Determines if the current price bar falls inside the specified session
Parameters:
string : sess The session to check
bool : useFilter (default=true) Whether or not to actually use this filter
Returns: A boolean - true if the current bar falls within the given time session
barOutSession(string, bool) Determines if the current price bar falls outside the specified session
Parameters:
string : sess The session to check
bool : useFilter (default=true) Whether or not to actually use this filter
Returns: A boolean - true if the current bar falls outside the given time session
dateFilter(int, int) Determines if this bar's time falls within date filter range
Parameters:
int : startTime The UNIX date timestamp to begin searching from
int : endTime the UNIX date timestamp to stop searching from
Returns: A boolean - true if the current bar falls within the given dates
dayFilter(bool, bool, bool, bool, bool, bool, bool) Checks if the current bar's day is in the list of given days to analyze
Parameters:
bool : monday Should the script analyze this day? (true/false)
bool : tuesday Should the script analyze this day? (true/false)
bool : wednesday Should the script analyze this day? (true/false)
bool : thursday Should the script analyze this day? (true/false)
bool : friday Should the script analyze this day? (true/false)
bool : saturday Should the script analyze this day? (true/false)
bool : sunday Should the script analyze this day? (true/false)
Returns: A boolean - true if the current bar's day is one of the given days
atrFilter()
fillCell()
poStrategyLibraryLibrary "poStrategyLibrary"
essential function for export
isFlat()
isLongShort()
pipProfit()
pipLoss()
OscillatorPivotsLibrary "OscillatorPivots"
Measures pivots in an oscillator and flags if they are above a configurable size. Uses absolute size rather than just highest/lowest in a candle range.
f_osc_Pivots()
Uses the total change in the Y axis, instead of a simple Williams pivot over a defined number of bars. In other words, it measures the size of the actual pivot, not just whether it happens to be the highest/lowest value in a range.
Measures the absolute, cumulative change both before and after the pivot, to avoid flagging mere kinks in trends.
The advantage is that absolute pivot size is, in some cases, precisely what we care about. A disadvantage is that it can take an arbitrary, perhaps long, time to confirm.
You can configure the threshold size of the pivot so that it finds large or small pivots.
Always returns a pivot high after a pivot low, then another pivot high and so on, in order. It never returns a high followed by a high, which simple indicators based on the ta.pivot() function can do.
@param chart_H_1 This must always be set to 1, unless you are using my HighTimeframeTiming library, in which case set it to the output of the function for a _HTF_H of 1.
@param chart_H_2 This must always be set to 2, unless you are using my HighTimeframeTiming library, in which case set it to the output of the function for a _HTF_H of 2.
@param _osc This is the oscillator float value.
@param _oscPivotSize This is the user setting for what counts as a big enough change to be a pivot.
@returns Information about the pivot that is likely to be useful in further calculations:
confirmPeak, confirmDip - whether the pivot was confirmed this bar
peakBarsBack, dipBarsBack - how many bars ago the actual peak or dip was
peakPrice, dipPrice - the value of the oscillator at the peak/dip
It also returns some internal variables, which are plotted in this library only for an understanding of how the function works.
debug_peakStartLevel, debug_dipStartLevel - The level of the currently active peak/dip
ReversalCandlestickPatternWithTrendIndentifierGMLibrary "ReversalCandlestickPatternWithTrendIndentifierGM"
Provides functions calculating the all-time high/low of values.
reversalCandlestickPatternWithTrendIndentifier(bullishcriteria, bearishcriteria, momentumOscillatorTypeInput) Calculates the Reversal Candlestick Pattern With Trend Indentifier.
Parameters:
bullishcriteria : Stoch RSI/RSI Bullish Criteria. defval=70, minval=60, maxval=100
bearishcriteria : Stoch RSI/RSI Bearish Criteria. defval=30, minval=0, maxval=40
momentumOscillatorTypeInput : Momentum Oscillator Type. options=
Returns: Reversal Candlestick Pattern With Trend Indentifier.
DominantCycleCollection of Dominant Cycle estimators. Length adaptation used in the Adaptive Moving Averages and the Adaptive Oscillators try to follow price movements and accelerate/decelerate accordingly (usually quite rapidly with a huge range). Cycle estimators, on the other hand, try to measure the cycle period of the current market, which does not reflect price movement or the rate of change (the rate of change may also differ depending on the cycle phase, but the cycle period itself usually changes slowly). This collection may become encyclopaedic, so if you have any working cycle estimator, drop me a line in the comments below. Suggestions are welcome. Currently included estimators are based on the work of John F. Ehlers
mamaPeriod(src, dynLow, dynHigh) MESA Adaptation - MAMA Cycle
Parameters:
src : Series to use
dynLow : Lower bound for the dynamic length
dynHigh : Upper bound for the dynamic length
Returns: Calculated period
Based on MESA Adaptive Moving Average by John F. Ehlers
Performs Hilbert Transform Homodyne Discriminator cycle measurement
Unlike MAMA Alpha function (in LengthAdaptation library), this does not compute phase rate of change
Introduced in the September 2001 issue of Stocks and Commodities
Inspired by the @everget implementation:
Inspired by the @anoojpatel implementation:
paPeriod(src, dynLow, dynHigh, preHP, preSS, preHP) Pearson Autocorrelation
Parameters:
src : Series to use
dynLow : Lower bound for the dynamic length
dynHigh : Upper bound for the dynamic length
preHP : Use High Pass prefilter (default)
preSS : Use Super Smoother prefilter (default)
preHP : Use Hann Windowing prefilter
Returns: Calculated period
Based on Pearson Autocorrelation Periodogram by John F. Ehlers
Introduced in the September 2016 issue of Stocks and Commodities
Inspired by the @blackcat1402 implementation:
Inspired by the @rumpypumpydumpy implementation:
Corrected many errors, and made small speed optimizations, so this could be the best implementation to date (still slow, though, so may revisit in future)
High Pass and Super Smoother prefilters are used in the original implementation
dftPeriod(src, dynLow, dynHigh, preHP, preSS, preHP) Discrete Fourier Transform
Parameters:
src : Series to use
dynLow : Lower bound for the dynamic length
dynHigh : Upper bound for the dynamic length
preHP : Use High Pass prefilter (default)
preSS : Use Super Smoother prefilter (default)
preHP : Use Hann Windowing prefilter
Returns: Calculated period
Based on Spectrum from Discrete Fourier Transform by John F. Ehlers
Inspired by the @blackcat1402 implementation:
High Pass, Super Smoother and Hann Windowing prefilters are used in the original implementation
phasePeriod(src, dynLow, dynHigh, preHP, preSS, preHP) Phase Accumulation
Parameters:
src : Series to use
dynLow : Lower bound for the dynamic length
dynHigh : Upper bound for the dynamic length
preHP : Use High Pass prefilter (default)
preSS : Use Super Smoother prefilter (default)
preHP : Use Hamm Windowing prefilter
Returns: Calculated period
Based on Dominant Cycle from Phase Accumulation by John F. Ehlers
High Pass and Super Smoother prefilters are used in the original implementation
doAdapt(type, src, len, dynLow, dynHigh, chandeSDLen, chandeSmooth, chandePower, preHP, preSS, preHP) Execute a particular Length Adaptation or Dominant Cycle Estimator from the list
Parameters:
type : Length Adaptation or Dominant Cycle Estimator type to use
src : Series to use
len : Reference lookback length
dynLow : Lower bound for the dynamic length
dynHigh : Upper bound for the dynamic length
chandeSDLen : Lookback length of Standard deviation for Chande's Dynamic Length
chandeSmooth : Smoothing length of Standard deviation for Chande's Dynamic Length
chandePower : Exponent of the length adaptation for Chande's Dynamic Length (lower is smaller variation)
preHP : Use High Pass prefilter for the Estimators that support it (default)
preSS : Use Super Smoother prefilter for the Estimators that support it (default)
preHP : Use Hann Windowing prefilter for the Estimators that support it
Returns: Calculated period (float, not limited)
doEstimate(type, src, dynLow, dynHigh, preHP, preSS, preHP) Execute a particular Dominant Cycle Estimator from the list
Parameters:
type : Dominant Cycle Estimator type to use
src : Series to use
dynLow : Lower bound for the dynamic length
dynHigh : Upper bound for the dynamic length
preHP : Use High Pass prefilter for the Estimators that support it (default)
preSS : Use Super Smoother prefilter for the Estimators that support it (default)
preHP : Use Hann Windowing prefilter for the Estimators that support it
Returns: Calculated period (float, not limited)
LengthAdaptationCollection of dynamic length adaptation algorithms. Mostly from various Adaptive Moving Averages (they are usually just EMA otherwise). Now you can combine Adaptations with any other Moving Averages or Oscillators (see my other libraries), to get something like Deviation Scaled RSI or Fractal Adaptive VWMA. This collection is not encyclopaedic. Suggestions are welcome.
chande(src, len, sdlen, smooth, power) Chande's Dynamic Length
Parameters:
src : Series to use
len : Reference lookback length
sdlen : Lookback length of Standard deviation
smooth : Smoothing length of Standard deviation
power : Exponent of the length adaptation (lower is smaller variation)
Returns: Calculated period
Taken from Chande's Dynamic Momentum Index (CDMI or DYMOI), which is dynamic RSI with this length
Original default power value is 1, but I use 0.5
A variant of this algorithm is also included, where volume is used instead of price
vidya(src, len, dynLow) Variable Index Dynamic Average Indicator (VIDYA)
Parameters:
src : Series to use
len : Reference lookback length
dynLow : Lower bound for the dynamic length
Returns: Calculated period
Standard VIDYA algorithm. The period oscillates from the Lower Bound up (slow)
I took the adaptation part, as it is just an EMA otherwise
vidyaRS(src, len, dynHigh) Relative Strength Dynamic Length - VIDYA RS
Parameters:
src : Series to use
len : Reference lookback length
dynHigh : Upper bound for the dynamic length
Returns: Calculated period
Based on Vitali Apirine's modification (Stocks and Commodities, January 2022) of VIDYA algorithm. The period oscillates from the Upper Bound down (fast)
I took the adaptation part, as it is just an EMA otherwise
kaufman(src, len, dynLow, dynHigh) Kaufman Efficiency Scaling
Parameters:
src : Series to use
len : Reference lookback length
dynLow : Lower bound for the dynamic length
dynHigh : Upper bound for the dynamic length
Returns: Calculated period
Based on Efficiency Ratio calculation orifinally used in Kaufman Adaptive Moving Average developed by Perry J. Kaufman
I took the adaptation part, as it is just an EMA otherwise
ds(src, len) Deviation Scaling
Parameters:
src : Series to use
len : Reference lookback length
Returns: Calculated period
Based on Derivation Scaled Super Smoother (DSSS) by John F. Ehlers
Originally used with Super Smoother
RMS originally has 50 bar lookback. Changed to 4x length for better flexibility. Could be wrong.
maa(src, len, threshold) Median Average Adaptation
Parameters:
src : Series to use
len : Reference lookback length
threshold : Adjustment threshold (lower is smaller length, default: 0.002, min: 0.0001)
Returns: Calculated period
Based on Median Average Adaptive Filter by John F. Ehlers
Discovered and implemented by @cheatcountry:
I took the adaptation part, as it is just an EMA otherwise
fra(len, fc, sc) Fractal Adaptation
Parameters:
len : Reference lookback length
fc : Fast constant (default: 1)
sc : Slow constant (default: 200)
Returns: Calculated period
Based on FRAMA by John F. Ehlers
Modified to allow lower and upper bounds by an unknown author
I took the adaptation part, as it is just an EMA otherwise
mama(src, dynLow, dynHigh) MESA Adaptation - MAMA Alpha
Parameters:
src : Series to use
dynLow : Lower bound for the dynamic length
dynHigh : Upper bound for the dynamic length
Returns: Calculated period
Based on MESA Adaptive Moving Average by John F. Ehlers
Introduced in the September 2001 issue of Stocks and Commodities
Inspired by the @everget implementation:
I took the adaptation part, as it is just an EMA otherwise
doAdapt(type, src, len, dynLow, dynHigh, chandeSDLen, chandeSmooth, chandePower) Execute a particular Length Adaptation from the list
Parameters:
type : Length Adaptation type to use
src : Series to use
len : Reference lookback length
dynLow : Lower bound for the dynamic length
dynHigh : Upper bound for the dynamic length
chandeSDLen : Lookback length of Standard deviation for Chande's Dynamic Length
chandeSmooth : Smoothing length of Standard deviation for Chande's Dynamic Length
chandePower : Exponent of the length adaptation for Chande's Dynamic Length (lower is smaller variation)
Returns: Calculated period (float, not limited)
doMA(type, src, len) MA wrapper on wrapper: if DSSS is selected, calculate it here
Parameters:
type : MA type to use
src : Series to use
len : Filtering length
Returns: Filtered series
Demonstration of a combined indicator: Deviation Scaled Super Smoother
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:
least_squares_regressionLibrary "least_squares_regression"
least_squares_regression: Least squares regression algorithm to find the optimal price interval for a given time period
basic_lsr(series, series, series) basic_lsr: Basic least squares regression algorithm
Parameters:
series : int t: time scale value array corresponding to price
series : float p: price scale value array corresponding to time
series : int array_size: the length of regression array
Returns: reg_slop, reg_intercept, reg_level, reg_stdev
trend_line_lsr(series, series, series, string, series, series) top_trend_line_lsr: Trend line fitting based on least square algorithm
Parameters:
series : int t: time scale value array corresponding to price
series : float p: price scale value array corresponding to time
series : int array_size: the length of regression array
string : reg_type: regression type in 'top' and 'bottom'
series : int max_iter: maximum fitting iterations
series : int min_points: the threshold of regression point numbers
Returns: reg_slop, reg_intercept, reg_level, reg_stdev, reg_point_num
simple_squares_regressionLibrary "simple_squares_regression"
simple_squares_regression: simple squares regression algorithm to find the optimal price interval for a given time period
basic_ssr(series, series, series) basic_ssr: Basic simple squares regression algorithm
Parameters:
series : float src: the regression source such as close
series : int region_forward: number of candle lines at the right end of the regression region from the current candle line
series : int region_len: the length of regression region
Returns: left_loc, right_loc, reg_val, reg_std, reg_max_offset
search_ssr(series, series, series, series) search_ssr: simple squares regression region search algorithm
Parameters:
series : float src: the regression source such as close
series : int max_forward: max number of candle lines at the right end of the regression region from the current candle line
series : int region_lower: the lower length of regression region
series : int region_upper: the upper length of regression region
Returns: left_loc, right_loc, reg_val, reg_level, reg_std_err, reg_max_offset
on_balance_volumeLibrary "on_balance_volume"
on_balance_volume: custom on balance volume
obv_diff(string, simple) obv_diff: custom on balance volume diff version
Parameters:
string : type: the moving average type of on balance volume
simple : int len: the moving average length of on balance volume
Returns: obv_diff: custom on balance volume diff value
obv_diff_norm(string, simple) obv_diff_norm: custom normalized on balance volume diff version
Parameters:
string : type: the moving average type of on balance volume
simple : int len: the moving average length of on balance volume
Returns: obv_diff: custom normalized on balance volume diff value
moving_averageLibrary "moving_average"
moving_average: moving average variants
variant(string, series, simple) variant: moving average variants
Parameters:
string : type: type in
series : float src: the source series of moving average
simple : int len: the length of moving average
Returns: float: the moving average variant value
NormalizedOscillatorsLibrary "NormalizedOscillators"
Collection of some common Oscillators. All are zero-mean and normalized to fit in the -1..1 range. Some are modified, so that the internal smoothing function could be configurable (for example, to enable Hann Windowing, that John F. Ehlers uses frequently). Some are modified for other reasons (see comments in the code), but never without a reason. This collection is neither encyclopaedic, nor reference, however I try to find the most correct implementation. Suggestions are welcome.
rsi2(upper, lower) RSI - second step
Parameters:
upper : Upwards momentum
lower : Downwards momentum
Returns: Oscillator value
Modified by Ehlers from Wilder's implementation to have a zero mean (oscillator from -1 to +1)
Originally: 100.0 - (100.0 / (1.0 + upper / lower))
Ignoring the 100 scale factor, we get: upper / (upper + lower)
Multiplying by two and subtracting 1, we get: (2 * upper) / (upper + lower) - 1 = (upper - lower) / (upper + lower)
rms(src, len) Root mean square (RMS)
Parameters:
src : Source series
len : Lookback period
Based on by John F. Ehlers implementation
ift(src) Inverse Fisher Transform
Parameters:
src : Source series
Returns: Normalized series
Based on by John F. Ehlers implementation
The input values have been multiplied by 2 (was "2*src", now "4*src") to force expansion - not compression
The inputs may be further modified, if needed
stoch(src, len) Stochastic
Parameters:
src : Source series
len : Lookback period
Returns: Oscillator series
ssstoch(src, len) Super Smooth Stochastic (part of MESA Stochastic) by John F. Ehlers
Parameters:
src : Source series
len : Lookback period
Returns: Oscillator series
Introduced in the January 2014 issue of Stocks and Commodities
This is not an implementation of MESA Stochastic, as it is based on Highpass filter not present in the function (but you can construct it)
This implementation is scaled by 0.95, so that Super Smoother does not exceed 1/-1
I do not know, if this the right way to fix this issue, but it works for now
netKendall(src, len) Noise Elimination Technology by John F. Ehlers
Parameters:
src : Source series
len : Lookback period
Returns: Oscillator series
Introduced in the December 2020 issue of Stocks and Commodities
Uses simplified Kendall correlation algorithm
Implementation by @QuantTherapy:
rsi(src, len, smooth) RSI
Parameters:
src : Source series
len : Lookback period
smooth : Internal smoothing algorithm
Returns: Oscillator series
vrsi(src, len, smooth) Volume-scaled RSI
Parameters:
src : Source series
len : Lookback period
smooth : Internal smoothing algorithm
Returns: Oscillator series
This is my own version of RSI. It scales price movements by the proportion of RMS of volume
mrsi(src, len, smooth) Momentum RSI
Parameters:
src : Source series
len : Lookback period
smooth : Internal smoothing algorithm
Returns: Oscillator series
Inspired by RocketRSI by John F. Ehlers (Stocks and Commodities, May 2018)
rrsi(src, len, smooth) Rocket RSI
Parameters:
src : Source series
len : Lookback period
smooth : Internal smoothing algorithm
Returns: Oscillator series
Inspired by RocketRSI by John F. Ehlers (Stocks and Commodities, May 2018)
Does not include Fisher Transform of the original implementation, as the output must be normalized
Does not include momentum smoothing length configuration, so always assumes half the lookback length
mfi(src, len, smooth) Money Flow Index
Parameters:
src : Source series
len : Lookback period
smooth : Internal smoothing algorithm
Returns: Oscillator series
lrsi(src, in_gamma, len) Laguerre RSI by John F. Ehlers
Parameters:
src : Source series
in_gamma : Damping factor (default is -1 to generate from len)
len : Lookback period (alternatively, if gamma is not set)
Returns: Oscillator series
The original implementation is with gamma. As it is impossible to collect gamma in my system, where the only user input is length,
an alternative calculation is included, where gamma is set by dividing len by 30. Maybe different calculation would be better?
fe(len) Choppiness Index or Fractal Energy
Parameters:
len : Lookback period
Returns: Oscillator series
The Choppiness Index (CHOP) was created by E. W. Dreiss
This indicator is sometimes called Fractal Energy
er(src, len) Efficiency ratio
Parameters:
src : Source series
len : Lookback period
Returns: Oscillator series
Based on Kaufman Adaptive Moving Average calculation
This is the correct Efficiency ratio calculation, and most other implementations are wrong:
the number of bar differences is 1 less than the length, otherwise we are adding the change outside of the measured range!
For reference, see Stocks and Commodities June 1995
dmi(len, smooth) Directional Movement Index
Parameters:
len : Lookback period
smooth : Internal smoothing algorithm
Returns: Oscillator series
Based on the original Tradingview algorithm
Modified with inspiration from John F. Ehlers DMH (but not implementing the DMH algorithm!)
Only ADX is returned
Rescaled to fit -1 to +1
Unlike most oscillators, there is no src parameter as DMI works directly with high and low values
fdmi(len, smooth) Fast Directional Movement Index
Parameters:
len : Lookback period
smooth : Internal smoothing algorithm
Returns: Oscillator series
Same as DMI, but without secondary smoothing. Can be smoothed later. Instead, +DM and -DM smoothing can be configured
doOsc(type, src, len, smooth) Execute a particular Oscillator from the list
Parameters:
type : Oscillator type to use
src : Source series
len : Lookback period
smooth : Internal smoothing algorithm
Returns: Oscillator series
Chande Momentum Oscillator (CMO) is RSI without smoothing. No idea, why some authors use different calculations
LRSI with Fractal Energy is a combo oscillator that uses Fractal Energy to tune LRSI gamma, as seen here: www.prorealcode.com
doPostfilter(type, src, len) Execute a particular Oscillator Postfilter from the list
Parameters:
type : Oscillator type to use
src : Source series
len : Lookback period
Returns: Oscillator series
CommonFiltersLibrary "CommonFilters"
Collection of some common Filters and Moving Averages. This collection is not encyclopaedic, but to declutter my other scripts. Suggestions are welcome, though. Many filters here are based on the work of John F. Ehlers
sma(src, len) Simple Moving Average
Parameters:
src : Series to use
len : Filtering length
Returns: Filtered series
ema(src, len) Exponential Moving Average
Parameters:
src : Series to use
len : Filtering length
Returns: Filtered series
rma(src, len) Wilder's Smoothing (Running Moving Average)
Parameters:
src : Series to use
len : Filtering length
Returns: Filtered series
hma(src, len) Hull Moving Average
Parameters:
src : Series to use
len : Filtering length
Returns: Filtered series
vwma(src, len) Volume Weighted Moving Average
Parameters:
src : Series to use
len : Filtering length
Returns: Filtered series
hp2(src) Simple denoiser
Parameters:
src : Series to use
Returns: Filtered series
fir2(src) Zero at 2 bar cycle period by John F. Ehlers
Parameters:
src : Series to use
Returns: Filtered series
fir3(src) Zero at 3 bar cycle period by John F. Ehlers
Parameters:
src : Series to use
Returns: Filtered series
fir23(src) Zero at 2 bar and 3 bar cycle periods by John F. Ehlers
Parameters:
src : Series to use
Returns: Filtered series
fir234(src) Zero at 2, 3 and 4 bar cycle periods by John F. Ehlers
Parameters:
src : Series to use
Returns: Filtered series
hp(src, len) High Pass Filter for cyclic components shorter than langth. Part of Roofing Filter by John F. Ehlers
Parameters:
src : Series to use
len : Filtering length
Returns: Filtered series
supers2(src, len) 2-pole Super Smoother by John F. Ehlers
Parameters:
src : Series to use
len : Filtering length
Returns: Filtered series
filt11(src, len) Filt11 is a variant of 2-pole Super Smoother with error averaging for zero-lag response by John F. Ehlers
Parameters:
src : Series to use
len : Filtering length
Returns: Filtered series
supers3(src, len) 3-pole Super Smoother by John F. Ehlers
Parameters:
src : Series to use
len : Filtering length
Returns: Filtered series
hannFIR(src, len) Hann Window Filter by John F. Ehlers
Parameters:
src : Series to use
len : Filtering length
Returns: Filtered series
hammingFIR(src, len) Hamming Window Filter (inspired by John F. Ehlers). Simplified implementation as Pedestal input parameter cannot be supplied, so I calculate it from the supplied length
Parameters:
src : Series to use
len : Filtering length
Returns: Filtered series
triangleFIR(src, len) Triangle Window Filter by John F. Ehlers
Parameters:
src : Series to use
len : Filtering length
Returns: Filtered series
doPrefilter(type, src) Execute a particular Prefilter from the list
Parameters:
type : Prefilter type to use
src : Series to use
Returns: Filtered series
doMA(type, src, len) Execute a particular MA from the list
Parameters:
type : MA type to use
src : Series to use
len : Filtering length
Returns: Filtered series