SgjoeLibraryLibrary "SgjoeLibrary"
Custom functions
highest_when(float, float) Permits a condition to be used with highest(high,condition)
Parameters:
float : _high_series The High for the condition
float : _when The condition such as close > high
Returns: The high(s) at the point(s) the condition was true
lowest_when(float, float) Permits a condition to be used with lowest(low,condition)
Parameters:
float : _low_series The Low for the condition
float : _when The condition such as close < low
Returns: The low(s) at the point(s) the condition was true
Indicators and strategies
MomentumSignalsLibrary "MomentumSignals"
Contains utilities varying algorithms for detecting key changes in momentum. Note: Momentum is not velocity and should be used in conjunction with other indicators. A change in momentum does not mean a reversal of velocity or trend.
simple(primary, secondary, len) Compares two series for changes in momentum to derive signal values.
Parameters:
primary : The primary series (typically a moving average) to look for changes in momentum.
secondary : The secondary series (typically derived moving average of the primary) to use as a comparison value.
len : The number of bars to measure the change in momentum.
filtered(primary, secondary, len, stdlen, stdMultiple) Compares two series for changes in momentum to derive signal values. Uses statistics to filter out changes in momentum.
Parameters:
primary : The primary series (typically a moving average) to look for changes in momentum.
secondary : The secondary series (typically derived moving average of the primary) to use as a comparison value.
len : The number of bars to measure the change in momentum.
stdlen : The number of bars to measure the change in momentum for filtering.
stdMultiple : The multiple of the change in momentum to use before reversiing.
special(primary, secondary, stdlen, stdMultiple) Compares two series for changes in momentum to derive signal values. Uses statistics to filter out changes in momentum. Does not signal when likely overbought or oversold.
Parameters:
primary : The primary series (typically a moving average) to look for changes in momentum.
secondary : The secondary series (typically derived moving average of the primary) to use as a comparison value.
stdlen : The number of bars to measure the change in momentum for filtering.
stdMultiple : The multiple of the change in momentum to use before reversiing.
GenericTradingLibrary "GenericTrading"
This library aims to collect rare but useful operations for
get_most_recent_long_or_short_position_closed_index() : returns most recent long/short closed bar index.
get_most_recent_long_or_short_position_open_index() : returns most recent long/short closed bar index.
These two functions designed to help to speed up the coding for strategies that contains "re-enter" logic.
These two functions also could applies in the situations where time-count is needed in your condition.
MomentumLibrary "Momentum"
Contains utilities varying algorithms for measuring momentum.
simple(fast, slow, src, fastType, slowType) Derives momentum from two moving averages of different lengths.
Parameters:
fast : The length of the fast moving average.
slow : The length of the slow moving average.
src : The series to measure from. Default is 'close'.
fastType : The type of moving average the fast should use. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA.
slowType : The type of moving average the slow should use. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA.
stochRSI(fast, fast, rsiLen, stochLen, src, kmode) Returns the K and D values of a Stochastic RSI. Allows for different moving averages to produce the K value.
Parameters:
fast : The length to average the stochastic.
fast : The length to smooth out K and produce D.
rsiLen : The length of the RSI.
stochLen : The length of stochastic.
src : The series to measure from. Default is 'close'.
kmode : The type of moving average to generate. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA.
Returns:
macd(fast, slow, signal, src, fastType, slowType, slowType) Same as well-known MACD formula but allows for different moving averages types to be used.
Parameters:
fast : The length of the fast moving average.
slow : The length of the slow moving average.
signal : The length of average to applied to smooth out the signal.
src : The series to measure from. Default is 'close'.
fastType : The type of moving average the fast should use. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA.
slowType : The type of moving average the slow should use. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA.
slowType : The type of moving average the signal should use. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA.
Returns:
arsenalLibrary "arsenal"
This library is a collection of weapons that will help us win the war against the market.
isNewbar(res, timezone) Checks if the res is in new bar at the current timeframe
Parameters:
res : - resolution of the bar to check if new
timezone : - timezone of the resolution
Returns: ch: - 1=true, 0=false
VolatilityLibrary "Volatility"
Functions for determining if volatility (true range) is within or exceeds normal.
The "True Range" (ta.tr) is used for measuring volatility.
Values are normalized by the volume adjusted weighted moving average (VAWMA) to be more like percent moves than price.
current(len) Returns the current price adjusted volatitlity ratio.
Parameters:
len : Number of bars to get a volume adjusted weighted average price.
normal(len, maxDeviation, level, gapDays, spec, res) Returns the normal upper range of volatility. Compensates for overnight gaps within a regular session.
Parameters:
len : Number of bars to measure volatility.
maxDeviation : The limit of volatility before considered an outlier.
level : The amount of standard deviation after cleaning outliers to be considered within normal.
gapDays : The number of days in the past to measure overnight gap volaility.
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = '1440').
isNormal(len, maxDeviation, level, gapDays, spec, res) Returns true if the volatility (true range) is within normal levels. Compensates for overnight gaps within a regular session.
Parameters:
len : Number of bars to measure volatility.
maxDeviation : The limit of volatility before considered an outlier.
level : The amount of standard deviation after cleaning outliers to be considered within normal.
gapDays : The number of days in the past to measure overnight gap volaility.
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = '1440').
severity(len, maxDeviation, level, gapDays, spec, res) Returns ratio of the current value to the normal value. Compensates for overnight gaps within a regular session.
Parameters:
len : Number of bars to measure volatility.
maxDeviation : The limit of volatility before considered an outlier.
level : The amount of standard deviation after cleaning outliers to be considered within normal.
gapDays : The number of days in the past to measure overnight gap volaility.
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = '1440').
DataCleanerLibrary "DataCleaner"
Functions for acquiring outlier levels and acquiring a cleaned version of a series.
outlierLevel(src, len, level) Gets the (standard deviation) outlier level for a given series.
Parameters:
src : The series to average and add a multiple of the standard deviation to.
len : The The number of bars to measure.
level : The positive or negative multiple of the standard deviation to apply to the average. A positive number will be the upper boundary and a negative number will be the lower boundary.
Returns: The average of the series plus the multiple of the standard deviation.
cleanUsing(src, result, len, maxDeviation) Returns an array representing the result series with (outliers provided by the source) removed.
Parameters:
src : The source series to read from.
result : The result series.
len : The maximum size of the resultant array.
maxDeviation : The positive or negative multiple of the standard deviation to apply to the average. A positive number will be the upper boundary and a negative number will be the lower boundary.
Returns: An array containing the cleaned series.
clean(src, len, maxDeviation) Returns an array representing the source series with outliers removed.
Parameters:
src : The source series to read from.
len : The maximum size of the resultant array.
maxDeviation : The positive or negative multiple of the standard deviation to apply to the average. A positive number will be the upper boundary and a negative number will be the lower boundary.
Returns: An array containing the cleaned series.
outlierLevelAdjusted(src, level, len, maxDeviation) Gets the (standard deviation) outlier level for a given series after a single pass of removing any outliers.
Parameters:
src : The series to average and add a multiple of the standard deviation to.
level : The positive or negative multiple of the standard deviation to apply to the average. A positive number will be the upper boundary and a negative number will be the lower boundary.
len : The The number of bars to measure.
maxDeviation : The optional standard deviation level to use when cleaning the series. The default is the value of the provided level.
Returns: The average of the series plus the multiple of the standard deviation.
LeoLibraryLibrary "LeoLibrary"
A collection of custom tools & utility functions commonly used with my scripts
getDecimals() Calculates how many decimals are on the quote price of the current market
Returns: The current decimal places on the market quote price
truncate(float, float) Truncates (cuts) excess decimal places
Parameters:
float : _number The number to truncate
float : _decimalPlaces (default=2) The number of decimal places to truncate to
Returns: The given _number truncated to the given _decimalPlaces
toWhole(float) Converts pips into whole numbers
Parameters:
float : _number The pip number to convert into a whole number
Returns: The converted number
toPips(float) Converts whole numbers back into pips
Parameters:
float : _number The whole number to convert into pips
Returns: The converted number
av_getPositionSize(float, float, float, float) Calculates OANDA forex position size for AutoView based on the given parameters
Parameters:
float : _balance The account balance to use
float : _risk The risk percentage amount (as a whole number - eg. 1 = 1% risk)
float : _stopPoints The stop loss distance in POINTS (not pips)
float : _conversionRate The conversion rate of our account balance currency
Returns: The calculated position size (in units - only compatible with OANDA)
getMA(int, string) Gets a Moving Average based on type
Parameters:
int : _length The MA period
string : _maType The type of MA
Returns: A moving average with the given parameters
getEAP(float) Performs EAP stop loss size calculation (eg. ATR >= 20.0 and ATR < 30, returns 20)
Parameters:
float : _atr The given ATR to base the EAP SL calculation on
Returns: The EAP SL converted ATR size
barsAboveMA(int, float) Counts how many candles are above the MA
Parameters:
int : _lookback The lookback period to look back over
float : _ma The moving average to check
Returns: The bar count of how many recent bars are above the MA
barsBelowMA(int, float) Counts how many candles are below the MA
Parameters:
int : _lookback The lookback period to look back over
float : _ma The moving average to reference
Returns: The bar count of how many recent bars are below the EMA
barsCrossedMA(int, float) Counts how many times the EMA was crossed recently
Parameters:
int : _lookback The lookback period to look back over
float : _ma The moving average to reference
Returns: The bar count of how many times price recently crossed the EMA
getPullbackBarCount(int, int) Counts how many green & red bars have printed recently (ie. pullback count)
Parameters:
int : _lookback The lookback period to look back over
int : _direction The color of the bar to count (1 = Green, -1 = Red)
Returns: The bar count of how many candles have retraced over the given lookback & direction
getBodySize() Gets the current candle's body size (in POINTS, divide by 10 to get pips)
Returns: The current candle's body size in POINTS
getTopWickSize() Gets the current candle's top wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's top wick size in POINTS
getBottomWickSize() Gets the current candle's bottom wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's bottom wick size in POINTS
getBodyPercent() Gets the current candle's body size as a percentage of its entire size including its wicks
Returns: The current candle's body size percentage
isHammer(float, bool) Checks if the current bar is a hammer candle based on the given parameters
Parameters:
float : _fib (default=0.382) The fib to base candle body on
bool : _colorMatch (default=false) Does the candle need to be green? (true/false)
Returns: A boolean - true if the current bar matches the requirements of a hammer candle
isStar(float, bool) Checks if the current bar is a shooting star candle based on the given parameters
Parameters:
float : _fib (default=0.382) The fib to base candle body on
bool : _colorMatch (default=false) Does the candle need to be red? (true/false)
Returns: A boolean - true if the current bar matches the requirements of a shooting star candle
isDoji(float, bool) Checks if the current bar is a doji candle based on the given parameters
Parameters:
float : _wickSize (default=2) The maximum top wick size compared to the bottom (and vice versa)
bool : _bodySize (default=0.05) The maximum body size as a percentage compared to the entire candle size
Returns: A boolean - true if the current bar matches the requirements of a doji candle
isBullishEC(float, float, bool) Checks if the current bar is a bullish engulfing candle
Parameters:
float : _allowance (default=0) How many POINTS to allow the open to be off by (useful for markets with micro gaps)
float : _rejectionWickSize (default=disabled) The maximum rejection wick size compared to the body as a percentage
bool : _engulfWick (default=false) Does the engulfing candle require the wick to be engulfed as well?
Returns: A boolean - true if the current bar matches the requirements of a bullish engulfing candle
isBearishEC(float, float, bool) Checks if the current bar is a bearish engulfing candle
Parameters:
float : _allowance (default=0) How many POINTS to allow the open to be off by (useful for markets with micro gaps)
float : _rejectionWickSize (default=disabled) The maximum rejection wick size compared to the body as a percentage
bool : _engulfWick (default=false) Does the engulfing candle require the wick to be engulfed as well?
Returns: A boolean - true if the current bar matches the requirements of a bearish engulfing candle
timeFilter(string, bool) Determines if the current price bar falls inside the specified session
Parameters:
string : _sess The session to check
bool : _useFilter (default=false) Whether or not to actually use this filter
Returns: A boolean - true if the current bar falls within the given time session
dateFilter(int, int) Determines if this bar's time falls within date filter range
Parameters:
int : _startTime The UNIX date timestamp to begin searching from
int : _endTime the UNIX date timestamp to stop searching from
Returns: A boolean - true if the current bar falls within the given dates
dayFilter(bool, bool, bool, bool, bool, bool, bool) Checks if the current bar's day is in the list of given days to analyze
Parameters:
bool : _monday Should the script analyze this day? (true/false)
bool : _tuesday Should the script analyze this day? (true/false)
bool : _wednesday Should the script analyze this day? (true/false)
bool : _thursday Should the script analyze this day? (true/false)
bool : _friday Should the script analyze this day? (true/false)
bool : _saturday Should the script analyze this day? (true/false)
bool : _sunday Should the script analyze this day? (true/false)
Returns: A boolean - true if the current bar's day is one of the given days
atrFilter(float, float) Checks the current bar's size against the given ATR and max size
Parameters:
float : _atr (default=ATR 14 period) The given ATR to check
float : _maxSize The maximum ATR multiplier of the current candle
Returns: A boolean - true if the current bar's size is less than or equal to _atr x _maxSize
fillCell(table, int, int, string, string, color, color) This updates the given table's cell with the given values
Parameters:
table : _table The table ID to update
int : _column The column to update
int : _row The row to update
string : _title The title of this cell
string : _value The value of this cell
color : _bgcolor The background color of this cell
color : _txtcolor The text color of this cell
Returns: A boolean - true if the current bar falls within the given dates
benchLibrary "bench"
A simple banchmark library to analyse script performance and bottlenecks.
Very useful if you are developing an overly complex application in Pine Script, or trying to optimise a library / function / algorithm...
Supports artificial looping benchmarks (of fast functions)
Supports integrated linear benchmarks (of expensive scripts)
One important thing to note is that the Pine Script compiler will completely ignore any calculations that do not eventually produce chart output. Therefore, if you are performing an artificial benchmark you will need to use the bench.reference(value) function to ensure the calculations are executed.
Please check the examples towards the bottom of the script.
Quick Reference
(Be warned this uses non-standard space characters to get the line indentation to work in the description!)
```
// Looping benchmark style
benchmark = bench.new(samples = 500, loops = 5000)
data = array.new_int()
if bench.start(benchmark)
while bench.loop(benchmark)
array.unshift(data, timenow)
bench.mark(benchmark)
while bench.loop(benchmark)
array.unshift(data, timenow)
bench.mark(benchmark)
while bench.loop(benchmark)
array.unshift(data, timenow)
bench.stop(benchmark)
bench.reference(array.get(data, 0))
bench.report(benchmark, '1x array.unshift()')
// Linear benchmark style
benchmark = bench.new()
data = array.new_int()
bench.start(benchmark)
for i = 0 to 1000
array.unshift(data, timenow)
bench.mark(benchmark)
for i = 0 to 1000
array.unshift(data, timenow)
bench.stop(benchmark)
bench.reference(array.get(data, 0))
bench.report(benchmark,'1000x array.unshift()')
```
Detailed Interface
new(samples, loops) Initialises a new benchmark array
Parameters:
samples : int, the number of bars in which to collect samples
loops : int, the number of loops to execute within each sample
Returns: int , the benchmark array
active(benchmark) Determing if the benchmarks state is active
Parameters:
benchmark : int , the benchmark array
Returns: bool, true only if the state is active
start(benchmark) Start recording a benchmark from this point
Parameters:
benchmark : int , the benchmark array
Returns: bool, true only if the benchmark is unfinished
loop(benchmark) Returns true until call count exceeds bench.new(loop) variable
Parameters:
benchmark : int , the benchmark array
Returns: bool, true while looping
reference(number, string) Add a compiler reference to the chart so the calculations don't get optimised away
Parameters:
number : float, a numeric value to reference
string : string, a string value to reference
mark(benchmark, number, string) Marks the end of one recorded interval and the start of the next
Parameters:
benchmark : int , the benchmark array
number : float, a numeric value to reference
string : string, a string value to reference
stop(benchmark, number, string) Stop the benchmark, ending the final interval
Parameters:
benchmark : int , the benchmark array
number : float, a numeric value to reference
string : string, a string value to reference
report(Prints, benchmark, title, text_size, position)
Parameters:
Prints : the benchmarks results to the screen
benchmark : int , the benchmark array
title : string, add a custom title to the report
text_size : string, the text size of the log console (global size vars)
position : string, the position of the log console (global position vars)
unittest_bench(case) Cache module unit tests, for inclusion in parent script test suite. Usage: bench.unittest_bench(__ASSERTS)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
unittest(verbose) Run the bench module unit tests as a stand alone. Usage: bench.unittest()
Parameters:
verbose : bool, optionally disable the full report to only display failures
GenericTALibrary "GenericTA"
What is it?
The real generic library. Which means it is just covering most built-in indicators / functions, but with more parameters, so the user don't have to write more few lines to achieve something simple and replicative.
Development process?
Will tidy it up, and setting up in later stage.
Welcome to inbox me to improve the library ------
If you are finding a similar thing. That's a good news. Because I am making it.
debuggerDEBUGGER is a library to help print debug messages to a console.
This library provides an easy-to-use interface to print your debugging messages to a console in the chart. Special attention has been given to printing series and arrays easily.
A debugger is a valuable tool when working on scripts and getting into trouble. Unfortunately, TradingView does not provide an interactive debugger, and does not provide a console to use the oldest trick in the debugging book: print statements. This library provides you with the latter tool, print statements.
As a bonus, the library also provides a way to show labels in the chart next to the pricing action.
For more information and examples of usage, check the description in the header comments.
logLibrary "log"
A Library to log and display messages in a table, with different colours.
The log consists of 3 columns:
Bar Index / Message / Log
Credits
QuantNomad - for his idea on logging messages as Error/Warnings and displaying the color based on the type of the message
setHeader(_t, _location, _header1, _header2, _header3, _halign, _valign, _size) Sets the header for the table to be used for displaying the logs.
Parameters:
_t : table, table to be used for printing
_location : string, Location of the table.
_header1 : string, the name to put into the Index Queue Header. Default is 'Bar #'
_header2 : string, the name to put into the Message Queue Header. Default is 'Message'
_header3 : string, the name to put into the Log Queue Header. Default is 'Log'
_halign : string, the horizontal alignment of header. Options - Left/Right/Center
_valign : string, the vertical alignment of header. Options - Top/Bottom/Center
_size : string, the size of text of header. Options - Tiny/Small/Normal/Large/Huge/Auto
Returns: Void
initHeader(_location, _rows, _header1, _header2, _header3, _halign, _valign, _size, _frameBorder, _cellBorder) Creates the table for logging.
3 columns will be displayed.
Bar Index Q / Message Q / Log Q
Parameters:
_location : string, Location of the table.
_rows : int, table size, excluding the header. Default value is 40.
_header1 : string, the name to put into the Index Queue Header. Default is 'Bar #'
_header2 : string, the name to put into the Message Queue Header. Default is 'Message'
_header3 : string, the name to put into the Log Queue Header. Default is 'Log'
_halign : string, the horizontal alignment of header. Options - Left/Right/Center
_valign : string, the vertical alignment of header. Options - Top/Bottom/Center
_size : string, the size of text of header. Options - Tiny/Small/Normal/Large/Huge/Auto
_frameBorder : int, table Frame BorderWidth. Default value is 1.
_cellBorder : int, table Cell Borders Width, Default value is 2.
Returns: table
init(_rows) Initiate array variables for logging.
Parameters:
_rows : int, table size, excluding the header. Default value is 40.
Returns: tuple, arrays - > error code Q, bar_index Q, Message Q, Log Q
log(_ec, _idx, _1, _2, _m1, _m2, _code, _prefix, _suffix) logs a message to logging queue.
Parameters:
_ec : int , Error/Codes (1-7) for colouring.
Default Colour Code is 1 - Gray, 2 - Orange, 3 - Red, 4 - Blue, 5 - Green, 6 - Cream, 7 - Offwhite
_idx : int , bar index Q. The index of current bar is logged automatically
you can add before and after this index value, whatever you choose to, via the _prefix and _suffix variables.
_1 : string , Message Q.
_2 : string , Log Q
_m1 : string, message needed to be logged to Message Q
_m2 : string, detailed log needed to be logged to Log Q
_code : int, Error/Code to be assigned. Default code is 1.
_prefix : string, prefix to Bar State Q message
_suffix : string, suffix to Bar State Q message
Order of logging would be Bar Index Q / Message Q / Log Q
Returns: void
resize(_ec, _idx, _1, _2, _rows) Resizes the all messaging queues.
a resize will delete the existing table, so a new header/table has to be initiated after the resize.
This is because pine doesnt allow changing the table dimensions once they have been recreated.
If size is decreased then removes the oldest messages
Parameters:
_ec : int , Error/Codes (1-7) for colouring.
_idx : int , bar index Q.
_1 : string , Message Q.
_2 : string , Log Q
_rows : int, the new size needed for the queue. Default value is 40.
Returns: void
print(_t, _ec, _idx, _1, _2, halign, halign, _size) Prints Bar Index Q / Message Q / Log Q
Parameters:
_t : table, table to be used for printing
_ec : int , Error/Codes (1-7) for colouring.
Default Colour Code is 1 - Gray, 2 - Orange, 3 - Red, 4 - Blue, 5 - Green, 6 - Cream, 7 - Offwhite
_idx : int , for bar index Q.
_1 : string , Message Q.
_2 : string , Log Q
halign : string, the horizontal alignment of all message column. Options - Left/Right/Center
halign : string, the vertical alignment of all message column. Options - Top/Bottom/Center
_size : string, the size of text across the table, excepr the headers. Options - Tiny/Small/Normal/Large/Huge/Auto
Returns: void
printx(_t, _idx, _1, _2, _ec, _fg, _bg, _halign, _valign, _size) Prints Bar Index Q / Message Q / Log Q, but with custom options to format the table and colours
Parameters:
_t : table, table to be used for printing
_idx : int , for bar index Q.
_1 : string , Message Q.
_2 : string , Log Q
_ec : int , Error/Codes (1-7) for colouring.
_fg : color , Color array specifying colours for foreground. Maximum length is seven. Need not provide all seven, but atleast one. If not enough provided then last colour in the array is used for missing codes
_bg : color , Same as fg.
_halign : string, the horizontal alignment of all message column. Options - Left/Right/Center
_valign : string, the vertical alignment of all message column. Options - Top/Bottom/Center
_size : string, the size of text across the table, excepr the headers. Options - Tiny/Small/Normal/Large/Huge/Auto
Returns: void
flush(_t, _idx, _1, _2, _ec) Clears queues of existing messages, filling with blanks and 0
Parameters:
_t : table, table to be flushed
_idx : int , for bar index Q.
_1 : string , Message Q.
_2 : string , Log Q
_ec : int , Error/Codes (1-7) for colouring.
Returns: void.
erase(_idx, _1, _2, _ec) Deletes message queue and the table used for displaying the queue
Parameters:
_idx : int , for bar index Q.
_1 : string , Message Q.
_2 : string , Log Q
_ec : int , Error/Codes (1-7) for colouring.
Returns: void
PivotPointsDailyTraditionalLibrary "PivotPointsDailyTraditional"
Provides the traditional daily pivot values and a pivot vacinity function.
P(level, daysPrior) Returns the P value.
Parameters:
level : The level to caclulate.
daysPrior : The number of days in the past to do the calculation.
R(level, daysPrior) Calculates the R value for a given pivot level.
Parameters:
level : The level to caclulate.
daysPrior : The number of days in the past to do the calculation.
S(level, daysPrior) Calculates the S value for a given pivot level.
Parameters:
level : The level to caclulate.
daysPrior : The number of days in the past to do the calculation.
vacinity(value, daysPrior, maxLevel) Returns a value representing where the provided value is in relation to each pivot level.
Parameters:
value : The value to compare against.
daysPrior : The number of days in the past to do the calculation.
maxLevel : The maximum number of pivot levels to include.
DailyLevelsLibrary "DailyLevels"
Functions for acquiring daily timeframe data by number of prior days.
openD(daysPrior, spec, res) Gets the open for the number of days prior.
Parameters:
daysPrior : Number of days back to get the open from.
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = '1440').
Returns: The open for the number of days prior.
highD(daysPrior, extraForward, spec, res) Gets the highest value for the number of days prior.
Parameters:
daysPrior : Number of days back to get the high from.
extraForward : Number of extra days forward to include.
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = '1440').
Returns: The high for the number of days prior.
lowD(daysPrior, extraForward, spec, res) Gets the lowest value for the number of days prior.
Parameters:
daysPrior : Number of days back to get the low from.
extraForward : Number of extra days forward to include.
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = '1440').
Returns: The low for the number of days prior.
closeD(daysPrior, spec, res) Gets the close for the number of days prior.
Parameters:
daysPrior : Number of days back to get the open from. 0 produces the current close
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = '1440').
Returns: The close for the number of days prior.
hlc3D(daysPrior, extraForward, spec, res) Gets the HLC3 value for the number of days prior.
Parameters:
daysPrior : Number of days back to get the HLC3 from.
extraForward : Number of extra days forward to include. Determines the closing value.
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = '1440').
Returns: The HLC3 for the number of days prior.
HurstExponentLibrary "HurstExponent"
Library to calculate Hurst Exponent refactored from Hurst Exponent - Detrended Fluctuation Analysis
demean(src) Calculates a series subtracted from the series mean.
Parameters:
src : The series used to calculate the difference from the mean (e.g. log returns).
Returns: The series subtracted from the series mean
cumsum(src, length) Calculates a cumulated sum from the series.
Parameters:
src : The series used to calculate the cumulative sum (e.g. demeaned log returns).
length : The length used to calculate the cumulative sum (e.g. 100).
Returns: The cumulative sum of the series as an array
aproximateLogScale(scale, length) Calculates an aproximated log scale. Used to save sample size
Parameters:
scale : The scale to aproximate.
length : The length used to aproximate the expected scale.
Returns: The aproximated log scale of the value
rootMeanSum(cumulativeSum, barId, numberOfSegments) Calculates linear trend to determine error between linear trend and cumulative sum
Parameters:
cumulativeSum : The cumulative sum array to regress.
barId : The barId for the slice
numberOfSegments : The total number of segments used for the regression calculation
Returns: The error between linear trend and cumulative sum
averageRootMeanSum(cumulativeSum, barId, length) Calculates the Root Mean Sum Measured for each block (e.g the aproximated log scale)
Parameters:
cumulativeSum : The cumulative sum array to regress and determine the average of.
barId : The barId for the slice
length : The length used for finding the average
Returns: The average root mean sum error of the cumulativeSum
criticalValues(length) Calculates the critical values for a hurst exponent for a given length
Parameters:
length : The length used for finding the average
Returns: The critical value, upper critical value and lower critical value for a hurst exponent
slope(cumulativeSum, length) Calculates the hurst exponent slope measured from root mean sum, scaled to log log plot using linear regression
Parameters:
cumulativeSum : The cumulative sum array to regress and determine the average of.
length : The length used for the hurst exponent sample size
Returns: The slope of the hurst exponent
smooth(src, length) Smooths input using advanced linear regression
Parameters:
src : The series to smooth (e.g. hurst exponent slope)
length : The length used to smooth
Returns: The src smoothed according to the given length
exponent(src, hurstLength) Wrapper function to calculate the hurst exponent slope
Parameters:
src : The series used for returns calculation (e.g. close)
hurstLength : The length used to calculate the hurst exponent (should be greater than 50)
Returns: The src smoothed according to the given length
SessionInfoLibrary "SessionInfo"
Utility functions for session specific information like the bar index of the session.
inSession(spec) Returns true if the current bar is in the session specification.
Parameters:
spec : session.regular (default), session.extended or other time spec.
Returns: True if the current is in session; otherwise false.
minutesToLen(minutes, multiple) Converts the number of minutes to a length to be used with indicators.
Parameters:
minutes : The number of minutes.
multiple : The length multiplier.
Returns: math.ceil(minutes * multiple / timeframe.multiplier)
bar(spec, res) Returns the intraday bar index. May not always map directly to time as a bars can be skipped.
Parameters:
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = "1440").
Returns: The integer index of the bar of the session.
isFirstBar(spec, res) Returns true if the current bar is the first one of the session.
Parameters:
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = "1440").
Returns: True if the current bar is the first one of the session.
wasLastBar(spec, res) Returns Returns true if the previous bar was the last of the session.
Parameters:
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = "1440").
Returns: True if was the last bar of the session.
MomentsLibrary "Moments"
Based on Moments (Mean,Variance,Skewness,Kurtosis) . Rewritten for Pinescript v5.
logReturns(src) Calculates log returns of a series (e.g log percentage change)
Parameters:
src : Source to use for the returns calculation (e.g. close).
Returns: Log percentage returns of a series
mean(src, length) Calculates the mean of a series using ta.sma
Parameters:
src : Source to use for the mean calculation (e.g. close).
length : Length to use mean calculation (e.g. 14).
Returns: The sma of the source over the length provided.
variance(src, length) Calculates the variance of a series
Parameters:
src : Source to use for the variance calculation (e.g. close).
length : Length to use for the variance calculation (e.g. 14).
Returns: The variance of the source over the length provided.
standardDeviation(src, length) Calculates the standard deviation of a series
Parameters:
src : Source to use for the standard deviation calculation (e.g. close).
length : Length to use for the standard deviation calculation (e.g. 14).
Returns: The standard deviation of the source over the length provided.
skewness(src, length) Calculates the skewness of a series
Parameters:
src : Source to use for the skewness calculation (e.g. close).
length : Length to use for the skewness calculation (e.g. 14).
Returns: The skewness of the source over the length provided.
kurtosis(src, length) Calculates the kurtosis of a series
Parameters:
src : Source to use for the kurtosis calculation (e.g. close).
length : Length to use for the kurtosis calculation (e.g. 14).
Returns: The kurtosis of the source over the length provided.
skewnessStandardError(sampleSize) Estimates the standard error of skewness based on sample size
Parameters:
sampleSize : The number of samples used for calculating standard error.
Returns: The standard error estimate for skewness based on the sample size provided.
kurtosisStandardError(sampleSize) Estimates the standard error of kurtosis based on sample size
Parameters:
sampleSize : The number of samples used for calculating standard error.
Returns: The standard error estimate for kurtosis based on the sample size provided.
skewnessCriticalValue(sampleSize) Estimates the critical value of skewness based on sample size
Parameters:
sampleSize : The number of samples used for calculating critical value.
Returns: The critical value estimate for skewness based on the sample size provided.
kurtosisCriticalValue(sampleSize) Estimates the critical value of kurtosis based on sample size
Parameters:
sampleSize : The number of samples used for calculating critical value.
Returns: The critical value estimate for kurtosis based on the sample size provided.
LabelHelperLibrary "LabelHelper"
Utility for managing active labels on the chart.
add(level, txt, labelColor, textColor) For displaying a lable at the last bar.
Parameters:
level : The value to display the label at.
txt : The text to show on the label.
labelColor : The color of the label.
textColor : The text color of the label.
Returns: The label being managed.
pNRTRLibrary "pNRTR"
Provides functions for calculating Nick Rypock Trailing Reverse (NRTR) trend values with higher precision offsets for both low, and high points rather than the standard single offset.
pnrtr(float low_offset = 0.2, float high_offset = 0.2, float value = close)
low_offset
Offset used for nrtr low_point calculations. Default is 0.2.
high_offset
Offset used for nrtr high_point calculations. Default is 0.2.
value
Variable used for nrtr point calculations. Default is close.
FunctionArrayMaxSubKadanesAlgorithmLibrary "FunctionArrayMaxSubKadanesAlgorithm"
Implements Kadane's maximum sum sub array algorithm.
size(samples) Kadanes algorithm.
Parameters:
samples : float array, sample data values.
Returns: float.
indices(samples) Kadane's algorithm with indices.
Parameters:
samples : float array, sample data values.
Returns: tuple with format .
cacheLibrary "cache"
A simple cache library to store key value pairs.
Fed up of injecting and returning so many values all the time?
Want to separate your code and keep it clean?
Need to make an expensive calculation and use the results in numerous places?
Want to throttle calculations or persist random values across bars or ticks?
Then you've come to the right place. Or not! Up to you, I don't mind either way... ;)
Check the helpers and unit tests in the script for further detail.
Detailed Interface
init(persistant) Initialises the syncronised cache key and value arrays
Parameters:
persistant : bool, toggles data persistance between bars and ticks
Returns: [string , float ], a tuple of both arrays
set(keys, values, key, value) Sets a value into the cache
Parameters:
keys : string , the array of cache keys
values : float , the array of cache values
key : string, the cache key to create or update
value : float, the value to set
has(keys, values, key) Checks if the cache has a key
Parameters:
keys : string , the array of cache keys
values : float , the array of cache values
key : string, the cache key to check
Returns: bool, true only if the key is found
get(keys, values, key) Gets a keys value from the cache
Parameters:
keys : string , the array of cache keys
values : float , the array of cache values
key : string, the cache key to get
Returns: float, the stored value
remove(keys, values, key) Removes a key and value from the cache
Parameters:
keys : string , the array of cache keys
values : float , the array of cache values
key : string, the cache key to remove
count() Counts how many key value pairs in the cache
Returns: int, the total number of pairs
loop(keys, values) Returns true for each value in the cache (use as the while loop expression)
Parameters:
keys : string , the array of cache keys
values : float , the array of cache values
next(keys, values) Returns each key value pair on successive calls (use in the while loop)
Parameters:
keys : string , the array of cache keys
values : float , the array of cache values
Returns: , tuple of each key value pair
clear(keys, values) Clears all key value pairs from the cache
Parameters:
keys : string , the array of cache keys
values : float , the array of cache values
unittest_cache(case) Cache module unit tests, for inclusion in parent script test suite. Usage: log.unittest_cache(__ASSERTS)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
unittest(verbose) Run the cache module unit tests as a stand alone. Usage: cache.unittest()
Parameters:
verbose : bool, optionally disable the full report to only display failures