taLibrary "ta"
█ OVERVIEW
This library holds technical analysis functions calculating values for which no Pine built-in exists.
Look first. Then leap.
█ FUNCTIONS
cagr(entryTime, entryPrice, exitTime, exitPrice)
It calculates the "Compound Annual Growth Rate" between two points in time. The CAGR is a notional, annualized growth rate that assumes all profits are reinvested. It only takes into account the prices of the two end points — not drawdowns, so it does not calculate risk. It can be used as a yardstick to compare the performance of two instruments. Because it annualizes values, the function requires a minimum of one day between the two end points (annualizing returns over smaller periods of times doesn't produce very meaningful figures).
Parameters:
entryTime : The starting timestamp.
entryPrice : The starting point's price.
exitTime : The ending timestamp.
exitPrice : The ending point's price.
Returns: CAGR in % (50 is 50%). Returns `na` if there is not >=1D between `entryTime` and `exitTime`, or until the two time points have not been reached by the script.
█ v2, Mar. 8, 2022
Added functions `allTimeHigh()` and `allTimeLow()` to find the highest or lowest value of a source from the first historical bar to the current bar. These functions will not look ahead; they will only return new highs/lows on the bar where they occur.
allTimeHigh(src)
Tracks the highest value of `src` from the first historical bar to the current bar.
Parameters:
src : (series int/float) Series to track. Optional. The default is `high`.
Returns: (float) The highest value tracked.
allTimeLow(src)
Tracks the lowest value of `src` from the first historical bar to the current bar.
Parameters:
src : (series int/float) Series to track. Optional. The default is `low`.
Returns: (float) The lowest value tracked.
█ v3, Sept. 27, 2022
This version includes the following new functions:
aroon(length)
Calculates the values of the Aroon indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
Returns: ( [float, float ]) A tuple of the Aroon-Up and Aroon-Down values.
coppock(source, longLength, shortLength, smoothLength)
Calculates the value of the Coppock Curve indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
longLength (simple int) : (simple int) Number of bars for the fast ROC value (length).
shortLength (simple int) : (simple int) Number of bars for the slow ROC value (length).
smoothLength (simple int) : (simple int) Number of bars for the weigted moving average value (length).
Returns: (float) The oscillator value.
dema(source, length)
Calculates the value of the Double Exponential Moving Average (DEMA).
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The double exponentially weighted moving average of the `source`.
dema2(src, length)
An alternate Double Exponential Moving Average (Dema) function to `dema()`, which allows a "series float" length argument.
Parameters:
src : (series int/float) Series of values to process.
length : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The double exponentially weighted moving average of the `src`.
dm(length)
Calculates the value of the "Demarker" indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
Returns: (float) The oscillator value.
donchian(length)
Calculates the values of a Donchian Channel using `high` and `low` over a given `length`.
Parameters:
length (int) : (series int) Number of bars (length).
Returns: ( [float, float, float ]) A tuple containing the channel high, low, and median, respectively.
ema2(src, length)
An alternate ema function to the `ta.ema()` built-in, which allows a "series float" length argument.
Parameters:
src : (series int/float) Series of values to process.
length : (series int/float) Number of bars (length).
Returns: (float) The exponentially weighted moving average of the `src`.
eom(length, div)
Calculates the value of the Ease of Movement indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
div (simple int) : (simple int) Divisor used for normalzing values. Optional. The default is 10000.
Returns: (float) The oscillator value.
frama(source, length)
The Fractal Adaptive Moving Average (FRAMA), developed by John Ehlers, is an adaptive moving average that dynamically adjusts its lookback period based on fractal geometry.
Parameters:
source (float) : (series int/float) Series of values to process.
length (int) : (series int) Number of bars (length).
Returns: (float) The fractal adaptive moving average of the `source`.
ft(source, length)
Calculates the value of the Fisher Transform indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Number of bars (length).
Returns: (float) The oscillator value.
ht(source)
Calculates the value of the Hilbert Transform indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
Returns: (float) The oscillator value.
ichimoku(conLength, baseLength, senkouLength)
Calculates values of the Ichimoku Cloud indicator, including tenkan, kijun, senkouSpan1, senkouSpan2, and chikou. NOTE: offsets forward or backward can be done using the `offset` argument in `plot()`.
Parameters:
conLength (int) : (series int) Length for the Conversion Line (Tenkan). The default is 9 periods, which returns the mid-point of the 9 period Donchian Channel.
baseLength (int) : (series int) Length for the Base Line (Kijun-sen). The default is 26 periods, which returns the mid-point of the 26 period Donchian Channel.
senkouLength (int) : (series int) Length for the Senkou Span 2 (Leading Span B). The default is 52 periods, which returns the mid-point of the 52 period Donchian Channel.
Returns: ( [float, float, float, float, float ]) A tuple of the Tenkan, Kijun, Senkou Span 1, Senkou Span 2, and Chikou Span values. NOTE: by default, the senkouSpan1 and senkouSpan2 should be plotted 26 periods in the future, and the Chikou Span plotted 26 days in the past.
ift(source)
Calculates the value of the Inverse Fisher Transform indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
Returns: (float) The oscillator value.
kvo(fastLen, slowLen, trigLen)
Calculates the values of the Klinger Volume Oscillator.
Parameters:
fastLen (simple int) : (simple int) Length for the fast moving average smoothing parameter calculation.
slowLen (simple int) : (simple int) Length for the slow moving average smoothing parameter calculation.
trigLen (simple int) : (simple int) Length for the trigger moving average smoothing parameter calculation.
Returns: ( [float, float ]) A tuple of the KVO value, and the trigger value.
pzo(length)
Calculates the value of the Price Zone Oscillator.
Parameters:
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
rms(source, length)
Calculates the Root Mean Square of the `source` over the `length`.
Parameters:
source (float) : (series int/float) Series of values to process.
length (int) : (series int) Number of bars (length).
Returns: (float) The RMS value.
rwi(length)
Calculates the values of the Random Walk Index.
Parameters:
length (simple int) : (simple int) Lookback and ATR smoothing parameter length.
Returns: ( [float, float ]) A tuple of the `rwiHigh` and `rwiLow` values.
stc(source, fast, slow, cycle, d1, d2)
Calculates the value of the Schaff Trend Cycle indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
fast (simple int) : (simple int) Length for the MACD fast smoothing parameter calculation.
slow (simple int) : (simple int) Length for the MACD slow smoothing parameter calculation.
cycle (simple int) : (simple int) Number of bars for the Stochastic values (length).
d1 (simple int) : (simple int) Length for the initial %D smoothing parameter calculation.
d2 (simple int) : (simple int) Length for the final %D smoothing parameter calculation.
Returns: (float) The oscillator value.
stochFull(periodK, smoothK, periodD)
Calculates the %K and %D values of the Full Stochastic indicator.
Parameters:
periodK (simple int) : (simple int) Number of bars for Stochastic calculation. (length).
smoothK (simple int) : (simple int) Number of bars for smoothing of the %K value (length).
periodD (simple int) : (simple int) Number of bars for smoothing of the %D value (length).
Returns: ( [float, float ]) A tuple of the slow %K and the %D moving average values.
stochRsi(lengthRsi, periodK, smoothK, periodD, source)
Calculates the %K and %D values of the Stochastic RSI indicator.
Parameters:
lengthRsi (simple int) : (simple int) Length for the RSI smoothing parameter calculation.
periodK (simple int) : (simple int) Number of bars for Stochastic calculation. (length).
smoothK (simple int) : (simple int) Number of bars for smoothing of the %K value (length).
periodD (simple int) : (simple int) Number of bars for smoothing of the %D value (length).
source (float) : (series int/float) Series of values to process. Optional. The default is `close`.
Returns: ( [float, float ]) A tuple of the slow %K and the %D moving average values.
supertrend(factor, atrLength, wicks)
Calculates the values of the SuperTrend indicator with the ability to take candle wicks into account, rather than only the closing price.
Parameters:
factor (float) : (series int/float) Multiplier for the ATR value.
atrLength (simple int) : (simple int) Length for the ATR smoothing parameter calculation.
wicks (simple bool) : (simple bool) Condition to determine whether to take candle wicks into account when reversing trend, or to use the close price. Optional. Default is false.
Returns: ( [float, int ]) A tuple of the superTrend value and trend direction.
szo(source, length)
Calculates the value of the Sentiment Zone Oscillator.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
t3(source, length, vf)
Calculates the value of the Tilson Moving Average (T3).
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
vf (simple float) : (simple float) Volume factor. Affects the responsiveness.
Returns: (float) The Tilson moving average of the `source`.
t3Alt(source, length, vf)
An alternate Tilson Moving Average (T3) function to `t3()`, which allows a "series float" `length` argument.
Parameters:
source (float) : (series int/float) Series of values to process.
length (float) : (series int/float) Length for the smoothing parameter calculation.
vf (simple float) : (simple float) Volume factor. Affects the responsiveness.
Returns: (float) The Tilson moving average of the `source`.
tema(source, length)
Calculates the value of the Triple Exponential Moving Average (TEMA).
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The triple exponentially weighted moving average of the `source`.
tema2(source, length)
An alternate Triple Exponential Moving Average (TEMA) function to `tema()`, which allows a "series float" `length` argument.
Parameters:
source (float) : (series int/float) Series of values to process.
length (float) : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The triple exponentially weighted moving average of the `source`.
trima(source, length)
Calculates the value of the Triangular Moving Average (TRIMA).
Parameters:
source (float) : (series int/float) Series of values to process.
length (int) : (series int) Number of bars (length).
Returns: (float) The triangular moving average of the `source`.
trima2(src, length)
An alternate Triangular Moving Average (TRIMA) function to `trima()`, which allows a "series int" length argument.
Parameters:
src : (series int/float) Series of values to process.
length : (series int) Number of bars (length).
Returns: (float) The triangular moving average of the `src`.
trix(source, length, signalLength, exponential)
Calculates the values of the TRIX indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
signalLength (simple int) : (simple int) Length for smoothing the signal line.
exponential (simple bool) : (simple bool) Condition to determine whether exponential or simple smoothing is used. Optional. The default is `true` (exponential smoothing).
Returns: ( [float, float, float ]) A tuple of the TRIX value, the signal value, and the histogram.
uo(fastLen, midLen, slowLen)
Calculates the value of the Ultimate Oscillator.
Parameters:
fastLen (simple int) : (series int) Number of bars for the fast smoothing average (length).
midLen (simple int) : (series int) Number of bars for the middle smoothing average (length).
slowLen (simple int) : (series int) Number of bars for the slow smoothing average (length).
Returns: (float) The oscillator value.
vhf(source, length)
Calculates the value of the Vertical Horizontal Filter.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Number of bars (length).
Returns: (float) The oscillator value.
vi(length)
Calculates the values of the Vortex Indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
Returns: ( [float, float ]) A tuple of the viPlus and viMinus values.
vzo(length)
Calculates the value of the Volume Zone Oscillator.
Parameters:
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
williamsFractal(period)
Detects Williams Fractals.
Parameters:
period (int) : (series int) Number of bars (length).
Returns: ( [bool, bool ]) A tuple of an up fractal and down fractal. Variables are true when detected.
wpo(length)
Calculates the value of the Wave Period Oscillator.
Parameters:
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
█ v7, Nov. 2, 2023
This version includes the following new and updated functions:
atr2(length)
An alternate ATR function to the `ta.atr()` built-in, which allows a "series float" `length` argument.
Parameters:
length (float) : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The ATR value.
changePercent(newValue, oldValue)
Calculates the percentage difference between two distinct values.
Parameters:
newValue (float) : (series int/float) The current value.
oldValue (float) : (series int/float) The previous value.
Returns: (float) The percentage change from the `oldValue` to the `newValue`.
donchian(length)
Calculates the values of a Donchian Channel using `high` and `low` over a given `length`.
Parameters:
length (int) : (series int) Number of bars (length).
Returns: ( [float, float, float ]) A tuple containing the channel high, low, and median, respectively.
highestSince(cond, source)
Tracks the highest value of a series since the last occurrence of a condition.
Parameters:
cond (bool) : (series bool) A condition which, when `true`, resets the tracking of the highest `source`.
source (float) : (series int/float) Series of values to process. Optional. The default is `high`.
Returns: (float) The highest `source` value since the last time the `cond` was `true`.
lowestSince(cond, source)
Tracks the lowest value of a series since the last occurrence of a condition.
Parameters:
cond (bool) : (series bool) A condition which, when `true`, resets the tracking of the lowest `source`.
source (float) : (series int/float) Series of values to process. Optional. The default is `low`.
Returns: (float) The lowest `source` value since the last time the `cond` was `true`.
relativeVolume(length, anchorTimeframe, isCumulative, adjustRealtime)
Calculates the volume since the last change in the time value from the `anchorTimeframe`, the historical average volume using bars from past periods that have the same relative time offset as the current bar from the start of its period, and the ratio of these volumes. The volume values are cumulative by default, but can be adjusted to non-accumulated with the `isCumulative` parameter.
Parameters:
length (simple int) : (simple int) The number of periods to use for the historical average calculation.
anchorTimeframe (simple string) : (simple string) The anchor timeframe used in the calculation. Optional. Default is "D".
isCumulative (simple bool) : (simple bool) If `true`, the volume values will be accumulated since the start of the last `anchorTimeframe`. If `false`, values will be used without accumulation. Optional. The default is `true`.
adjustRealtime (simple bool) : (simple bool) If `true`, estimates the cumulative value on unclosed bars based on the data since the last `anchor` condition. Optional. The default is `false`.
Returns: ( [float, float, float ]) A tuple of three float values. The first element is the current volume. The second is the average of volumes at equivalent time offsets from past anchors over the specified number of periods. The third is the ratio of the current volume to the historical average volume.
rma2(source, length)
An alternate RMA function to the `ta.rma()` built-in, which allows a "series float" `length` argument.
Parameters:
source (float) : (series int/float) Series of values to process.
length (float) : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The rolling moving average of the `source`.
supertrend2(factor, atrLength, wicks)
An alternate SuperTrend function to `supertrend()`, which allows a "series float" `atrLength` argument.
Parameters:
factor (float) : (series int/float) Multiplier for the ATR value.
atrLength (float) : (series int/float) Length for the ATR smoothing parameter calculation.
wicks (simple bool) : (simple bool) Condition to determine whether to take candle wicks into account when reversing trend, or to use the close price. Optional. Default is `false`.
Returns: ( [float, int ]) A tuple of the superTrend value and trend direction.
vStop(source, atrLength, atrFactor)
Calculates an ATR-based stop value that trails behind the `source`. Can serve as a possible stop-loss guide and trend identifier.
Parameters:
source (float) : (series int/float) Series of values that the stop trails behind.
atrLength (simple int) : (simple int) Length for the ATR smoothing parameter calculation.
atrFactor (float) : (series int/float) The multiplier of the ATR value. Affects the maximum distance between the stop and the `source` value. A value of 1 means the maximum distance is 100% of the ATR value. Optional. The default is 1.
Returns: ( [float, bool ]) A tuple of the volatility stop value and the trend direction as a "bool".
vStop2(source, atrLength, atrFactor)
An alternate Volatility Stop function to `vStop()`, which allows a "series float" `atrLength` argument.
Parameters:
source (float) : (series int/float) Series of values that the stop trails behind.
atrLength (float) : (series int/float) Length for the ATR smoothing parameter calculation.
atrFactor (float) : (series int/float) The multiplier of the ATR value. Affects the maximum distance between the stop and the `source` value. A value of 1 means the maximum distance is 100% of the ATR value. Optional. The default is 1.
Returns: ( [float, bool ]) A tuple of the volatility stop value and the trend direction as a "bool".
Removed Functions:
allTimeHigh(src)
Tracks the highest value of `src` from the first historical bar to the current bar.
allTimeLow(src)
Tracks the lowest value of `src` from the first historical bar to the current bar.
trima2(src, length)
An alternate Triangular Moving Average (TRIMA) function to `trima()`, which allows a
"series int" length argument.
Indicators and strategies
ArrayOperationsIntLibrary "ArrayOperationsInt"
Array Basic Operations for Integers
add(sample_a, sample_b) Adds sample_b to sample_a and returns a new array.
Parameters:
sample_a : values to be added to.
sample_b : values to add.
Returns: int array with added results.
subtract(sample_a, sample_b) subtracts sample_b from sample_a and returns a new array.
Parameters:
sample_a : values to be subtracted from.
sample_b : values to subtract.
Returns: int array with subtracted results.
multiply(sample_a, sample_b) multiply sample_a with sample_b and returns a new array.
Parameters:
sample_a : values to multiply.
sample_b : values to multiply with.
Returns: int array with multiplied results.
divide(sample_a, sample_b) divide sample_a with sample_b and returns a new array.
Parameters:
sample_a : values to divide.
sample_b : values to divide with.
Returns: int array with divided results.
power(sample_a, sample_b) rise sample_a to the power of sample_b and returns a new array.
Parameters:
sample_a : base values to raise.
sample_b : values of exponents.
Returns: int array with raised results.
remainder(sample_a, sample_b) integer remainder of sample_a under the dividend sample_b and returns a new array.
Parameters:
sample_a : values of quotients.
sample_b : values of dividends.
Returns: int array with remainder results.
ArrayOperationsFloatLibrary "ArrayOperationsFloat"
Array Basic Operations for Integers
add(sample_a, sample_b) Adds sample_b to sample_a and returns a new array.
Parameters:
sample_a : values to be added to.
sample_b : values to add.
Returns: float array with added results.
subtract(sample_a, sample_b) subtracts sample_b from sample_a and returns a new array.
Parameters:
sample_a : values to be subtracted from.
sample_b : values to subtract.
Returns: float array with subtracted results.
multiply(sample_a, sample_b) multiply sample_a with sample_b and returns a new array.
Parameters:
sample_a : values to multiply.
sample_b : values to multiply with.
Returns: float array with multiplied results.
divide(sample_a, sample_b) divide sample_a with sample_b and returns a new array.
Parameters:
sample_a : values to divide.
sample_b : values to divide with.
Returns: float array with divided results.
power(sample_a, sample_b) rise sample_a to the power of sample_b and returns a new array.
Parameters:
sample_a : base values to raise.
sample_b : values of exponents.
Returns: float array with raised results.
remainder(sample_a, sample_b) float remainder of sample_a under the dividend sample_b and returns a new array.
Parameters:
sample_a : values of quotients.
sample_b : values of dividends.
Returns: float array with remainder results.
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.
BinaryDecimalConversionLibrary "BinaryDecimalConversion"
Converts decimal to and from binary.
to_binary(number) convert integer to binary string
Parameters:
number : int, value to convert.
Returns: string
to_decimal(binary) Converts a binary in a string to decimal.
Parameters:
binary : string, binary number in a string.
Returns: int
StringEvaluationLibrary "StringEvaluation"
Methods to handle evaluation of strings.
is_comma(char) Check if char is a comma ".".
Parameters:
char : string, 1 character string.
Returns: bool.
is_op(char) Check if char is a operator.
Parameters:
char : string, 1 character string.
Returns: bool.
number(char) convert a single char string into valid number.
Parameters:
char : string, 1 character string.
Returns: float.
operator(op, left, right) operation between left and right values.
Parameters:
op : string, operator string character.
left : float, left value of operation.
right : float, right value of operation.
operator_precedence(op) level of precedence of operator.
Parameters:
op : string, operator 1 char string.
Returns: int.
cleanup(_str) Evaluate a string to clean up and retrieve only used chars
Parameters:
_str : string, arithmetic operations in a string.
Returns: string array, evaluated array.
generate_rpn(tokens) uses Shunting-Yard algorithm to generate a RPN (Reverse Polish notation)
array of strings from a array of strings containing arithmetic notation.
ex:.. ' ' --> ' '
Parameters:
tokens : string array, array with arithmetic notation.
Returns:
parse_rpn() evaluate a RPN (Reverse Polish notation) array of strings.
ex:.. 3 4 2 * 1 5 - 2 3 ^ ^ / +
| @param tokens string array, RPN ordered tokens, ex( ).
| @returns float, solution.
eval() evaluate a string with references to a array of arguments.
| @param tokens string, arithmetic operations with references to indices in arguments, ex:"0+1*0+2*2+3" arguments
| @param arguments float array, arguments.
| @returns float, solution.
SignificantFiguresLibrary "SignificantFigures"
sigFig(float _float, int _figures)
@description Takes a floating-point number - one that can, but doesn't have to, include a decimal point - and converts it to a floating-point number with only a certain number of digits left. For example, say you want to display a variable from your script to the user and it comes out to something like 45.366666666666666666666667 or whatever. That looks awful when you, for example, print it in a label. Now you could round it up to the nearest integer easily using a built-in function, or even to a certain number of decimal places using a reasonably simple custom function. But that's a bit arbitrary. Suppose you don't know what asset the script will be used on, and so you can't predict what the price is, and what the value will turn out to be. It could be 0.00045366666666666666666666667 instead. Now if you round it up to 3 decimal places it comes out as 0.000, which is useless. My function will round that number to 0.0004536 instead, if told to do it to 4 significant digits.
I think this is more friendly.
@function Converts float with arbitrary number of digits to one with a specified number of significant figures.
@param float _float is the floating-point number to manipulate.
@param int _figures is the number of significant figures you want.
@returns Returns a float with the specified number of significant figures
MathSpecialFunctionsGammaLibrary "MathSpecialFunctionsGamma"
Gamma Functions.
GammaQ(index) Enumeration of the polynomial coefficients for the "GammaLn" approximation.
Parameters:
index : int, 0 => index => 10, index of coeficient.
Returns: float
GammaLn(z) Computes the logarithm of the Gamma function.
Parameters:
z : The argument of the gamma function.
Returns: The logarithm of the gamma function.
Gamma(z) Computes the Gamma function.
Parameters:
z : The argument of the gamma function.
Returns: float, The logarithm of the gamma function.
GammaLowerRegularized(a, x)
Parameters:
a : float, The argument for the gamma function.
x : float, The upper integral limit.
Returns: float, The lower incomplete gamma function.
GammaUpperRegularized(a, x) Returns the upper incomplete regularized gamma function
Parameters:
a : float, The argument for the gamma function.
x : float, The lower integral limit.
Returns: float, The upper incomplete regularized gamma function.
GammaUpperIncomplete(a, x) Returns the upper incomplete gamma function.
Parameters:
a : float, The argument for the gamma function.
x : float, The lower integral limit.
Returns: float, The upper incomplete gamma function.
GammaLowerIncomplete(a, x)
Parameters:
a : float, The argument for the gamma function.
x : float, The upper integral limit.
Returns: float, The lower incomplete gamma function.
ProbabilityLibrary "Probability"
erf(value) Complementary error function
Parameters:
value : float, value to test.
Returns: float
ierf_mcgiles(value) Computes the inverse error function using the Mc Giles method, sacrifices accuracy for speed.
Parameters:
value : float, -1.0 >= _value >= 1.0 range, value to test.
Returns: float
ierf_double(value) computes the inverse error function using the Newton method with double refinement.
Parameters:
value : float, -1. > _value > 1. range, _value to test.
Returns: float
ierf(value) computes the inverse error function using the Newton method.
Parameters:
value : float, -1. > _value > 1. range, _value to test.
Returns: float
complement(probability) probability that the event will not occur.
Parameters:
probability : float, 0 >=_p >= 1, probability of event.
Returns: float
entropy_gini_impurity_single(probability) Gini Inbalance or Gini index for a given probability.
Parameters:
probability : float, 0>=x>=1, probability of event.
Returns: float
entropy_gini_impurity(events) Gini Inbalance or Gini index for a series of events.
Parameters:
events : float , 0>=x>=1, array with event probability's.
Returns: float
entropy_shannon_single(probability) Entropy information value of the probability of a single event.
Parameters:
probability : float, 0>=x>=1, probability value.
Returns: float, value as bits of information.
entropy_shannon(events) Entropy information value of a distribution of events.
Parameters:
events : float , 0>=x>=1, array with probability's.
Returns: float
inequality_chebyshev(n_stdeviations) Calculates Chebyshev Inequality.
Parameters:
n_stdeviations : float, positive over or equal to 1.0
Returns: float
inequality_chebyshev_distribution(mean, std) Calculates Chebyshev Inequality.
Parameters:
mean : float, mean of a distribution
std : float, standard deviation of a distribution
Returns: float
inequality_chebyshev_sample(data_sample) Calculates Chebyshev Inequality for a array of values.
Parameters:
data_sample : float , array of numbers.
Returns: float
intersection_of_independent_events(events) Probability that all arguments will happen when neither outcome
is affected by the other (accepts 1 or more arguments)
Parameters:
events : float , 0 >= _p >= 1, list of event probabilities.
Returns: float
union_of_independent_events(events) Probability that either one of the arguments will happen when neither outcome
is affected by the other (accepts 1 or more arguments)
Parameters:
events : float , 0 >= _p >= 1, list of event probabilities.
Returns: float
mass_function(sample, n_bins) Probabilities for each bin in the range of sample.
Parameters:
sample : float , samples to pool probabilities.
n_bins : int, number of bins to split the range
@return float
cumulative_distribution_function(mean, stdev, value) Use the CDF to determine the probability that a random observation
that is taken from the population will be less than or equal to a certain value.
Or returns the area of probability for a known value in a normal distribution.
Parameters:
mean : float, samples to pool probabilities.
stdev : float, number of bins to split the range
value : float, limit at which to stop.
Returns: float
transition_matrix(distribution) Transition matrix for the suplied distribution.
Parameters:
distribution : float , array with probability distribution. ex:.
Returns: float
diffusion_matrix(transition_matrix, dimension, target_step) Probability of reaching target_state at target_step after starting from start_state
Parameters:
transition_matrix : float , "pseudo2d" probability transition matrix.
dimension : int, size of the matrix dimension.
target_step : number of steps to find probability.
Returns: float
state_at_time(transition_matrix, dimension, start_state, target_state, target_step) Probability of reaching target_state at target_step after starting from start_state
Parameters:
transition_matrix : float , "pseudo2d" probability transition matrix.
dimension : int, size of the matrix dimension.
start_state : state at which to start.
target_state : state to find probability.
target_step : number of steps to find probability.
MathStatisticsKernelDensityEstimationLibrary "MathStatisticsKernelDensityEstimation"
(KDE) Method for Kernel Density Estimation
kde(observations, kernel, bandwidth, nsteps)
Parameters:
observations : float array, sample data.
kernel : string, the kernel to use, default='gaussian', options='uniform', 'triangle', 'epanechnikov', 'quartic', 'triweight', 'gaussian', 'cosine', 'logistic', 'sigmoid'.
bandwidth : float, bandwidth to use in kernel, default=0.5, range=(0, +inf), less will smooth the data.
nsteps : int, number of steps in range of distribution, default=20, this value is connected to how many line objects you can display per script.
Returns: tuple with signature: (float array, float array)
draw_horizontal(distribution_x, distribution_y, distribution_lines, graph_lines, graph_labels) Draw a horizontal distribution at current location on chart.
Parameters:
distribution_x : float array, distribution points x value.
distribution_y : float array, distribution points y value.
distribution_lines : line array, array to append the distribution curve lines.
graph_lines : line array, array to append the graph lines.
graph_labels : label array, array to append the graph labels.
Returns: void, updates arrays: distribution_lines, graph_lines, graph_labels.
draw_vertical(distribution_x, distribution_y, distribution_lines, graph_lines, graph_labels) Draw a vertical distribution at current location on chart.
Parameters:
distribution_x : float array, distribution points x value.
distribution_y : float array, distribution points y value.
distribution_lines : line array, array to append the distribution curve lines.
graph_lines : line array, array to append the graph lines.
graph_labels : label array, array to append the graph labels.
Returns: void, updates arrays: distribution_lines, graph_lines, graph_labels.
style_distribution(lines, horizontal, to_histogram, line_color, line_style, linewidth) Style the distribution lines.
Parameters:
lines : line array, distribution lines to style.
horizontal : bool, default=true, if the display is horizontal(true) or vertical(false).
to_histogram : bool, default=false, if graph style should be switched to histogram.
line_color : color, default=na, if defined will change the color of the lines.
line_style : string, defaul=na, if defined will change the line style, options=('na', line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_right, line.style_arrow_left, line.style_arrow_both)
linewidth : int, default=na, if defined will change the line width.
Returns: void.
style_graph(lines, lines, horizontal, line_color, line_style, linewidth) Style the graph lines and labels
Parameters:
lines : line array, graph lines to style.
lines : labels array, graph labels to style.
horizontal : bool, default=true, if the display is horizontal(true) or vertical(false).
line_color : color, default=na, if defined will change the color of the lines.
line_style : string, defaul=na, if defined will change the line style, options=('na', line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_right, line.style_arrow_left, line.style_arrow_both)
linewidth : int, default=na, if defined will change the line width.
Returns: void.
MathStatisticsKernelFunctionsLibrary "MathStatisticsKernelFunctions"
TODO: add library description here
uniform(distance, bandwidth) Uniform kernel.
Parameters:
distance : float, distance to kernel origin.
bandwidth : float, default=1.0, bandwidth limiter to weight the kernel.
Returns: float.
triangular(distance, bandwidth) Triangular kernel.
Parameters:
distance : float, distance to kernel origin.
bandwidth : float, default=1.0, bandwidth limiter to weight the kernel.
Returns: float.
epanechnikov(distance, bandwidth) Epanechnikov kernel.
Parameters:
distance : float, distance to kernel origin.
bandwidth : float, default=1.0, bandwidth limiter to weight the kernel.
Returns: float.
quartic(distance, bandwidth) Quartic kernel.
Parameters:
distance : float, distance to kernel origin.
bandwidth : float, default=1.0, bandwidth limiter to weight the kernel.
Returns: float.
triweight(distance, bandwidth) Triweight kernel.
Parameters:
distance : float, distance to kernel origin.
bandwidth : float, default=1.0, bandwidth limiter to weight the kernel.
Returns: float.
tricubic(distance, bandwidth) Tricubic kernel.
Parameters:
distance : float, distance to kernel origin.
bandwidth : float, default=1.0, bandwidth limiter to weight the kernel.
Returns: float.
gaussian(distance, bandwidth) Gaussian kernel.
Parameters:
distance : float, distance to kernel origin.
bandwidth : float, default=1.0, bandwidth limiter to weight the kernel.
Returns: float.
cosine(distance, bandwidth) Cosine kernel.
Parameters:
distance : float, distance to kernel origin.
bandwidth : float, default=1.0, bandwidth limiter to weight the kernel.
Returns: float.
logistic(distance, bandwidth) logistic kernel.
Parameters:
distance : float, distance to kernel origin.
bandwidth : float, default=1.0, bandwidth limiter to weight the kernel.
Returns: float.
sigmoid(distance, bandwidth) Sigmoid kernel.
Parameters:
distance : float, distance to kernel origin.
bandwidth : float, default=1.0, bandwidth limiter to weight the kernel.
Returns: float.
select(kernel, distance, bandwidth) Kernel selection method.
Parameters:
kernel : string, kernel to select. (options="uniform", "triangle", "epanechnikov", "quartic", "triweight", "tricubic", "gaussian", "cosine", "logistic", "sigmoid")
distance : float, distance to kernel origin.
bandwidth : float, default=1.0, bandwidth limiter to weight the kernel.
Returns: float.
MathTransformsHartleyLibrary "MathTransformsHartley"
implementation of the Fast Discrete Hartley Transform(DHT).
naive(samples) Generic naive transform for the (DHT).
Parameters:
samples : float array, 1d data.
Returns: float array.
fdht(samples) Fast Discrete Hartley Transform (DHT).
Parameters:
samples : float array, data samples.
Returns: float array.
idht(samples, asymmetric_scaling) Inverse Discrete Hartley Transform (DHT).
Parameters:
samples : float array, data samples.
asymmetric_scaling : bool, default=true, scaling option.
Returns: float array.
MathSpecialFunctionsTestFunctionsLibrary "MathSpecialFunctionsTestFunctions"
Methods for test functions.
rosenbrock(input_x, input_y) Valley-shaped Rosenbrock function for 2 dimensions: (x,y) -> (1-x)^2 + 100*(y-x^2)^2.
Parameters:
input_x : float, common range within (-5.0, 10.0) or (-2.048, 2.048).
input_y : float, common range within (-5.0, 10.0) or (-2.048, 2.048).
Returns: float
rosenbrock_mdim(samples) Valley-shaped Rosenbrock function for 2 or more dimensions.
Parameters:
samples : float array, common range within (-5.0, 10.0) or (-2.048, 2.048).
Returns: float
himmelblau(input_x, input_y) Himmelblau, a multi-modal function: (x,y) -> (x^2+y-11)^2 + (x+y^2-7)^2
Parameters:
input_x : float, common range within (-6.0, 6.0 ).
input_y : float, common range within (-6.0, 6.0 ).
Returns: float
rastrigin(samples) Rastrigin, a highly multi-modal function with many local minima.
Parameters:
samples : float array, common range within (-5.12, 5.12 ).
Returns: float
drop_wave(input_x, input_y) Drop-Wave, a multi-modal and highly complex function with many local minima.
Parameters:
input_x : float, common range within (-5.12, 5.12 ).
input_y : float, common range within (-5.12, 5.12 ).
Returns: float
ackley(input_x) Ackley, a function with many local minima. It is nearly flat in outer regions but has a large hole at the center.
Parameters:
input_x : float array, common range within (-32.768, 32.768 ).
Returns: float
bohachevsky1(input_x, input_y) Bowl-shaped first Bohachevsky function.
Parameters:
input_x : float, common range within (-100.0, 100.0 ).
input_y : float, common range within (-100.0, 100.0 ).
Returns: float
matyas(input_x, input_y) Plate-shaped Matyas function.
Parameters:
input_x : float, common range within (-10.0, 10.0 ).
input_y : float, common range within (-10.0, 10.0 ).
Returns: float
six_hump_camel(input_x, input_y) Valley-shaped six-hump camel back function.
Parameters:
input_x : float, common range within (-3.0, 3.0 ).
input_y : float, common range within (-2.0, 2.0 ).
Returns: float
MathGeometryCurvesChaikinLibrary "MathGeometryCurvesChaikin"
Implements the chaikin algorithm to create a curved path, from assigned points.
chaikin(points_x, points_y, closed) Chaikin algorithm method, uses provided points to generate a smoothed path.
Parameters:
points_x : float array, the x value of points.
points_y : float array, the y value of points.
closed : bool, default=false, is the path closed or not.
Returns: tuple with 2 float arrays.
smooth(points_x, points_y, iterations, closed) Iterate the chaikin algorithm, to smooth a sample of points into a curve path.
Parameters:
points_x : float array, the x value of points.
points_y : float array, the y value of points.
iterations : int, number of iterations to apply the smoothing.
closed : bool, default=false, is the path closed or not.
Returns: array of lines.
draw(path_x, path_y, closed) Draw the path.
Parameters:
path_x : float array, the x value of the path.
path_y : float array, the y value of the path.
closed : bool, default=false, is the path closed or not.
Returns: array of lines.
Double_Triple_EMALibrary "Double_Triple_EMA"
Provides the functions to calculate Double and Triple Exponentional Moving Averages (DEMA & TEMA).
dema(_source, _length) Calculates Double Exponentional Moving Averages (DEMA)
Parameters:
_source : -> Open, Close, High, Low, etc ('close' is used if no argument is supplied)
_length : -> DEMA length
Returns: Double Exponential Moving Average (DEMA) of an input source at the specified input length
tema(_source, _length) Calculates Triple Exponentional Moving Averages (TEMA)
Parameters:
_source : -> Open, Close, High, Low, etc ('close' is used if no argument is supplied)
_length : -> TEMA length
Returns: Triple Exponential Moving Average (TEMA) of an input source at the specified input length
AutoColorLibrary "AutoColor"
Function provides rgb color based on deviation of highest and lowest value for the period from current value
fColor(src1, len1) Calculates rgb color based on deviation of highest and lowest value for the period from current value
Parameters:
src1 : Series to use (`close` is used if no argument is supplied).
len1 : Length for highest and lowest series (`10` is used if no argument is supplied).
Returns: color for series
Library_All_In_OneLibrary "Library_All_In_One"
fnRSI()
fnTSI()
Discription:
Contains several functions of Pinescript all in one Library. This reduce your coding.
How to use:
import Wilson-IV/Library_All_In_One/1 as _lib
Examples of plotting the RSI and TSI:
plot(_lib.fnRSI(close, 14))
plot(_lib.fnTSI(close, 25, 14))
Markets:
It can be used to all markets.
NOTE:
It will expands with more function during time.
multiMaLibrary "multiMa"
Provides function that returns the type of moving average requested.
ma(type, src, len) Returns the moving average requested.
Parameters:
type : The type of moving average (choose one of "EMA", "SMA", "DEMA", "TEMA", "WMA", "VWMA", "SMMA", "HMA")
src : The source
len : The length
Returns: The moving average requested or `na`
MathSpecialFunctionsLogisticLibrary "MathSpecialFunctionsLogistic"
Methods for logistic equation.
logistic(probability) Computes the logistic function.
Parameters:
probability : float, value to compute the logistic function.
Returns: float
logit(probability) Computes the logit function, the inverse of the sigmoid logistic function.
Parameters:
probability : float, value to compute the logit function.
Returns: float
MathTrigonometryLibrary "MathTrigonometry"
Trigonometric methods.
sinc(value) Normalized sinc function.
Parameters:
value : float, value.
Returns: float.
cot(value) Cotangent of value.
Parameters:
value : float, value.
Returns: float.
csc(value) Cosecant of value.
Parameters:
value : float, value.
Returns: float.
sec(value) Secant of value.
Parameters:
value : float, value.
Returns: float.
acot(value) Arc cotangent of value.
Parameters:
value : float, adjacent value.
Returns: float.
asec(value) Arc secant of value.
Parameters:
value : float, hypotenuse value.
Returns: float.
acsc(value) Arc cosecant of value.
Parameters:
value : float, hipotenuse value.
Returns: float.
sinh(angle) Hyperbolic sine of angle.
Parameters:
angle : float, value.
Returns: float.
cosh(angle) Hyperbolic cosine of angle.
Parameters:
angle : float, value.
Returns: float.
tanh(angle) Hyperbolic tangent of angle.
Parameters:
angle : float, value.
Returns: float.
coth(angle) Hyperbolic cotangent of angle.
Parameters:
angle : float, value.
Returns: float.
sech(angle) Hyperbolic secant of angle.
Parameters:
angle : float, value.
Returns: float.
csch(angle) Hyperbolic cosecant of angle.
Parameters:
angle : float, value.
Returns: float.
asinh(value) Hyperbolic area sine.
Parameters:
value : float, value.
Returns: float.
acosh(value) Hyperbolic area cosine.
Parameters:
value : float, value.
Returns: float.
atanh(value) Hyperbolic area tangent.
Parameters:
value : float, value.
Returns: float.
acoth(value) Hyperbolic area cotangent.
Parameters:
value : float, value.
Returns: float.
asech(value) Hyperbolic area secant.
Parameters:
value : float, value.
Returns: float.
acsch(value) Hyperbolic area cosecant.
Parameters:
value : float, value.
Returns: float.
MathSearchDijkstraLibrary "MathSearchDijkstra"
Shortest Path Tree Search Methods using Dijkstra Algorithm.
min_distance(distances, flagged_vertices) Find the lowest cost/distance.
Parameters:
distances : float array, data set with distance costs to start index.
flagged_vertices : bool array, data set with visited vertices flags.
Returns: int, lowest cost/distance index.
dijkstra(matrix_graph, dim_x, dim_y, start) Dijkstra Algorithm, perform a greedy tree search to calculate the cost/distance to selected start node at each vertex.
Parameters:
matrix_graph : int array, matrix holding the graph adjacency list and costs/distances.
dim_x : int, x dimension of matrix_graph.
dim_y : int, y dimension of matrix_graph.
start : int, the vertex index to start search.
Returns: int array, set with costs/distances to each vertex from start vertexs.
shortest_path(start, end, matrix_graph, dim_x, dim_y) Retrieves the shortest path between 2 vertices in a graph using Dijkstra Algorithm.
Parameters:
start : int, the vertex index to start search.
end : int, the vertex index to end search.
matrix_graph : int array, matrix holding the graph adjacency list and costs/distances.
dim_x : int, x dimension of matrix_graph.
dim_y : int, y dimension of matrix_graph.
Returns: int array, set with vertex indices to the shortest path.
MathGaussFunctionLibrary "MathGaussFunction"
Implements multiple gauss methods.
f_1d(point_x, sigma) 1-D Gaussian function.
Parameters:
point_x : float, x value.
sigma : float, sigma value, default=1.0.
Returns: float, function's value at point_x.
f_2d(point_x, point_y, sigma) 2-D Gaussian function.
Parameters:
point_x : float, x value.
point_y : float, y value.
sigma : float, sigma value, default=1.0.
Returns: float, function's value at (point_x, point_y).
kernel_1d(size, sigma) 1-D Gaussian kernel.
Parameters:
size : int, Kernel size (should be odd), .
sigma : float, sigma value, default=1.0.
Returns: float array, Returns 1-D Gaussian kernel of the specified size.
kernel_2d(size, sigma) 2-D Gaussian kernel.
Parameters:
size : int, Kernel size (should be odd), .
sigma : float, sigma value, default=1.0.
Returns: float array, Returns 2-D Gaussian kernel of the specified size.
MathFinancialAbsoluteRiskMeasuresLibrary "MathFinancialAbsoluteRiskMeasures"
Financial Absolute Risk Measures.
gain_stdev(sample) Standard deviation of gains in a data sample.
Parameters:
sample : float array, data sample.
Returns: float.
loss_stdev(sample) Standard deviation of losses in a data sample.
Parameters:
sample : float array, data sample.
Returns: float.
downside_stdev(sample, minimal_acceptable_return) Downside standard deviation in a data sample.
Parameters:
sample : float array, data sample.
minimal_acceptable_return : float, minimum gain value.
Returns: float.
semi_stdev(sample) Standard deviation of less than average returns in a data sample.
Parameters:
sample : float array, data sample.
Returns: float.
gain_loss_ratio(sample) ratio of average gains of average losses in a data sample.
Parameters:
sample : float array, data sample.
Returns: float.
compound_risk_score(source, length) Compound Risk Score
Parameters:
source : float, input data, default=close.
length : int, period of observation, default=12)
Returns: float.