Dynamic Array Table (versatile display methods)Library "datTable"
Dynamic Array Table.... Configurable Shape/Size Table from Arrays
Allows for any data in any size combination of arrays to join together
with:
all possible orientations!
filling all cells contiguously and/or flipping at boundaries
vertical or horizontal rotation
x/y axis direction swapping
all types array inputs for data.
please notify of any bugs. thanks
init(_posit)
Get Table (otional gapping cells)
Parameters:
_posit : String or Int (1-9 3x3 grid L to R)
Returns: Table
coords()
Req'd coords Seperate for VARIP table, non-varip coords
add
Add arrays to display table. coords reset each calc
uses displaytable object, string titles, and color optional array, and second line optional data array.
อินดิเคเตอร์และกลยุทธ์
PlurexSignalCoreLibrary "PlurexSignalCore"
General purpose functions and helpers for use in more specific Plurex Signal alerting scripts and libraries
plurexMarket()
Build a Plurex market string from a base and quote asset symbol.
Returns: A market string that can be used in Plurex Signal messages.
tickerToPlurexMarket()
Builds Plurex market string from the syminfo
Returns: A market string that can be used in Plurex Signal messages.
simpleMessage(secret, action, marketOverride)
Builds Plurex Signal Message json to be sent to a Signal webhook
Parameters:
secret : The secret for your Signal on plurex
action : The action of the message. One of .
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
entryMessage(secret, isLong, budgetPercentage, priceLimit, marketOverride)
Builds Plurex Signal Entry Message json to be sent to a Signal webhook with optional parameters for budget and price limits.
Parameters:
secret : The secret for your Signal on plurex
isLong : The action of the message. true for LONG, false for SHORT.
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
long(secret, budgetPercentage, priceLimit, marketOverride)
Builds Plurex Signal LONG Message json to be sent to a Signal webhook with optional parameters for budget and price limits.
Parameters:
secret : The secret for your Signal on plurex
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
short(secret, budgetPercentage, priceLimit, marketOverride)
Builds Plurex Signal SHORT Message json to be sent to a Signal webhook with optional parameters for budget and price limits.
Parameters:
secret : The secret for your Signal on plurex
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
closeAll(secret, marketOverride)
Builds Plurex Signal CLOSE_ALL Message json to be sent to a Signal webhook.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
closeShorts(secret, marketOverride)
Builds Plurex Signal CLOSE_SHORTS Message json to be sent to a Signal webhook.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
closeLongs(secret, marketOverride)
Builds Plurex Signal CLOSE_LONGS Message json to be sent to a Signal webhook.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
closeFirstLong(secret, marketOverride)
Builds Plurex Signal CLOSE_FIRST_LONG Message json to be sent to a Signal webhook.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
closeLastLong(secret, marketOverride)
Builds Plurex Signal CLOSE_LAST_LONG Message json to be sent to a Signal webhook.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
closeFirstShort(secret, marketOverride)
Builds Plurex Signal CLOSE_FIRST_SHORT Message json to be sent to a Signal webhook.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
closeLastShort(secret, marketOverride)
Builds Plurex Signal CLOSE_LAST_SHORT Message json to be sent to a Signal webhook.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
Expansion Contraction LibraryLibrary "ExpansionContraction"
Library for Expansion Contraction Indicator, a zero-lag dual perspective indicator created by Brian Latta based on Jake Bernstein’s principles of Moving Average Channel system.
calc(shortLookback, longLookback)
Calculates Expansion Contraction values.
Parameters:
shortLookback : Integer for the short lookback calculation, defaults to 8
longLookback : Integer for the long lookback calculation, defaults to 32
@return Returns array of Expansion Contraction values
stdevCalc(positiveShort, negativeShort, positiveLong, negativeLong, stdevLookback)
Calculates standard deviation lines based on Expansion Contraction Long and Short values.
Parameters:
positiveShort : Float for the positive short XC value from calculation
negativeShort : Float for the negative short XC value from calculation
positiveLong : Float for the positive long XC value from calculation
negativeLong : Float for the negative long XC value from calculation
stdevLookback : Integer for the standard deviation lookback, defaults to 500
@return Returns array of standard deviation values
trend(positiveShort, negativeShort, positiveLong, negativeLong)
Determines if trend is strong or weak based on Expansion Contraction values.
Parameters:
positiveShort : Float for the positive short XC value from calculation
negativeShort : Float for the negative short XC value from calculation
positiveLong : Float for the positive long XC value from calculation
negativeLong : Float for the negative long XC value from calculation
@return Returns array of boolean values indicating strength or weakness of trend
Stringify - Timeframe Enumeration --> StringLibrary "Stringify"
Cast variable types and enumerations to human-readable Strings
timeframe(string)
Cast a timeframe enumeration to readable string.
Parameters:
string : `T` is a timeframe enumeration ('3D', '120', '15', '5s' ...)
Returns: A string representation of the timeframe or 'NA' if `x` is `na`
EMAFlowLibrary "EMAFlow"
Functions that manipulate a set of 5 MAs created within user-supplied maximum and minimum lengths. The MAs are spaced out (within the range) in a way that approximates how Fibonnaci numbers are spaced.
Using MA flow, as opposed to simple crosses of the minimum and maximum lengths, gives more detail, and can result in faster changes and more resistance to chop, depending how you use it.
f_emaFlowBias()
@function f_emaFlowBias: Gives a bullish or bearish bias reading based on the EMA flow from the user-supplied range.
@param int _min: The minimum length of the EMA set.
@param int _max: The maximum length of the EMA set.
@param: string _source: The source for the EMA set. Must be in standard format (open, close, ohlc4, etc.)
@returns: An integer, representing the bias: 1 is bearish, 2 is slightly bearish, 3 is neutral, 4 is slightly bullish, 5 is bullish.
taLibrary "ta"
Collection of all custom and enhanced TA indicators. Same as enhanced_ta. But, removed all the displays to make it faster.
ma(source, maType, length)
returns custom moving averages
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
Returns: moving average for the given type and length
atr(maType, length)
returns ATR with custom moving average
Parameters:
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
Returns: ATR for the given moving average type and length
atrpercent(maType, length)
returns ATR as percentage of close price
Parameters:
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
Returns: ATR as percentage of close price for the given moving average type and length
bb(source, maType, length, multiplier, sticky)
returns Bollinger band for custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Bollinger band with custom moving average for given source, length and multiplier
bbw(source, maType, length, multiplier, sticky)
returns Bollinger bandwidth for custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Bollinger Bandwidth for custom moving average for given source, length and multiplier
bpercentb(source, maType, length, multiplier, sticky)
returns Bollinger Percent B for custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Bollinger Percent B for custom moving average for given source, length and multiplier
kc(source, maType, length, multiplier, useTrueRange, sticky)
returns Keltner Channel for custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
useTrueRange : - if set to false, uses high-low.
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Keltner Channel for custom moving average for given souce, length and multiplier
kcw(source, maType, length, multiplier, useTrueRange, sticky)
returns Keltner Channel Width with custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
useTrueRange : - if set to false, uses high-low.
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Keltner Channel Width for custom moving average
kpercentk(source, maType, length, multiplier, useTrueRange, sticky)
returns Keltner Channel Percent K Width with custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
useTrueRange : - if set to false, uses high-low.
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Keltner Percent K for given moving average, source, length and multiplier
dc(length, useAlternateSource, alternateSource, sticky)
returns Custom Donchian Channel
Parameters:
length : - donchian channel length
useAlternateSource : - Custom source is used only if useAlternateSource is set to true
alternateSource : - Custom source
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Donchian channel
dcw(length, useAlternateSource, alternateSource, sticky)
returns Donchian Channel Width
Parameters:
length : - donchian channel length
useAlternateSource : - Custom source is used only if useAlternateSource is set to true
alternateSource : - Custom source
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Donchian channel width
dpercentd(useAlternateSource, alternateSource, length, sticky)
returns Donchian Channel Percent of price
Parameters:
useAlternateSource : - Custom source is used only if useAlternateSource is set to true
alternateSource : - Custom source
length : - donchian channel length
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Donchian channel Percent D
oscillatorRange(source, method, highlowLength, rangeLength, sticky)
oscillatorRange - returns Custom overbought/oversold areas for an oscillator input
Parameters:
source : - Osillator source such as RSI, COG etc.
method : - Valid values for method are : sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
highlowLength : - length on which highlow of the oscillator is calculated
rangeLength : - length used for calculating oversold/overbought range - usually same as oscillator length
sticky : - overbought, oversold levels won't change unless crossed
Returns: Dynamic overbought and oversold range for oscillator input
oscillator(type, length, shortLength, longLength, source, highSource, lowSource, method, highlowLength, sticky)
oscillator - returns Choice of oscillator with custom overbought/oversold range
Parameters:
type : - oscillator type. Valid values : cci, cmo, cog, mfi, roc, rsi, stoch, tsi, wpr
length : - Oscillator length - not used for TSI
shortLength : - shortLength only used for TSI
longLength : - longLength only used for TSI
source : - custom source if required
highSource : - custom high source for stochastic oscillator
lowSource : - custom low source for stochastic oscillator
method : - Valid values for method are : sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
highlowLength : - length on which highlow of the oscillator is calculated
sticky : - overbought, oversold levels won't change unless crossed
Returns: Oscillator value along with dynamic overbought and oversold range for oscillator input
multibands(bandType, source, maType, length, useTrueRange, sticky, numberOfBands, multiplierStart, multiplierStep)
multibands - returns Choice of oscillator with custom overbought/oversold range
Parameters:
bandType : - Band type - can be either bb or kc
source : - custom source if required
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : - Oscillator length - not used for TSI
useTrueRange : - if set to false, uses high-low.
sticky : - for sticky borders which only change upon source crossover/crossunder
numberOfBands : - Number of bands to generate
multiplierStart : - Starting ATR or Standard deviation multiplier for first band
multiplierStep : - Incremental value for multiplier for each band
Returns: array of band values sorted in ascending order
mbandoscillator(bandType, source, maType, length, useTrueRange, stickyBands, numberOfBands, multiplierStart, multiplierStep)
mbandoscillator - Multiband oscillator created on the basis of bands
Parameters:
bandType : - Band type - can be either bb or kc
source : - custom source if required
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : - Oscillator length - not used for TSI
useTrueRange : - if set to false, uses high-low.
stickyBands : - for sticky borders which only change upon source crossover/crossunder for band detection
numberOfBands : - Number of bands to generate
multiplierStart : - Starting ATR or Standard deviation multiplier for first band
multiplierStep : - Incremental value for multiplier for each band
Returns: oscillator currentStates - Array containing states for last n bars
CSMlibraryLibrary "CSMlibrary"
TODO: Contains functions to simplify my scripts. Using code snippets in reference manual and elsewhere .....
CSMplot()
Slope_TKLibrary "Slope_TK"
This library calculate the slope of a serie between two points
The serie can be ta.ema(close,200) for example
The size is the number of bars between the two points for the slope calculation, for example it can be 10
slope_of_ema200 = slope(t a.eam(close, 200) , 10 )
slope( float serie, int size )
libcompressLibrary "libcompress"
numbers compressor for large output data compression
compress_fp24()
converts float to base64 (4 chars) | 24 bits: 1 sign + 5 exponent + 18 mantissa
Returns: 4-character base64_1/5/18 representation of x
compress_ufp18()
converts unsigned float to base64 (3 chars) | 18 bits: 5 exponent + 13 mantissa
Returns: 3-character base64_0/5/13 representation of x
compress_int()
converts int to base64
racille_arrayutilsLibrary "racille_arrayutils"
The most used array utility functions
func_sin()
returns sin function as a parameter to calculate the function_array()
func_cos()
returns cos function as a parameter to calculate the function_array()
func_tan()
returns tan function as a parameter to calculate the function_array()
func_cot()
returns cot function as a parameter to calculate the function_array()
func_asin()
returns asin function as a parameter to calculate the function_array()
func_acos()
returns acos function as a parameter to calculate the function_array()
func_atan()
returns atan function as a parameter to calculate the function_array()
func_acot()
returns acot function as a parameter to calculate the function_array()
func_sqrt()
returns sqrt function as a parameter to calculate the function_array()
func_pow(x)
returns pow function as a parameter to calculate the function_array()
Parameters:
x : - power
func_exp(x)
returns exp function as a parameter to calculate the function_array()
Parameters:
x : - base
func_log(x)
returns log function as a parameter to calculate the function_array()
Parameters:
x : - base
func_replace_array(arr, func)
replace each element of array with func(element) and returns a new array
Parameters:
arr : - array
func : - function to replace. Must be one of func_*()
Returns: new array, where each element is func(element)
multiply_array(arr, x)
multiplies each element of array by multiplier and returns a new array
Parameters:
arr : - array
x : - multiplier
Returns: new array, where each element is multiplied on x
multiply_array(arr, n)
multiplies each element of array by multiplier and returns a new array
Parameters:
arr : - array
n : - multiplier
Returns: new array, where each element is multiplied on n
multiply_array(arr, n)
multiplies each element of array by multiplier and returns a new array
Parameters:
arr : - array
n : - multiplier
Returns: new array, where each element is multiplied on n
divide_array(arr, x)
divides each element of array by divider and returns a new array
Parameters:
arr : - array
x : - divider
Returns: new array, where each element is multiplied on x
divide_array(arr, n)
divides each element of array by divider and returns a new array
Parameters:
arr : - array
n : - divider
Returns: new array, where each element is multiplied on n
increase_array(arr, x)
adds increment to each element of array and returns a new array
Parameters:
arr : - array
x : - increment
Returns: new array, where each element is multiplied on x
increase_array(arr, n)
adds increment to each element of array and returns a new array
Parameters:
arr : - array
n : - increment
Returns: new array, where each element is multiplied on n
increase_array(arr, n)
adds increment to each element of array and returns a new array
Parameters:
arr : - array
n : - increment
Returns: new array, where each element is multiplied on x
decrease_array(arr, x)
substracts decrement to each element of array and returns a new array
Parameters:
arr : - array
x : - decrement
Returns: new array, where each element is multiplied on x
decrease_array(arr, n)
substracts decrement to each element of array and returns a new array
Parameters:
arr : - array
n : - decrement
Returns: new array, where each element is multiplied on n
decrease_array(arr, n)
substracts decrement to each element of array and returns a new array
Parameters:
arr : - array
n : - decrement
Returns: new array, where each element is multiplied on x
negate_array(arr)
changes each elements sign of array and returns a new array
Parameters:
arr : - array
Returns: new array, where each element is of different sign
array_sum()
calculates elementwise sum of two arrays
array_diff()
calculates elementwise difference of two arrays
array_product()
calculates elementwise product of two arrays
array_division()
calculates elementwise division of two arrays
StringStringHashmapLibrary "StringStringHashmap"
A simple implementation of a key string-to-string value dictionary in pine script
create_ss_dict()
Create an empty string-string dictionary
Returns: the indices and elements of the dict
add_key_value(key, value, i, e)
Add new key-value pair in the dictionary
Parameters:
key : string
value : string
i : string the indices of the dictionary
e : string the element of the dictionary
get_value(key, i, e)
Get the value of the given key
Parameters:
key : string
i : string the indices of the dictionary
e : string the element of the dictionary
Returns: return the value of the given key
change_value(key, value, i, e)
Change the value of the given key
Parameters:
key : string
value : string
i : string the indices of the dictionary
e : string the element of the dictionary
Hurst Exponent (Dubuc's variation method)Library "Hurst"
hurst(length, samples, hi, lo)
Estimate the Hurst Exponent using Dubuc's variation method
Parameters:
length : The length of the history window to use. Large values do not cause lag.
samples : The number of scale samples to take within the window. These samples are then used for regression. The minimum value is 2 but 3+ is recommended. Large values give more accurate results but suffer from a performance penalty.
hi : The high value of the series to analyze.
lo : The low value of the series to analyze.
The Hurst Exponent is a measure of fractal dimension, and in the context of time series it may be interpreted as indicating a mean-reverting market if the value is below 0.5 or a trending market if the value is above 0.5. A value of exactly 0.5 corresponds to a random walk.
There are many definitions of fractal dimension and many methods for its estimation. Approaches relying on calculation of an area, such as the Box Counting Method, are inappropriate for time series data, because the units of the x-axis (time) do match the units of the y-axis (price). Other approaches such as Detrended Fluctuation Analysis are useful for nonstationary time series but are not exactly equivalent to the Hurst Exponent.
This library implements Dubuc's variation method for estimating the Hurst Exponent. The technique is insensitive to x-axis units and is therefore useful for time series. It will give slightly different results to DFA, and the two methods should be compared to see which estimator fits your trading objectives best.
Original Paper:
Dubuc B, Quiniou JF, Roques-Carmes C, Tricot C. Evaluating the fractal dimension of profiles. Physical Review A. 1989;39(3):1500-1512. DOI: 10.1103/PhysRevA.39.1500
Review of various Hurst Exponent estimators for time-series data, including Dubuc's method:
www.intechopen.com
NetLiquidityLibraryLibrary "NetLiquidityLibrary"
The Net Liquidity Library provides daily values for net liquidity. Net liquidity is measured as Fed Balance Sheet - Treasury General Account - Reverse Repo. Time series for each individual component included too.
get_net_liquidity_for_date(t)
Function takes date in timestamp form and returns the Net Liquidity value for that date. If date is not present, 0 is returned.
Parameters:
t : The timestamp of the date you are requesting the Net Liquidity value for.
Returns: The Net Liquidity value for the specified date.
get_net_liquidity()
Gets the Net Liquidity time series from Dec. 2021 to current. Dates that are not present are represented as 0.
Returns: The Net Liquidity time series.
text_utilsLibrary "text_utils"
a set of functions to handle placeholder in texts
add_placeholder(list, key, value)
add a placehodler key and value to a local list
Parameters:
list : - reference to a local string array containing all placeholders, add string list = array.new_string(0) to your code
key : - a string representing the placeholder in a text, e.g. '{ticker}'
value : - a string representing the value of the placeholder e.g. 'EURUSD'
Returns: void
add_placeholder(list, key, value, format)
add a placehodler key and value to a local list
Parameters:
list : - reference to a local string array containing all placeholders, add string list = array.new_string(0) to your code
key : - a string representing the placeholder in a text, e.g. '{ticker}'
value : - an integer value representing the value of the placeholder e.g. 10
format : - optional format string to be used when converting integer value to string, see str.format() for details, must contain '{0}'
Returns: void
add_placeholder(list, key, value, format)
add a placehodler key and value to a local list
Parameters:
list : - reference to a local string array containing all placeholders, add string list = array.new_string(0) to your code
key : - a string representing the placeholder in a text, e.g. '{ticker}'
value : - a float value representing the value of the placeholder e.g. 1.5
format : - optional format string to be used when converting float value to string, see str.format() for details, must contain '{0}'
Returns: void
replace_all_placeholder(list, text_to_covert)
replace all placeholder keys with their value in a given text
Parameters:
list : - reference to a local string array containing all placeholders
text_to_covert : - a text with placeholder keys before their are replaced by their values
Returns: text with all replaced placeholder keys
ReduceSecurityCallsLibrary "ReduceSecurityCalls"
This library allows you to reduce the number of request.security calls to 1 per symbol per timeframe. Script provides example how to use it with request.security and possible optimisation applied to htf data call.
This data can be used to calculate everything you need and more than that (for example you can calculate 4 emas with one function call on mat_out).
ParseSource(mat_outs, o)
Should be used inside request.security call. Optimise your calls using timeframe.change when htf data parsing! Supports up to 5 expressions (results of expressions must be float or int)
Parameters:
mat_outs : Matrix to be used as outputs, first value is newest
o : Please use parametres in the order they specified (o should be 1st, h should be 2nd etc..)
Returns: outs array, due to weird limitations do not try this :matrix_out = matrix.copy(ParseSource)
String_Encoder_DecoderLibrary "String_Encoder_Decoder"
String encoder and decoder to use in internal data tranfer in script calculations.
In example, script encode 125 values once and then decode them every candle.
encode(array or values (val1,val2,val3,val4,val5,val6)
encode: encode some values into string
Parameters:
array : of values or values1, value2 (up to 6 values)
(input values must be stringified)
Returns: encoded value
decode(val)
decode: decode into string
Parameters:
val : value to decode, must be stringified
Returns: decoded array of stringified values
fast_utilsLibrary "fast_utils"
This library contains my favourite functions. Will be updated frequently
count_int_digits()
Count int digits in number
Returns: : number of int digits in number
count_float_digits()
Count float digits in number
Returns: : number of float digits in number
stringify()
Convert values in array or matrix into string values
Returns: : array or matrix of string values
arrcompare()
Compare values in arrays
Returns: : bool value
arrdedup()
Remove duplicate values in array
Returns: : array without duplicates
ResInMins()
Converts current resolution in minutes
Returns: : return float number of minuted
MultOfRes(res, mult)
Convert current float TF in minutes to target string TF in "timeframe.period" format.
Parameters:
res : : current resolution in minutes
mult : : Multiple of current TF to be calculated.
Returns: : timeframe format string
fractionLibrary "fraction"
Fraction Creation and Basic Operations.
Cracked a tough problem in making this Polarity Agnostic Decimal without a cheating "abs * sign of input".
it's quite fast, however still test for errors before production use.
>> Big Neon Sign on 1/0 value. <<
Int Array (LOC 0/1)..
To/From Decimal(float)
Comparison ( < / == / >)
Add / Sub / Mult / Div
Invert polarity +/-
String output with 2 formats ..
make(_numerator, _denominator, _val)
Parameters:
_numerator : (int) above the line integer ie: ____ of (___ / bottom )
_denominator : (int) below the line integer ie: ____ of (top / ______ )
_val : (int) OPTIONAL (for no real reason including it) integer to multiply
Returns: array where index 0 is Numerator, 1 is Denominator
add(_fraction, _fraction2)
Perform add operation (left adds right onto )
Parameters:
_fraction : (array) left side Fraction Object
_fraction2 : (array) right side Fraction Object
Returns: array where index 0 is Numerator, 1 is Denominator
subtract(_fraction, _fraction2)
Perform subtract operation (left subtracts right from )
Parameters:
_fraction : (array) left side Fraction Object
_fraction2 : (array) right side Fraction Object
Returns: array where index 0 is Numerator, 1 is Denominator
multiply(_fraction, _fraction2)
Perform multiply operation (left multiplies by right )
Parameters:
_fraction : (array) left side Fraction Object
_fraction2 : (array) right side Fraction Object
Returns: array where index 0 is Numerator, 1 is Denominator
divide(_fraction, _fraction2)
Perform divide operation (left divides by right )
Parameters:
_fraction : (array) left side Fraction Object
_fraction2 : (array) right side Fraction Object
Returns: array where index 0 is Numerator, 1 is Denominator
negative(_fraction)
Perform Negative number inversion ie: (-1/2 => 1/2) or (3/5 => -3/5)
Parameters:
_fraction : (array) Fraction Object to invert to/from negative
Returns: array where index 0 is Numerator, 1 is Denominator
isSmaller(_fraction, _fraction2)
Check if first fraction is smaller
Parameters:
_fraction : (array) left side Fraction Object
_fraction2 : (array) right side Fraction Object
Returns: True if smaller, false if bigger
isLarger(_fraction, _fraction2)
Check if first fraction is larger
Parameters:
_fraction : (array) left side Fraction Object
_fraction2 : (array) right side Fraction Object
Returns: True if smaller, false if bigger
isEqual(_fraction, _fraction2)
Check if first fraction is equal
Parameters:
_fraction : (array) left side Fraction Object
_fraction2 : (array) right side Fraction Object
Returns: True if smaller, false if bigger
fromDec(_input, _epsilon, _iterations)
Convert Decimal to Fraction array
note : this is my own Negative Number Capable (tiny speed loss)
adaptation of the fastest algo out there
Exclusive for Tradingview.
Parameters:
_input : (float) Decimal Input
_epsilon : (int) (OPTIONAL) to precision 0's after dec 0.0000 -> epsilon 0's
_iterations : (int) (OPTIONAL) Maximum iterations Till give up
Returns: array where index 0 is Numerator, 1 is Denominator
toDec()
Convert Fraction to Decimal Output
Returns: Float of fration
toString(_fraction)
Create "A/B" or "A and B/C" String Value of Fraction.
Parameters:
_fraction : (array) Fraction Object to invert to/from negative
Returns: String as (-)? A and B/C format
Encoder DecoderLibrary "EncoderDecoder"
Simple example how to encode some values into float number and then decode it back to original values
f_calctype()
Encode parameter
Returns: encoded value
f_calctype()
Decode parameter
Returns: decoded value
f_srctype()
Encode parameter
Returns: encoded value
f_srctype()
Decode parameter
Returns: decoded value
f_encode(calc_type, src_type, tf, length)
Encodes 4 paramters into float number
Parameters:
calc_type : 1st paramter to encode (its values defined in f_calctype functions) max number of values that can be encoded = 100
src_type : 2nd paramter to encode (its values defined in f_src_type functions) max number of values that can be encoded = 100
tf : 3rd paramter to encode (may be int number with format.price precision length!)
length : 4th paramter to encode (may be any int number)
Returns: float number
f_decode()
Decodes 4 paramters into tuple
Returns: tuple
Global_Economic_CalendarLibrary of economic events. Created to display events on the desired chart through the indicator.
Countries: USA, China, Eurozone, Russia
Importance: 3 stars
Source: Investing
Библиотека экономических событий. Создана для отображения событий на нужном графике через индикатор.
Страны: США, Китай, Еврозона, Россия
Важность: 3 звезды
Источник: Investing
Traders_Reality_LibLibrary "Traders_Reality_Lib"
This library contains common elements used in Traders Reality scripts
calcPvsra(pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, darkGreyCandleColor, lightGrayCandleColor)
calculate the pvsra candle color and return the color as well as an alert if a vector candle has apperared.
Situation "Climax"
Bars with volume >= 200% of the average volume of the 10 previous chart TFs, or bars
where the product of candle spread x candle volume is >= the highest for the 10 previous
chart time TFs.
Default Colors: Bull bars are green and bear bars are red.
Situation "Volume Rising Above Average"
Bars with volume >= 150% of the average volume of the 10 previous chart TFs.
Default Colors: Bull bars are blue and bear are violet.
Parameters:
pvsraVolume : the instrument volume series (obtained from request.sequrity)
pvsraHigh : the instrument high series (obtained from request.sequrity)
pvsraLow : the instrument low series (obtained from request.sequrity)
pvsraClose : the instrument close series (obtained from request.sequrity)
pvsraOpen : the instrument open series (obtained from request.sequrity)
redVectorColor : red vector candle color
greenVectorColor : green vector candle color
violetVectorColor : violet/pink vector candle color
blueVectorColor : blue vector candle color
darkGreyCandleColor : regular volume candle down candle color - not a vector
lightGrayCandleColor : regular volume candle up candle color - not a vector
@return
adr(length, barsBack)
Parameters:
length : how many elements of the series to calculate on
barsBack : starting possition for the length calculation - current bar or some other value eg last bar
@return adr the adr for the specified lenght
adrHigh(adr, fromDo)
Calculate the ADR high given an ADR
Parameters:
adr : the adr
fromDo : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrHigh the position of the adr high in price
adrLow(adr, fromDo)
Parameters:
adr : the adr
fromDo : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrLow the position of the adr low in price
splitSessionString(sessXTime)
given a session in the format 0000-0100:23456 split out the hours and minutes
Parameters:
sessXTime : the session time string usually in the format 0000-0100:23456
@return
calcSessionStartEnd(sessXTime, gmt)
calculate the start and end timestamps of the session
Parameters:
sessXTime : the session time string usually in the format 0000-0100:23456
gmt : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return
drawOpenRange(sessXTime, sessXcol, showOrX, gmt)
draw open range for a session
Parameters:
sessXTime : session string in the format 0000-0100:23456
sessXcol : the color to be used for the opening range box shading
showOrX : boolean flag to toggle displaying the opening range
gmt : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return void
drawSessionHiLo(sessXTime, show_rectangleX, show_labelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle)
Parameters:
sessXTime : session string in the format 0000-0100:23456
show_rectangleX : show the session high and low lines
show_labelX : show the session label
sessXcolLabel : the color to be used for the hi/low lines and label
sessXLabel : the session label text
gmt : the gmt offset string usually in the format GMT+1 or GMT+2 etc
sessionLineStyle : the line stile for the session high low lines
@return void
calcDst()
calculate market session dst on/off flags
@return indicating if DST is on or off for a particular region
timestampPreviousDayOfWeek(previousDayOfWeek, hourOfDay, gmtOffset, oneWeekMillis)
Timestamp any of the 6 previous days in the week (such as last Wednesday at 21 hours GMT)
Parameters:
previousDayOfWeek : Monday or Satruday
hourOfDay : the hour of the day when psy calc is to start
gmtOffset : the gmt offset string usually in the format GMT+1 or GMT+2 etc
oneWeekMillis : the amount if time for a week in milliseconds
@return the timestamp of the psy level calculation start time
getdayOpen()
get the daily open - basically exchange midnight
@return the daily open value which is float price
newBar(res)
new_bar: check if we're on a new bar within the session in a given resolution
Parameters:
res : the desired resolution
@return true/false is a new bar for the session has started
toPips(val)
to_pips Convert value to pips
Parameters:
val : the value to convert to pips
@return the value in pips
rLabel(ry, rtext, rstyle, rcolor, valid, labelXOffset)
a function that draws a right aligned lable for a series during the current bar
Parameters:
ry : series float the y coordinate of the lable
rtext : the text of the label
rstyle : the style for the lable
rcolor : the color for the label
valid : a boolean flag that allows for turning on or off a lable
labelXOffset : how much to offset the label from the current position
rLabelOffset(ry, rtext, rstyle, rcolor, valid, labelXOffset)
a function that draws a right aligned lable for a series during the current bar
Parameters:
ry : series float the y coordinate of the lable
rtext : the text of the label
rstyle : the style for the lable
rcolor : the color for the label
valid : a boolean flag that allows for turning on or off a lable
labelXOffset : how much to offset the label from the current position
rLabelLastBar(ry, rtext, rstyle, rcolor, valid, labelXOffset)
a function that draws a right aligned lable for a series only on the last bar
Parameters:
ry : series float the y coordinate of the lable
rtext : the text of the label
rstyle : the style for the lable
rcolor : the color for the label
valid : a boolean flag that allows for turning on or off a lable
labelXOffset : how much to offset the label from the current position
drawLine(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, labelXOffset, validTimeFrame)
a function that draws a line and a label for a series
Parameters:
xSeries : series float the y coordinate of the line/label
res : the desired resolution controlling when a new line will start
tag : the text for the lable
xColor : the color for the label
xStyle : the style for the line
xWidth : the width of the line
xExtend : extend the line
isLabelValid : a boolean flag that allows for turning on or off a label
labelXOffset : how much to offset the label from the current position
validTimeFrame : a boolean flag that allows for turning on or off a line drawn
drawLineDO(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, labelXOffset, validTimeFrame)
a function that draws a line and a label for the daily open series
Parameters:
xSeries : series float the y coordinate of the line/label
res : the desired resolution controlling when a new line will start
tag : the text for the lable
xColor : the color for the label
xStyle : the style for the line
xWidth : the width of the line
xExtend : extend the line
isLabelValid : a boolean flag that allows for turning on or off a label
labelXOffset : how much to offset the label from the current position
validTimeFrame : a boolean flag that allows for turning on or off a line drawn
drawPivot(pivotLevel, res, tag, pivotColor, pivotLabelColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid, validTimeFrame, levelStart, pivotLabelXOffset)
draw a pivot line - the line starts one day into the past
Parameters:
pivotLevel : series of the pivot point
res : the desired resolution
tag : the text to appear
pivotColor : the color of the line
pivotLabelColor : the color of the label
pivotStyle : the line style
pivotWidth : the line width
pivotExtend : extend the line
isLabelValid : boolean param allows to turn label on and off
validTimeFrame : only draw the line and label at a valid timeframe
levelStart : basically when to start drawing the levels
pivotLabelXOffset : how much to offset the label from its current postion
@return the pivot line series
getPvsraFlagByColor(pvsraColor, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, lightGrayCandleColor)
convert the pvsra color to an internal code
Parameters:
pvsraColor : the calculated pvsra color
redVectorColor : the user defined red vector color
greenVectorColor : the user defined green vector color
violetVectorColor : the user defined violet vector color
blueVectorColor : the user defined blue vector color
lightGrayCandleColor : the user defined regular up candle color
@return pvsra internal code
updateZones(pvsra, direction, boxArr, maxlevels, pvsraHigh, pvsraLow, pvsraOpen, pvsraClose, transperancy, zoneupdatetype, zonecolor, zonetype, borderwidth, coloroverride, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, lightGrayCandleColor)
a function that draws the unrecovered vector candle zones
Parameters:
pvsra : internal code
direction : above or below the current pa
boxArr : the array containing the boxes that need to be updated
maxlevels : the maximum number of boxes to draw
pvsraHigh : the pvsra high value series
pvsraLow : the pvsra low value series
pvsraOpen : the pvsra open value series
pvsraClose : the pvsra close value series
transperancy : the transparencfy of the vecor candle zones
zoneupdatetype : the zone update type
zonecolor : the zone color if overriden
zonetype : the zone type
borderwidth : the width of the border
coloroverride : if the color overriden
redVectorColor : the user defined red vector color
greenVectorColor : the user defined green vector color
violetVectorColor : the user defined violet vector color
blueVectorColor : the user defined blue vector color
lightGrayCandleColor : the user defined regular up candle color
cleanarr(arr)
clean an array from na values
Parameters:
arr : the array to clean
@return if the array was cleaned
calcPsyLevels(oneWeekMillis, showPsylevels, psyType, sydDST)
calculate the psy levels
4 hour res based on how mt4 does it
mt4 code
int Li_4 = iBarShift(NULL, PERIOD_H4, iTime(NULL, PERIOD_W1, Li_0)) - 2 - Offset;
ObjectCreate("PsychHi", OBJ_TREND, 0, Time , iHigh(NULL, PERIOD_H4, iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)), iTime(NULL, PERIOD_W1, 0), iHigh(NULL, PERIOD_H4,
iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)));
so basically because the session is 8 hours and we are looking at a 4 hour resolution we only need to take the highest high an lowest low of 2 bars
we use the gmt offset to adjust the 0000-0800 session to Sydney open which is at 2100 during dst and at 2200 otherwize. (dst - spring foward, fall back)
keep in mind sydney is in the souther hemisphere so dst is oposite of when london and new york go into dst
Parameters:
oneWeekMillis : a constant value
showPsylevels : should psy levels be calculated
psyType : the type of Psylevels - crypto or forex
sydDST : is Sydney in DST
@return
strategyLibrary "strategy"
Library containing few key calculations for strategy involving leveraged limit and stop orders
getQty(entry, stop, riskPercentage)
calculate qty and leverage based on entry and stop price for given risk percentage.
Parameters:
entry : Entry Price
stop : Stop Price
riskPercentage : risk percentage per trade
Returns: - Quantity based on the risk and calculated leverage on position including existing positions
bracketOrder(entry, stop, target, maxLeverage, isLimitOrder, riskPercentage)
Calculates position size based on risk and creates bracket orders for given entry/stop/target
Parameters:
entry : Entry Price
stop : Stop Price
target : Target Price
maxLeverage : Maximum leverage allowed
isLimitOrder : if true, places limit order for entry, else places stop order.
riskPercentage : risk percentage per trade
Returns: orderPlaced - true if orders successfully placed, false otherwise.
order(entry, stop, maxLeverage, isLimitOrder, riskPercentage)
Calculates position size based on risk and creates order for given entry/stop
Parameters:
entry : Entry Price
stop : Stop Price
maxLeverage : Maximum leverage allowed
isLimitOrder : if true, places limit order for entry, else places stop order.
riskPercentage : risk percentage per trade
Returns: orderPlaced - true if orders successfully placed, false otherwise.
kNNLibrary "kNN"
Collection of experimental kNN functions. This is a work in progress, an improvement upon my original kNN script:
The script can be recreated with this library. Unlike the original script, that used multiple arrays, this has been reworked with the new Pine Script matrix features.
To make a kNN prediction, the following data should be supplied to the wrapper:
kNN : filter type. Right now either Binary or Percent . Binary works like in the original script: the system stores whether the price has increased (+1) or decreased (-1) since the previous knnStore event (called when either long or short condition is supplied). Percent works the same, but the values stored are the difference of prices in percents. That way larger differences in prices would give higher scores.
k : number k. This is how many nearest neighbors are to be selected (and summed up to get the result).
skew : kNN minimum difference. Normally, the prediction is done with a simple majority of the neighbor votes. If skew is given, then more than a simple majority is needed for a prediction. This also means that there are inputs for which no prediction would be given (if the majority votes are between -skew and +skew). Note that in Percent mode more profitable trades will have higher voting power.
depth : kNN matrix size limit. Originally, the whole available history of trades was used to make a prediction. This not only requires more computational power, but also neglects the fact that the market conditions are changing. This setting restricts the memory matrix to a finite number of past trades.
price : price series
long : long condition. True if the long conditions are met, but filters are not yet applied. For example, in my original script, trades are only made on crossings of fast and slow MAs. So, whenever it is possible to go long, this value is set true. False otherwise.
short : short condition. Same as long , but for short condition.
store : whether the inputs should be stored. Additional filters may be applied to prevent bad trades (for example, trend-based filters), so if you only need to consult kNN without storing the trade, this should be set to false.
feature1 : current value of feature 1. A feature in this case is some kind of data derived from the price. Different features may be used to analyse the price series. For example, oscillator values. Not all of them may be used for kNN prediction. As the current kNN implementation is 2-dimensional, only two features can be used.
feature2 : current value of feature 2.
The wrapper returns a tuple: [ longOK, shortOK ]. This is a pair of filters. When longOK is true, then kNN predicts a long trade may be taken. When shortOK is true, then kNN predicts a short trade may be taken. The kNN filters are returned whenever long or short conditions are met. The trade is supposed to happen when long or short conditions are met and when the kNN filter for the desired direction is true.
Exported functions :
knnStore(knn, p1, p2, src, maxrows)
Store the previous trade; buffer the current one until results are in. Results are binary: up/down
Parameters:
knn : knn matrix
p1 : feature 1 value
p2 : feature 2 value
src : current price
maxrows : limit the matrix size to this number of rows (0 of no limit)
Returns: modified knn matrix
knnStorePercent(knn, p1, p2, src, maxrows)
Store the previous trade; buffer the current one until results are in. Results are in percents
Parameters:
knn : knn matrix
p1 : feature 1 value
p2 : feature 2 value
src : current price
maxrows : limit the matrix size to this number of rows (0 of no limit)
Returns: modified knn matrix
knnGet(distance, result)
Get neighbours by getting k results with the smallest distances
Parameters:
distance : distance array
result : result array
Returns: array slice of k results
knnDistance(knn, p1, p2)
Create a distance array from the two given parameters
Parameters:
knn : knn matrix
p1 : feature 1 value
p2 : feature 2 value
Returns: distance array
knnSum(knn, p1, p2, k)
Make a prediction, finding k nearest neighbours and summing them up
Parameters:
knn : knn matrix
p1 : feature 1 value
p2 : feature 2 value
k : sum k nearest neighbors
Returns: sum of k nearest neighbors
doKNN(kNN, k, skew, depth, price, long, short, store, feature1, feature2)
execute kNN filter
Parameters:
kNN : filter type
k : number k
skew : kNN minimum difference
depth : kNN matrix size limit
price : series
long : long condition
short : short condition
store : store the supplied features (if false, only checks the results without storage)
feature1 : feature 1 value
feature2 : feature 2 value
Returns: filter output