_lib_MilitzerThis is a collection of functions either found on the internet, or made by me.
This is only public so my other scripts that reference this can also be public.
If you find anything useful for you here, be my guest.
Debugging
consoleLibrary "console"
Simple debug console to print messages from your strategy code.
USAGE :
Make sure your strategy overlay is false
Import the library :
import keio/console/1 as console
init(lines, panes)
Initialise function.
USAGE :
var log = console.init()
Parameters:
lines : Optional. Number of lines to display
panes : Optional. Number of panes to display
Returns: initialised log
print(log)
Prints a message to the console.
USAGE :
log := console.print(log, "message")
Parameters:
log : Mandatory. The log returned from the init() function
Returns: The log
okhan_commonThis is a draft version of a library intended to clean up my other indicators, thats why probably it won't be heplful for others, and I won't focus on documenting it at the moment.
However, if by any chance you plan to use this library, let me know if you need me to document anything.
lib_MilitzerLibrary "lib_Militzer"
// This is a collection of functions either found on the internet, or made by me.
// This is only public so my other scripts that reference this can also be public.
// But if you find anything useful here, be my guest.
print()
strToInt()
timeframeToMinutes()
easytableLibrary "easytable"
Create tables easily, with minimal code
▦ FEATURES ▦
█ Create tables █ JSON To Table █ Change Colors █ Array to Rows/Columns █ Pre-Styles █ Change Text Size █ Delete Rows/Columns █ Blink Cells
indentify_table_id() Identifies all tables ID number in each cell(0,0).
get_table_by_id(id_number) Get table object by ID number.
Parameters:
id_number : (int) ID number of the table to fetch.
Returns: table.
change_cells_color(table_object, cells_color, start_column, end_column, start_row, end_row) Change cells background colors.
Parameters:
table_object : (table) table object to be changed.
cells_color : (color) Cells color.
start_column : (int) Start column.
end_column : (int) End column.
start_row : (int) Start Row.
end_row : (int) End Row to change.
Returns: Void.
change_cells_text_color(table_object, text_color, start_column, end_column, start_row, end_row) Change cells text colors.
Parameters:
table_object : (table) table object to be changed.
text_color : (color) Text color.
start_column : (int) Start column.
end_column : (int) End column.
start_row : (int) Start Row.
end_row : (int) End Row.
Returns: Void.
change_all_table_text_color(table_object, text_color, table_column_size, table_row_size) Change All table text color.
Parameters:
table_object : (table) table object to be changed.
text_color : (color) Text color.
table_column_size : (int) Size of the table columns.
table_row_size : (int) Size of the table rows.
Returns: Void.
change_table_size(table_object, n_of_columns, n_of_rows, tbl_size) Change table size.
Parameters:
table_object : (table) table object to be changed.
n_of_columns : (int) Size of the table columns.
n_of_rows : (int) Size of the table rows.
tbl_size : (string) size of the table.
Returns: Void.
change_cells_text_size(text_size, start_column, end_column, start_row, end_row, table_id) Change table cells text size .
Parameters:
text_size : (string) Text size.
start_column : (int) Start column.
end_column : (int)(optional) End column.
start_row : (int)(optional) Start Row.
end_row : (int)(optional) End Row.
table_id : (int)(optional) Number of the ID of the table.
Returns: Void.
table_delete_row(table_object, table_column_size, start_row, end_row) Delete specified rows from table.
Parameters:
table_object : (table) table object to be changed.
table_column_size : (int) Table columns max size.
start_row : (int) Start row to delete.
end_row : (int)(optional) End row to delete (optional — Assumes start_row value).
Returns: Void.
table_delete_column(table_object, table_row_size, start_column, end_column) Delete specified columns from table.
Parameters:
table_object : (table) table object to be changed.
table_row_size : (int) Table rows max size.
start_column : (int) Start column to delete.
end_column : (int)(optional) End column to delete (optional — Assumes start_column value).
Returns: Void.
array_to_table_column_auto(column_to_insert, array_to_insert, table_id) Insert string array to table column without passing table object.
Parameters:
column_to_insert : (int) Column to be inserted.
array_to_insert : (string array) Start column to delete.
table_id : (int)(optional) Number of the ID of the table.
Returns: Void.
array_to_table_row_auto(row_to_insert, array_to_insert, table_id) Insert string array to table row without passing table object.
Parameters:
row_to_insert : (int) Column to be inserted.
array_to_insert : (string array) Start column to delete.
table_id : (int)(optional) Number of the ID of the table.
Returns: Void.
array_to_table_row(table_object, row_to_insert, array_to_insert) Insert string array to table row by passing table object.
Parameters:
table_object : (table) table object to be changed.
row_to_insert : (int) Row to be inserted.
array_to_insert : (string array) Start column to delete.
Returns: Void.
array_to_table_column(table_object, column_to_insert, array_to_insert) Insert string array to table column by passing table object.
Parameters:
table_object : (table) table object to be changed.
column_to_insert : (int) Column to be inserted.
array_to_insert : (string array) Start column to delete.
Returns: Void.
blink_cell(cell_column, cell_row, c_color, blink_interval_ms, table_id) Changes cell color at set intervals (blink).
Parameters:
cell_column : (int) Cell column position.
cell_row : (int) Cell row position.
c_color : (color) Color to blink.
blink_interval_ms : (int)(opt) Interval in milliseconds.
table_id : (int)(opt) Table ID number.
change_table_style(table_object, number_of_columns, number_of_rows, color) Changes table pre-style by selecting a pre-style number.
Parameters:
table_object : (table) table object to be changed.
number_of_columns : (int) Table column size.
number_of_rows : (int) Table row size.
color : 1 (color) Color of .
Returns: Void.
create_table_clean(n_of_columns, n_of_rows, position) Create a simple(blank) table without any styling.
Parameters:
n_of_columns : (int) Numbers of columns in the table.
n_of_rows : (int) Number of rows in the table.
position : (string) table position.
Returns: table object.
create_table_with_style(n_of_columns, n_of_rows, style_number, position) Create table with a pre-set style.
Parameters:
n_of_columns : (int) Numbers of columns in the table.
n_of_rows : (int) Number of rows in the table.
style_number : (int) Style number.
position : (string) table position.
Returns: table object.
json_to_table(raw_json) Create table based on input raw json string.
Parameters:
raw_json : (int) Raw json string.
Returns: table object.
json_example() Example function that display a table based on a json
example_create_table()
Logger Library For Pinescript (Logging and Debugging)Library "LoggerLib"
This is a logging library for Pinescript. It is aimed to help developers testing and debugging scripts with a simple to use logger function.
Pinescript lacks a native logging implementation. This library would be helpful to mitigate this insufficiency.
This library uses table to print outputs into its view. It is simple, customizable and robust.
You can start using it's .log() method just like any other logging method in other languages.
//////////////////
USAGE
//////////////////
-- Recommended: Please Read The Documentation From Source Code Below. It Is Much More Readable There And Will Be Updated Along With Newer Versions. --
Importing the Library
---------------------
import paragjyoti2012/LoggerLib/ as Logger
.init() : Initializes the library and returns the logger pointer. (Later will be used as a function parameter)
.initTable: Initializes the Table View for the Logger and returns the table id. (Later will be used as a function parameter)
parameters:
logger: The logger pointer got from .init()
max_rows_count: Number of Rows to display in the Logger Table (default is 10)
offset: The offset value for the rows (Used for scrolling the view)
position: Position of the Table View
Values could be:
left
right
top-right
(default is left)
size: Font Size of content
Values could be:
small
normal
large
(default is small)
hide_date: Whether to hide the Date/Time column in the Logger (default is false)
returns: Table
example usage of .initTable()
import paragjyoti2012/LoggerLib/1 as Logger
var logger=Logger.init()
var logTable=Logger.initTable(logger, max_rows_count=20, offset=0, position="top-right")
-------------------
LOGGING
-------------------
.log() : Logging Method
params: (string message, |string| logger, table table_id, string type="message")
logger: pass the logger pointer from .init()
table_id: pass the table pointer from .initTable()
message: The message to log
type: Type of the log message
Values could be:
message
warning
error
info
success
(default is message)
returns: void
///////////////////////////////////////
Full Boilerplate For Using In Indicator
///////////////////////////////////////
P.S: Change the | (pipe) character into square brackets while using in script (or copy it from the source code instead)
offset=input.int(0,"Offset",minval=0)
size=input.string("small","Font Size",options=|"normal","small","large"|)
rows=input.int(15,"No Of Rows")
position=input.string("left","Position",options=|"left","right","top-right"|)
hide_date=input.bool(false,"Hide Time")
import paragjyoti2012/LoggerLib/1 as Logger
var logger=Logger.init()
var logTable=Logger.initTable(logger,rows,offset,position,size,hide_date)
rsi=ta.rsi(close,14)
|macd,signal,hist|=ta.macd(close,12,26,9)
if(ta.crossunder(close,34000))
Logger.log("Dropped Below 34000",logger,logTable,"warning")
if(ta.crossunder(close,35000))
Logger.log("Dropped Below 35000",logger,logTable)
if(ta.crossover(close,38000))
Logger.log("Crossed 38000",logger,logTable,"info")
if(ta.crossunder(rsi,20))
Logger.log("RSI Below 20",logger,logTable,"error")
if(ta.crossover(macd,signal))
Logger.log("Macd Crossed Over Signal",logger,logTable)
if(ta.crossover(rsi,80))
Logger.log("RSI Above 80",logger,logTable,"success")
////////////////////////////
// For Scrolling the Table View
////////////////////////////
There is a subtle way of achieving nice scrolling behaviour for the Table view. Open the input properties panel for the table/indicator. Focus on the input field for "Offset", once it's focused, you could use your mouse scroll wheel to increment/decrement the offset values; It will smoothly scroll the Logger Table Rows as well.
/////////////////////
For any assistance using this library or reporting issues, please write in the comment section below.
I will try my best to guide you and update the library. Thanks :)
/////////////////////
ObjectStackLibrary "ObjectStack"
init()
push()
push()
push()
push()
push()
nextIndex()
nextIndex()
nextIndex()
nextIndex()
nextIndex()
delete()
delete()
delete()
delete()
delete()
cleanOldest()
cleanOldest()
cleanOldest()
cleanOldest()
cleanOldest()
BE_CustomFx_LibraryLibrary "BE_CustomFx_Library"
A handful collection of regular functions, Custom Tools & Utility Functions could be used in regular Scripts. hope these functions can be understood by a non programmer like me too.
G_TextValOfNumber(ValueToConvert, RequiredDecimalPlaces, BeginingChar, EndChar) Function to return the String Value of Number with decimal precision with the prefix and suffix characters provided
Parameters:
ValueToConvert : = Number to Convert
RequiredDecimalPlaces : = No of Decimal values Required. supports to a max of 5 decimals else defaults to 2
BeginingChar : = Prefix character which is needed.
EndChar : = Suffix character which is needed.
Returns: Returns Out put with formated value of Given Number for the specified deicimal values with Prefix and suffix string
G_TradableValue(ValueToConvert, NeedCustomization, RequiredDecimalPlaces) Function to return the Tradable Value of Number
Parameters:
ValueToConvert : = Number to Convert
NeedCustomization : = set to 1 if you want to customize the decimal percision values. default is No customization needed, which provides output equalent to round_to_mintick
RequiredDecimalPlaces : = if NeedCustomization is set to 1 mention the decimal percision value required. max supported decimal is 5 else defaults to 2
Returns: Returns Out put with formated value of Given Number
G_TxtSizeForLables(SizeValue) Function to Get size Value for text values used in Lables
Parameters:
SizeValue : = auto, tiny, small, normal, large, huge. specify either of these values or default value Normal will be displayed as output
Returns: Returns Respective Text size
G_Reg_LineType(LineType) Function to Get Line Style Value for text values used in Lines
Parameters:
LineType : = 'solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)' or default line style 'dotted (┈)' will be the output
Returns: Returns Respective Line style
G_ShapeTypeForLables(ShapeType) Function to Get Shape Style Value for text values used in plot shapes
Parameters:
ShapeType : = 'XCross', 'Cross', 'Triangle Up', 'Triangle Down', 'Flag', 'Circle','Arrow Up', 'Arrow Down','Lable Up', 'Lable Down' or default shpae style Triangle Up will be the output
Returns: Returns Respective Shape style
G_Indicator_Val(string, float, int, int) Gets Output of the technical analyis indicator which has length Parameter. RSI, ATR, EMA, SMA, HMA, WMA, VWMA, 'CMO', 'MOM', 'ROC','VWAP'
Parameters:
string : IndicatorName to be specified
float : SrcVal for the TA indicator default is close
int : Length for the TA indicator
int : DecimalValue optional to specify if required formatted output with decimal percision
Returns: Value with the given parameters
G_CandleInfo(string, bool, float, bool) function to get Candle Informarion such as both wicksize, top wick size , bottom wick size, full candle size and body size in default points
Parameters:
string : WhatCandleInfo, string input with either of these options "Wick" , "TWick" , "BWick" , "Candle", "Body" , "BearfbVal", "BullfbVal" , "CandleOpen" ,"CandleClose", "CandleHigh" , "CandleLow", "BodyPct"
bool : RepaintingVersion, set to true if required data on the realtime bar else default is set to false
float : FibValueOfCandle, set the fibo value to extract fibvalue of the candle else default is set to 38.2%
bool : AccountforGaps, set to true if required data on considering the gap between previous and current bar else default is set to false
Returns: Returns Respective values for the candles
G_BullBearBarCount(int, int) Counts how many green & red bars have printed recently (ie. pullback count)
Parameters:
int : HowManyCandlesToCheck The lookback period to look back over
int : BullBear The color of the bar to count (1 = Bull, -1 = Bear), Open = close candles are ignored
Returns: The bar count of how many candles have retraced over the given lookback with specific candles
BarToStartYourCalculation(Int) function to get candle co-ordinate in order to use it further for calculating your analysis work . "Heart full Thanks to 3 Pine motivators (LonesomeTheBlue, Myank & Sriki) who helped me cracking this logic"
Parameters:
Int : SelectedCandleNumber (default=450) How many candles you would need to anlysie in your script from the right.
Returns: A boolean - output is returned to say the starting point and continue to diplay true for the future candles
isHammer(float, bool, 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)
bool : NeedRepainting (default=false) Specify True if you need them to calculate on the realtime bars
Returns: A boolean - true if the current bar matches the requirements of a hammer candle
isStar(float, bool, 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)
bool : NeedRepainting (default=false) Specify True if you need them to calculate on the realtime bars
Returns: A boolean - true if the current bar matches the requirements of a shooting star candle
isDoji(float, float, bool) Checks if the current bar is a doji candle based on the given parameters
Parameters:
float : _wickSize (default=1.5 times) The maximum allowed times can be top wick size compared to the bottom (and vice versa)
float : _bodySize (default= 5 percent to be mentioned as 0.05) The maximum body size as a percentage compared to the entire candle size
bool : NeedRepainting (default=false) Specify true if you need them to calculate on the realtime bars
Returns: A boolean - true if the current bar matches the requirements of a doji candle
isBullishEC(float, float, bool, 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?
bool : NeedRepainting (default=false) Specify True if you need them to calculate on the realtime bars
Returns: A boolean - true if the current bar matches the requirements of a bullish engulfing candle
isBearishEC(float, float, bool, 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?
bool : NeedRepainting (default=false) Specify True if you need them to calculate on the realtime bars
Returns: A boolean - true if the current bar matches the requirements of a bearish engulfing candle
Plot_TrendLineAtDegree(float, float, int, string, bool) helps you to plot the Trendlines based on the specified angle at the defined price to bar ratio
Parameters:
float : Degree (default=14) angle at which Trendline to be plot
float : price2bar_ratio (default=1e-10) The maximum rejection wick size compared to the body as a percentage
int : Bars2Plot (default=6) Does the engulfing candle require the wick to be engulfed as well?
string : LineStyle = 'solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)' or default line style 'dotted (┈)' will be the output
bool : PlotOnOpen_Close (default=false) Specify True if you need them to calculate on the Open\Close Values
Returns: plot the Trendlines based on the specified angle at the defined price to bar ratio
globalCurrently in PineScript you cannot modify global variables in functions because of scope limitations.
One way to work around that is to use arrays.
This Library simplifies the use of arrays as global variables to make your code look cleaner.
If you're coming from other programming languages, I'm sure you will come across this issue in your PineScript journey at some point.
------------------------------------
The code below will throw an error that says: Cannot modify global variable 'price' in function.
var price = 0.0
function() =>
price := 5.5
------------------------------------
To work around that you can do:
var price = array.new_float(1, 0.0)
function() =>
array.set(price, 0, 5.5)
But that code does not spark joy.
------------------------------------
So I bring to you the global library:
import marspumpkin/global/1
var price = global.init(0.0)
function() =>
global.set(price, 5.5)
Debug_Window_LibraryLibrary "Debug_Window_Library"
Provides a framework for logging debug information to a window on the chart.
consoleWrite(txt, maxLines) Adds a line of text to the debug window. The text is rolled off the bottom of the window as it fills up.
Parameters:
txt : - this is the text to be appended to the window
maxLines : - this is the size of the window in lines.
Returns: nothing
The example above shows the close value for the last 10 bars.
Here's the code.
//@version=5
indicator("Debug Library test Script", overlay=true)
import sp2432/Debug_Window_Library/1 as dbg
// add some text to the debug window
dbg .consoleWrite( str .tostring(close), 10)
Thange VaultLibrary "ThangeVault"
Thange Vault is a collection of utility functions required by the Thange Woodwind Playbook.
debug(msg) Print debug information
Parameters:
msg : message to be logged on console
Returns: nothing
tickFormat() Create a string template to restrict stop-loss, take-profit level precision to ticks.
Returns: A string format template
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
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
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
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
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.
DebugConsoleLibrary "DebugConsole"
Methods for debuging/output into a table, console like style.
init(size) initiate property variables.
Parameters:
size : int, console line size.
Returns: tuple, table and string array.
queue(console_id, new_line) Regular Queue, will be called once every bar its called.
Parameters:
console_id : string array, console configuration array.
new_line : string, with contents for new line.
Returns: void.
queue_one(console_id, new_line) Queue only one time, will not repeat itself.
Parameters:
console_id : string array, console configuration array.
new_line : string, with contents for new line.
Returns: void.
update(table_id, console_id) Update method for the console screen.
Parameters:
table_id : table, table to update console text.
console_id : string array, console configuration array.
Returns: void.
Simple debug functionSimple method I used to debug problem in my script.
For loop generates 5 numbers from the given depth. At present, depth is 9
Rules for generating the combinations are as follows:
First number is always 1
Two even numbers should not be adjacent to each other and two odd numbers should not be adjacent to each other
Numbers should be ordered in incremental order.
Print all possible combinations
While the logic above is just a random one. Debug method can be reused for any program.