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
Göstergeler ve stratejiler
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
logLibrary "log"
Logging library for easily displaying debug, info, warn, error and critical messages.
No real need to explain why you might want to use this library! I'm sure you've all experienced the frustration of trying to understand the data state of your scripts... so, enjoy! More on it's way...
(Don't forget to check the helpers in the script and the useful tips below)
Some Useful Tips
By default the log console persists between bars (for history) and bars and ticks (for realtime).
Sometimes it is useful to clear the log after each candle or tick (assuming we are using the above helpers):
```
log_print(clear = true) // starts afresh on every bar and tick (excludes historical bars but good realtime tick analysis)
log_print(clear = barstate.isnew) // clears the log at the start of each bar (again, excludes historical but good realtime candle analysis)
```
It is also useful to be able to selectively understand the state of data at specific points or times within a script:
```
if log.once()
debug('useful variable', my_var) // this log only gets written once, upon first execution of this statement
if log.only(5)
debug3(a, b, c) // these variables are only logged the first five times this statement is executed
log_print(clear = false) // clear must be false and you should not write other logs on every bar, or the above will be lost
```
Final tip. If you want to view ONLY log entries of a particular level, then negate the constant:
```
log_print(level = -LOG_DEBUG)
```
Detailed Interface
once() Restrict execution to only happen once. Usage: if assert.once() happens_once()
Returns: bool, true on first execution within scope, false subsequently
only(repeat) Restrict execution to happen a set number of times. Usage: if assert.only(5) happens_five_times()
Parameters:
repeat : int, the number of times to return true
Returns: bool, true for the set number of times within scope, false subsequently
init() Initialises the log array
Returns: string , tuple based array to contain all pending log entries (__LOG)
clear(msgs) Clears the log array
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
trace(msgs, msg) Writes a trace message to the log console
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
msg : string, the trace message to write to the log
debug(msgs, msg) Writes a debug message to the log console
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
msg : string, the debug message to write to the log
info(msgs, msg) Writes an info message to the log console
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
msg : string, the info message to write to the log
warn(msgs, msg) Writes a warning message to the log console
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
msg : string, the warn message to write to the log
error(msgs, msg) Writes an error message to the log console
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
msg : string, the error message to write to the log
fatal(msgs, msg) Writes a critical message to the log console
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
msg : string, the fatal message to write to the log
log(msgs, level, msg) Write a log message to the log console with a custom level
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
level : ing, the logging level to assign to the message
msg : string, the log message to write to the log
severity(msgs) Checks the unprocessed log messages and returns the highest present level
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
Returns: int, the highest level found within the unfiltered logs
print(msgs, level, clear, rows, text_size, position) Prints all log messages to the screen
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
level : int, the minimum required log level of each message to be displayed
clear : bool, clear the printed log console after each render (useful with realtime when set to barstate.isconfirmed)
rows : int, the number of rows to display in the log console
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_log(case) Log module unit tests, for inclusion in parent script test suite. Usage: log.unittest_log(__ASSERTS)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
unittest(verbose) Run the log module unit tests as a stand alone. Usage: log.unittest()
Parameters:
verbose : bool, optionally disable the full report to only display failures
customcandlesLibrary "customcandles"
customcandles: Contains methods which can send custom candlesticks based on the input
macandles(maType, length, o, h, l, c) macandles: Provides OHLC of moving average candles
Parameters:
maType : - Moving average Type. Can be sma, ema, hma, rma, wma, vwma, swma, linreg, median
length : - Defaulted to 20. Can chose custom length
o : - Optional different open source. By default is set to open
h : - Optional different high source. By default is set to high
l : - Optional different low source. By default is set to low
c : - Optional different close source. By default is set to close
Returns: : Custom Moving Average based OHLC values
hacandles() hacandles: Provides Heikin Ashi OHLC values
Returns: : Custom Heikin Ashi OHLC values
ocandles(type, length, shortLength, longLength, method, highlowLength, sticky, percentCandles) macandles: Provides OHLC of moving average candles
Parameters:
type : - Oscillator Type. Can be cci, cmo, cog, mfi, roc, rsi, tsi, mfi
length : - Defaulted to 14. Can chose custom length
shortLength : - Used only for TSI. Default is 13
longLength : - Used only for TSI. Default is 25
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
percentCandles : - candles are generated based on percent with respect to high/low instead of actual oscillator values
Returns: : Custom Moving Average based OHLC values
DiscordWebhookFunctionLibrary "DiscordWebhookFunction"
discordMarkdown(_str, _italic, _bold, _code, _strike, _under) Convert string to markdown formatting User can combine any function at the same time.
Parameters:
_str : String input
_italic : Italic
_bold : Bold
_code : Code markdown
_strike : Strikethrough
_under : Underline
Returns: string Markdown formatted string.
discordWebhookJSON(_username, _avatarImgUrl, _contentText, _bodyTitle, _descText, _bodyUrl, _embedCol, _timestamp, _authorName, _authorUrl, _authorIconUrl, _footerText, _footerIconUrl, _thumbImgUrl, _imageUrl) Convert data to JSON format for Discord Webhook Integration.
Parameters:
_username : Override bot (webhook) username string / name,
_avatarImgUrl : Override bot (webhook) avatar by image URL,
_contentText : Main content page message,
_bodyTitle : Custom Webhook's embed message body title,
_descText : Webhook's embed message body description,
_bodyUrl : Webhook's embed body direct link URL,
_embedCol : Webhook's embed color,
_timestamp : Timestamp,
_authorName : Webhook's embed author name / title,
_authorUrl : Webhook's embed author direct link URL,
_authorIconUrl : Webhook's embed author icon by image URL,
_footerText : Webhook's embed footer text / title,
_footerIconUrl : Webhook's embed footer icon by image URL,
_thumbImgUrl : Webhook's embed thumbnail image URL,
_imageUrl : Webhook's embed body image URL.
Returns: string Single-line JSON format
assertLibrary "assert"
Production ready assertions and auto-reporting for unit testing pine scripts.
This library was born from the need to maintain production level stability and catch regressions / bugs early and fast. I hope this help you trust your pine scripts too. More libraries and tools on their way... please follow for more.
Please see the script for helpers to copy into your own scripts as well as examples at the bottom of the library unit testing itself.
Quick Reference
```
case = assert.init()
new_case(case, 'Asserts for floats and ints')
assert.equal(a, b, case, 'a == b')
assert.not_equal(a, b, case, 'a != b')
assert.nan(a, case, 'a == na')
assert.not_nan(a, case, 'a != na')
assert.is_in(a, b, case, 'a in b ')
assert.is_not_in(a, b, case, 'a not in b ')
assert.array_equal(a, b, case, 'a == b ')
new_case(case, 'Asserts for ints only')
assert.int_in(a, b, case, 'a in b ')
assert.int_not_in(a, b, case, 'a not in b ')
assert.int_array_equal(a, b, case, 'a == b ')
new_case(case, 'Asserts for bools only')
assert.is_true(a, case, 'a == true')
assert.is_false(a, case, 'a == false')
assert.bool_equal(a, b, case, 'a == b')
assert.bool_not_equal(a, b, case, 'a != b')
assert.bool_nan(a, case, 'a == na')
assert.bool_not_nan(a, case, 'a != na')
assert.bool_array_equal(a, b, case, 'a == b ')
new_case(case, 'Asserts for strings only')
assert.str_equal(a, b, case, 'a == b')
assert.str_not_equal(a, b, case, 'a != b')
assert.str_nan(a, case, 'a == na')
assert.str_not_nan(a, case, 'a != na')
assert.str_in(a, b, case, 'a in b ')
assert.str_not_in(a, b, case, 'a not in b ')
assert.str_array_equal(a, b, case, 'a == b ')
assert.report(case)
```
Detailed Interface
once() Restrict execution to only happen once. Usage: if assert.once() happens_once()
Returns: bool, true on first execution within scope, false subsequently
init() Initialises the asserts array
Returns: string , tuple based array containing all unit test results and current case details (__ASSERTS)
equal(a, b, case, name) Numeric assert equal. Usage: assert.equal(1, 1, case, 'one == one')
Parameters:
a : float, numeric value "a" to compare equal to "b"
b : float, numeric value "b" to compare equal to "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
not_equal(a, b, case, name) Numeric assert not equal. Usage: assert.not_equal(1, 2, case, 'one != two')
Parameters:
a : float, numeric value "a" to compare not equal "b"
b : float, numeric value "b" to compare not equal "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
nan(a, case, name) Numeric assert is NaN. Usage: assert.nan(float(na), case, 'number is NaN')
Parameters:
a : float, numeric value "a" to check is NaN
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
not_nan(a, case, name) Numeric assert is not NaN. Usage: assert.not_nan(1, case, 'number is not NaN')
Parameters:
a : float, numeric value "a" to check is not NaN
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
is_in(a, b, case, name) Numeric assert value in float array. Usage: assert.is_in(1, array.from(1.0), case, '1 is in ')
Parameters:
a : float, numeric value "a" to check is in array "b"
b : float , array "b" to check contains "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
is_not_in(a, b, case, name) Numeric assert value not in float array. Usage: assert.is_not_in(2, array.from(1.0), case, '2 is not in ')
Parameters:
a : float, numeric value "a" to check is not in array "b"
b : float , array "b" to check does not contain "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
array_equal(a, b, case, name) Float assert arrays are equal. Usage: assert.array_equal(array.from(1.0), array.from(1.0), case, ' == ')
Parameters:
a : float , array "a" to check is identical to array "b"
b : float , array "b" to check is identical to array "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
int_in(a, b, case, name) Integer assert value in integer array. Usage: assert.int_in(1, array.from(1), case, '1 is in ')
Parameters:
a : int, value "a" to check is in array "b"
b : int , array "b" to check contains "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
int_not_in(a, b, case, name) Integer assert value not in integer array. Usage: assert.int_not_in(2, array.from(1), case, '2 is not in ')
Parameters:
a : int, value "a" to check is not in array "b"
b : int , array "b" to check does not contain "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
int_array_equal(a, b, case, name) Integer assert arrays are equal. Usage: assert.int_array_equal(array.from(1), array.from(1), case, ' == ')
Parameters:
a : int , array "a" to check is identical to array "b"
b : int , array "b" to check is identical to array "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
is_true(a, case, name) Boolean assert is true. Usage: assert.is_true(true, case, 'is true')
Parameters:
a : bool, value "a" to check is true
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
is_false(a, case, name) Boolean assert is false. Usage: assert.is_false(false, case, 'is false')
Parameters:
a : bool, value "a" to check is false
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
bool_equal(a, b, case, name) Boolean assert equal. Usage: assert.bool_equal(true, true, case, 'true == true')
Parameters:
a : bool, value "a" to compare equal to "b"
b : bool, value "b" to compare equal to "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
bool_not_equal(a, b, case, name) Boolean assert not equal. Usage: assert.bool_not_equal(true, false, case, 'true != false')
Parameters:
a : bool, value "a" to compare not equal "b"
b : bool, value "b" to compare not equal "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
bool_nan(a, case, name) Boolean assert is NaN. Usage: assert.bool_nan(bool(na), case, 'bool is NaN')
Parameters:
a : bool, value "a" to check is NaN
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
bool_not_nan(a, case, name) Boolean assert is not NaN. Usage: assert.bool_not_nan(true, case, 'bool is not NaN')
Parameters:
a : bool, value "a" to check is not NaN
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
bool_array_equal(a, b, case, name) Boolean assert arrays are equal. Usage: assert.bool_array_equal(array.from(true), array.from(true), case, ' == ')
Parameters:
a : bool , array "a" to check is identical to array "b"
b : bool , array "b" to check is identical to array "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
str_equal(a, b, case, name) String assert equal. Usage: assert.str_equal('hi', 'hi', case, '"hi" == "hi"')
Parameters:
a : string, value "a" to compare equal to "b"
b : string, value "b" to compare equal to "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
str_not_equal(a, b, case, name) String assert not equal. Usage: assert.str_not_equal('hi', 'bye', case, '"hi" != "bye"')
Parameters:
a : string, value "a" to compare not equal "b"
b : string, value "b" to compare not equal "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
str_nan(a, case, name) String assert is NaN. Usage: assert.str_nan(string(na), case, 'string is NaN')
Parameters:
a : string, value "a" to check is NaN
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
str_not_nan(a, case, name) String assert is not NaN. Usage: assert.str_not_nan('hi', case', 'string is not NaN')
Parameters:
a : string, value "a" to check is not NaN
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
str_in(a, b, case, name) String assert value in string array. Usage: assert.str_in('hi', array.from('hi'), case, '"hi" in ')
Parameters:
a : string, value "a" to check is in array "b"
b : string , array "b" to check contains "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
str_not_in(a, b, case, name) String assert value not in string array. Usage: assert.str_in('hi', array.from('bye'), case, '"hi" in ')
Parameters:
a : string, value "a" to check is not in array "b"
b : string , array "b" to check does not contain "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
str_array_equal(a, b, case, name) String assert arrays are equal. Usage: assert.str_array_equal(array.from('hi'), array.from('hi'), case, ' == ')
Parameters:
a : string , array "a" to check is identical to array "b"
b : string , array "b" to check is identical to array "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
new_case(case, name) Assign a new test case name, for the next set of unit tests. Usage: assert.new_case(case, 'My tests')
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the case name for the next suite of tests
clear(case) Clear all stored unit tests from all cases. Usage: assert.clear(case)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
revert(case) Revert the previous unit test. Usage: = assert.revert(case)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
Returns: , tuple containing the msg and result of the reverted test
passed(case, revert) Check if the last unit test has passed. Usage: bool success = assert.passed(case)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
revert : bool, optionally revert the test
Returns: bool, true only if the test passed
failed(case, revert) Check if the last unit test has failed. Usage: bool failure = assert.failed(case)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
revert : bool, optionally revert the test
Returns: bool, true only if the test failed
report(case, verbose) Report the outcome of unit tests that fail. Usage: bool passed = assert.report(case)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
verbose : bool, optionally display full report that includes the outcome of all tests
Returns: bool, true only if all tests passed
unittest_assert(case) Assert module unit tests, for inclusion in parent script test suite. Usage: assert.unittest_assert(__ASSERTS)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
unittest(verbose) Run the assert module unit tests as a stand alone. Usage: assert.unittest()
Parameters:
verbose : bool, optionally toggle report to display the outcome of all unit tests
CandleEvaluationLibrary "CandleEvaluation"
Contains functions to evaluate bullish and bearish, engulfing, and outsized candles. They are different from the built-in indicators from TradingView in that these functions don't evaluate classical patterns composed of multiple candles, and they reflect my own understanding of what is "bullish" and bearish", "engulfing", and "outsized".
isBullishBearishCandle()
Determines if the current candle is bullish or bearish according to the length of the wicks and the open and close.
int _barsBack How many bars back is the candle you want to evaluate. By default this is 0, i.e., the current bar.
returns Two values, true or false, for whether it's a bullish or bearish candle respectively.
isTripleBull()
Tells you whether a candle is a "Triple Bull" - that is, one which is bullish in three ways:
It closes higher than it opens
It closes higher than the body of the previous candle
The High is above the High of the previous candle.
int _barsBack How many bars back is the candle you want to evaluate. By default this is 0, i.e., the current bar.
returns True or false.
isTripleBear()
Tells you whether a candle is a "Triple Bear" - that is, one which is bearish in three ways:
It closes lower than it opens
It closes lower than the body of the previous candle
The Low is below the Low of the previous candle.
int _barsBack How many bars back is the candle you want to evaluate. By default this is 0, i.e., the current bar.
returns True or false.
isBigBody()
Tells you if the current candle has a larger than average body size.
int _length - The length of the sma to calculate the average
float _percent - The percentage of the average that the candle body has to be to count as "big". E.g. 100 means it has to be just larger than the average, 200 means it has to be twice as large.
returns True or false
isBullishEngulfing()
Tells you if the current candle is a bullish engulfing candle.
int _barsBack How many bars back is the candle you want to evaluate. By default this is 0, i.e., the current bar.
int _atrFraction The denominator for the ATR fraction, which is the small amount by which the open can be different from the previous close.
returns True or false
isBearishEngulfing()
Tells you if the current candle is a bearish engulfing candle.
int _barsBack How many bars back is the candle you want to evaluate. By default this is 0, i.e., the current bar.
int _atrFraction The denominator for the ATR fraction, which is the small amount by which the open can be different from the previous close.
returns True or false
ArrayMultipleDimensionPrototypeLibrary "ArrayMultipleDimensionPrototype"
A prototype library for Multiple Dimensional array methods
index_md_to_1d()
new_float(dimensions, initial_size) Creates a variable size multiple dimension array.
Parameters:
dimensions : int array, dimensions of array.
initial_size : float, default=na, initial value of the array.
Returns: float array
dimensions(id, value) set value of a element in a multiple dimensions array.
Parameters:
id : float array, multiple dimensions array.
value : float, new value.
Returns: float.
get(id) get value of a multiple dimensions array.
Parameters:
id : float array, multiple dimensions array.
Returns: float.
set(id) set value of a element in a multiple dimensions array.
Parameters:
id : float array, multiple dimensions array.
Returns: float.
FFTLibraryLibrary "FFTLibrary" contains a function for performing Fast Fourier Transform (FFT) along with a few helper functions. In general, FFT is defined for complex inputs and outputs. The real and imaginary parts of formally complex data are treated as separate arrays (denoted as x and y). For real-valued data, the array of imaginary parts should be filled with zeros.
FFT function
fft(x, y, dir) : Computes the one-dimensional discrete Fourier transform using an in-place complex-to-complex FFT algorithm . Note: The transform also produces a mirror copy of the frequency components, which correspond to the signal's negative frequencies.
Parameters:
x : float array, real part of the data, array size must be a power of 2
y : float array, imaginary part of the data, array size must be the same as x ; for real-valued input, y must be an array of zeros
dir : string, options = , defines the direction of the transform: forward" (time-to-frequency) or inverse (frequency-to-time)
Returns: x, y : tuple (float array, float array), real and imaginary parts of the transformed data (original x and y are changed on output)
Helper functions
fftPower(x, y) : Helper function that computes the power of each frequency component (in other words, Fourier amplitudes squared).
Parameters:
x : float array, real part of the Fourier amplitudes
y : float array, imaginary part of the Fourier amplitudes
Returns: power : float array of the same length as x and y , Fourier amplitudes squared
fftFreq(N) : Helper function that returns the FFT sample frequencies defined in cycles per timeframe unit. For example, if the timeframe is 5m, the frequencies are in cycles/(5 minutes).
Parameters:
N : int, window length (number of points in the transformed dataset)
Returns: freq : float array of N, contains the sample frequencies (with zero at the start).
LibraryStopwatchLibrary "LibraryStopwatch"
Provides functions to time the execution of a script.
When timing scripts, keep in mind that the runtime environment is fluid on TradingView. Different servers or server loads will impact execution time.
Look first. Then leap.
stopwatchStats() Times the execution of a script.
Returns: A tuple of four values: timePerBarInMs, totalTimeInMs, barsTimed, barsNotTimed
stopwatch() Times the execution of a script.
Returns: A single value: The time elapsed since the beginning of the script, in ms.
lib_Indicators_DTLibrary "lib_Indicators_DT"
This library functions returns some Moving averages and indicators.
Created it to feed my indicator/strategy "INDICATOR & CONDITIONS COMBINATOR FRAMEWORK v1 " which I will publish it as soon as possible.
Credits: Library includes some public indicators, snippets from tradingview & @03.freeman's ("All MAs displayed") scripts.
(I hope, I dont break Tradingview's House Rules on Script Publishing)
f_plotPrep(src_, src_, src_, src_) Prepare Indicator Plot Type
Parameters:
src_ : Source
src_ : plotingType_ "Original, Stochastic, Percent"
src_ : stochlen_ Stochasting plottingtype length
src_ : plotSWMA_ Use SWMA for the output
Returns: Return the prepared indicator
f_funcPlot(string, float, simple, string, simple, bool) f_funcPlot(string f, float src_, simple int length_, string plotingType_ = "Original", simple int stochlen_=50, bool plotSWMA=false) Return selected indicator value with different parameters
Parameters:
string : f indicator-> options=
float : src_ close,open.....
simple : int length_ indicator length
string : plotingType return param-> options= ['Original', 'Stochastic', 'PercentRank')
simple : int stochlen_ length for return Param
bool : plotSWMA Use SWMA on Plot
Returns: float
DrawIndicatorOnTheChartLibrary "DrawIndicatorOnTheChart"
this library is used to show an indicator (such RSI, CCI, MOM etc) on the main chart with indicator's horizontal lines in a window. Location of the window is calculated dynamically by last price movemements
drawIndicator(indicatorName, indicator, indicatorcolor, period, indimax_, indimin_, levels, precision, xlocation) draws the related indicator on the chart
Parameters:
indicatorName : is the indicator name as string such "RSI", "CCI" etc
indicator : is the indicator you want to show, such rsi(close, 14), mom(close, 10) etc
indicatorcolor : is the color of indicator line
period : is the length of the window to show
indimax_ : is the maximum value of the indicator, for example for RSI it's 100.0, if the indicator (such CCI, MOM etc) doesn't have maximum value then use "na"
indimin_ : is the minimum value of the indicator, for example for RSI it's 0.0, if the indicator (such CCI, MOM etc)doesn't have maximum value then use "na"
levels : is the levels of the array for the horizontal lines. for example if you want horizontal lines at 30.0, and 70.0 then use array.from(30.0, 70.0). if no horizontal lines then use array.from(na)
precision : is the precision/number of decimals that is used to show indicator values, for example for RSI set it 2
xlocation : is end location of the indicator window, for example if xlocation = 0 window is created on the index of the last bar/candle
Returns: none