PineUnitPineUnit by Guardian667
A comprehensive testing framework for Pine Script on TradingView. Built with well-known testing paradigms like Assertions, Units and Suites. It offers the ability to log test results in TradingView's built-in Pine Protocol view, as well as displaying them in a compact table directly on your chart, ensuring your scripts are both robust and reliable.
Unit testing Pine Script indicators, libraries, and strategies becomes seamless, ensuring the precision and dependability of your TradingView scripts. Beyond standard function testing based on predefined input values, PineUnit supports series value testing. This means a test can run on every bar, taking into account its specific values. Moreover, you can specify the exact conditions under which a test should execute, allowing for series-based testing only on bars fitting a designated scenario.
Detailed Guide & Source Code
Quick Start
To get started swiftly with PineUnit, follow this minimalistic example.
import Guardian667/PineUnit/1 as PineUnit
var testSession = PineUnit.createTestSession()
var trueTest = testSession.createSimpleTest("True is always True")
trueTest.assertTrue(true)
testSession.report()
After running your script, you'll notice a table on your chart displaying the test results. For a detailed log output, you can also utilize the Pine Protocol view in TradingView.
--------------------------------------------------------------
T E S T S
--------------------------------------------------------------
Running Default Unit
Tests run: 1, Failures: 0, Not executed: 0, Skipped: 0
To further illustrate, let's introduce a test that's destined to fail:
var bullTest = testSession.createSeriesTest("It's allways Bull Market")
bullTest.assertTrue(close > open, "Uhoh... it's not always bullish")
After executing, the test results will reflect this intentional discrepancy:
--------------------------------------------------------------
T E S T S
--------------------------------------------------------------
Running Default Unit
Tests run: 2, Failures: 1, Not executed: 0, Skipped: 0 <<< FAILURE! - in
It's allways Bull Market
Uhoh... it's not always bullish ==> expected: , but was
This shows how PineUnit efficiently captures and reports discrepancies in test expectations.
It's important to recognise the difference between `createSimpleTest()` and `createSeriesTest()`. In contrast to a simple test, a series-based test is executed on each bar, making assertions on series values.
License
This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
@ Guardian667
A Personal Note
As a software developer experienced in OO-based languages, diving into Pine Script is a unique journey. While many aspects of it are smooth and efficient, there are also notable gaps, particularly in the realm of testing. We've all been there: using `plotchar()` for debugging, trying to pinpoint those elusive issues in our scripts. I've come to appreciate the value of writing tests, which often obviates the need for such debugging. My hope is that this Testing Framework serves you well and saves you a significant amount of time, more that I invested into developing this "baby."
Debugging
printerLibrary "printer"
Printer Library, designed to streamline the process of printing data directly onto charts while offering advanced features for enhanced functionality.
For full documentation, please visit faiyaz7283.github.io
TradeTrackerv2Library "TradeTrackerv2"
This library can be used to track (hypothetical) trades on the chart. Enter the Open, SL, and TP prices (or TP in R to have it calculated) and then call Trade.TrackTrade(barIndex). Keep track of your trades in an array and then simply call TradeTracker.UpdateAllTrades(close) to update all trades based on the current close price.
How to use:
1. Import the library, as always. I'm assuming the alias of "Tracker" below.
2. The Type Trade is exported, so generate a Trade object like newTrade = Tracker.Trade.new() .
3. Set the values for Open, SL, and TP. TP can be set either by price or by R, which will calculate the R based on the Open->SL range:
newTrade.priceOpen = 1.0
newTrade.priceSl = 0.5
newTrade.priceTp = 2.0
-- or in place of the third line above --
newTrade.rTp = 2
4. On each interval you want to update (whether that's per tick/close or on each bar), call trades.UpdateAllTrades(close) . This snippet assumes you have an array named trades (var trades = array.new()) .
In future updates, more customization options will be created. This is the initial prototype.
method MakeTradeLines(t, barIdx)
Namespace types: Trade
Parameters:
t (Trade)
barIdx (int)
method UpdateLabel(t)
Namespace types: Trade
Parameters:
t (Trade)
method MakeLabel(t, barIdx)
Namespace types: Trade
Parameters:
t (Trade)
barIdx (int)
method CloseTrade(t)
Namespace types: Trade
Parameters:
t (Trade)
method OpenTrade(t)
Namespace types: Trade
Parameters:
t (Trade)
method OpenCloseTrade(t, _close)
Namespace types: Trade
Parameters:
t (Trade)
_close (float)
method CalculateProfits(t, _close)
Calculates profits/losses for the Trade, given _close price
Namespace types: Trade
Parameters:
t (Trade)
_close (float)
method UpdateTrade(t, _close)
Namespace types: Trade
Parameters:
t (Trade)
_close (float)
method SetInitialValues(t, barIdx)
Namespace types: Trade
Parameters:
t (Trade)
barIdx (int)
method UpdateAllTrades(trades, _close)
Namespace types: Trade
Parameters:
trades (Trade )
_close (float)
method TrackTrade(t, barIdx)
Namespace types: Trade
Parameters:
t (Trade)
barIdx (int)
Trade
Fields:
id (series__integer)
isOpen (series__bool)
isClosed (series__bool)
isBuy (series__bool)
priceOpen (series__float)
priceTp (series__float)
priceSl (series__float)
rTP (series__float)
profit (series__float)
r (series__float)
resultR (series__float)
lineOpen (series__line)
lineTp (series__line)
lineSl (series__line)
labelStats (series__label)
TradeLibrary "Trade"
A Trade Tracking Library
Monitor conditions with less code by using Arrays. When your conditions are met in chronologically, a signal is returned and the scanning starts again.
Create trades automatically with Stop Loss, Take Profit and Entry. The trades will automatically track based on the market movement and update when the targets are hit.
Sample Usage
Enter a buy trade when RSI crosses below 70 then crosses above 80 before it crosses 40.
Note: If RSI crosses 40 before 80, No trade will be entered.
rsi = ta.rsi(close, 21)
buyConditions = array.new_bool()
buyConditions.push(ta.crossunder(rsi, 70))
buyConditions.push(ta.crossover(rsi, 80))
buy = Trade.signal(buyConditions, ta.crossunder(rsi, 40))
trade = Trade.new(close-(100*syminfo.mintick), close +(200*syminfo.mintick), condition=buy)
plot(trade.takeprofit, "TP", style=plot.style_circles, linewidth=4, color=color.lime)
alertcondition(trade.tp_hit, "TP Hit")
method signal(conditions, reset)
Signal Conditions
Namespace types: bool
Parameters:
conditions (bool )
reset (bool)
Returns: Boolean: True when all the conditions have occured
method update(this, stoploss, takeprofit, entry)
Update Trade Parameters
Namespace types: Trade
Parameters:
this (Trade)
stoploss (float)
takeprofit (float)
entry (float)
Returns: nothing
method clear(this)
Clear Trade Parameters
Namespace types: Trade
Parameters:
this (Trade)
Returns: nothing
method track(this, _high, _low)
Track Trade Parameters
Namespace types: Trade
Parameters:
this (Trade)
_high (float)
_low (float)
Returns: nothing
new(stoploss, takeprofit, entry, _high, _low, condition, update)
New Trade with tracking
Parameters:
stoploss (float)
takeprofit (float)
entry (float)
_high (float)
_low (float)
condition (bool)
update (bool)
Returns: a Trade with targets and updates if stoploss or takeprofit is hit
new()
New Empty Trade
Returns: an empty trade
Trade
Fields:
stoploss (series__float)
takeprofit (series__float)
entry (series__float)
sl_hit (series__bool)
tp_hit (series__bool)
open (series__integer)
debugLibrary "debug"
Show Array or Matrix Elements In Table
Use anytime you want to see the elements in an array or a matrix displayed.
Effective debugger, particularly for strategies and complex logic structures.
Look in code to find instructions. Reach out if you need assistance.
Functionality includes:
Viewing the contents of an array or matrix on screen.
Track variables and variable updates using debug()
Track if and when local scopes fire using debugs()
Types Allowed:
string
float
int
string
debug(_col, _row, _name, _value, _msg, _ip)
Debug Variables in Matrix
Parameters:
_col (int) : (int) Assign Column
_row (int) : (int) Assign Row
_name (matrix) : (simple matrix) Matrix Name
_value (string) : (string) Assign variable as a string (str.tostring())
_msg (string)
_ip (int) : (int) (default 1) 1 for continuous updates. 2 for barstate.isnew updates. 3 for barstate.isconfirmed updates. -1 to only add once
Returns: Returns Variable _value output and _msg formatted as '_msg: variableOutput' in designated column and row
debug(_col, _row, _name, _value, _msg, _ip)
Parameters:
_col (int)
_row (int)
_name (matrix)
_value (float)
_msg (string)
_ip (int)
debug(_col, _row, _name, _value, _msg, _ip)
Parameters:
_col (int)
_row (int)
_name (matrix)
_value (int)
_msg (string)
_ip (int)
debug(_col, _row, _name, _value, _msg, _ip)
Parameters:
_col (int)
_row (int)
_name (matrix)
_value (bool)
_msg (string)
_ip (int)
debugs(_col, _row, _name, _msg)
Debug Scope in Matrix - Identify When Scope Is Accessed
Parameters:
_col (int) : (int) Column Number
_row (int) : (int) Row Number
_name (matrix) : (simple matrix) Matrix Name
_msg (string) : (string) Message
Returns: Message appears in debug panel using _col/_row as the identifier
viewArray(_arrayName, _pos, _txtSize, _tRows, s_index, s_border, _rowCol, bCol, _fillCond, _offset)
Array Element Display (Supports float , int , string , and bool )
Parameters:
_arrayName (float ) : ID of Array to be Displayed
_pos (string) : Position for Table
_txtSize (string) : Size of Table Cell Text
_tRows (int) : Number of Rows to Display Data In (columns will be calculated accordingly)
s_index (bool) : (Optional. Default True.) Show/Hide Index Numbers
s_border (bool) : (Optional. Default False.) Show/Hide Border
_rowCol (string)
bCol (color) : = (Optional. Default Black.) Frame/Border Color.
_fillCond (bool) : (Optional) Conditional statement. Function displays array only when true. For instances where size is not immediately known or indices are na. Default = true, indicating array size is set at bar_index 0.
_offset (int) : (Optional) Use to view historical array states. Default = 0, displaying realtime bar.
Returns: A Display of Array Values in a Table
viewArray(_arrayName, _pos, _txtSize, _tRows, s_index, s_border, _rowCol, bCol, _fillCond, _offset)
Parameters:
_arrayName (int )
_pos (string)
_txtSize (string)
_tRows (int)
s_index (bool)
s_border (bool)
_rowCol (string)
bCol (color)
_fillCond (bool)
_offset (int)
viewArray(_arrayName, _pos, _txtSize, _tRows, s_index, s_border, _rowCol, bCol, _fillCond, _offset)
Parameters:
_arrayName (string )
_pos (string)
_txtSize (string)
_tRows (int)
s_index (bool)
s_border (bool)
_rowCol (string)
bCol (color)
_fillCond (bool)
_offset (int)
viewArray(_arrayName, _pos, _txtSize, _tRows, s_index, s_border, _rowCol, bCol, _fillCond, _offset)
Parameters:
_arrayName (bool )
_pos (string)
_txtSize (string)
_tRows (int)
s_index (bool)
s_border (bool)
_rowCol (string)
bCol (color)
_fillCond (bool)
_offset (int)
viewMatrix(_matrixName, _pos, _txtSize, s_index, _resetIdx, s_border, bCol, _fillCond, _offset)
Matrix Element Display (Supports , , , and )
Parameters:
_matrixName (matrix) : ID of Matrix to be Displayed
_pos (string) : Position for Table
_txtSize (string) : Size of Table Cell Text
s_index (bool) : (Optional. Default True.) Show/Hide Index Numbers
_resetIdx (bool)
s_border (bool) : (Optional. Default False.) Show/Hide Border
bCol (color) : = (Optional. Default Black.) Frame/Border Color.
_fillCond (bool) : (Optional) Conditional statement. Function displays matrix only when true. For instances where size is not immediately known or indices are na. Default = true, indicating matrix size is set at bar_index 0.
_offset (int) : (Optional) Use to view historical matrix states. Default = 0, displaying realtime bar.
Returns: A Display of Matrix Values in a Table
viewMatrix(_matrixName, _pos, _txtSize, s_index, _resetIdx, s_border, bCol, _fillCond, _offset)
Parameters:
_matrixName (matrix)
_pos (string)
_txtSize (string)
s_index (bool)
_resetIdx (bool)
s_border (bool)
bCol (color)
_fillCond (bool)
_offset (int)
viewMatrix(_matrixName, _pos, _txtSize, s_index, _resetIdx, s_border, bCol, _fillCond, _offset)
Parameters:
_matrixName (matrix)
_pos (string)
_txtSize (string)
s_index (bool)
_resetIdx (bool)
s_border (bool)
bCol (color)
_fillCond (bool)
_offset (int)
viewMatrix(_matrixName, _pos, _txtSize, s_index, _resetIdx, s_border, bCol, _fillCond, _offset)
Parameters:
_matrixName (matrix)
_pos (string)
_txtSize (string)
s_index (bool)
_resetIdx (bool)
s_border (bool)
bCol (color)
_fillCond (bool)
_offset (int)
lib_unitLibrary "lib_unit"
functions for assertions and unit testing
method init(this)
Namespace types: Test
Parameters:
this (Test)
method is_true(this, expression, message)
assert that expression is true, if it's false a runtime error will be thrown
Namespace types: Test
Parameters:
this (Test)
expression (bool) : The value to be true
message (string) : The message to print in the runtime error
method is_false(this, expression, message)
assert that expression is false, if it's true a runtime error will be thrown
Namespace types: Test
Parameters:
this (Test)
expression (bool) : The value to be false
message (string) : The message to print in the runtime error
method equals(this, expression, expected, message)
assert if expression and expected are equal, if they don't match a runtime error will be thrown
Namespace types: Test
Parameters:
this (Test)
expression (string) : The value to test
expected (string) : The expected value
message (string) : The message to print in the runtime error
method equals(this, expression, expected, message)
assert if expression and expected are equal, if they don't match a runtime error will be thrown
Namespace types: Test
Parameters:
this (Test)
expression (int) : The value to test
expected (int) : The expected value
message (string) : The message to print in the runtime error
method equals(this, expression, expected, message)
assert if expression and expected are equal, if they don't match a runtime error will be thrown
Namespace types: Test
Parameters:
this (Test)
expression (float) : The value to test
expected (float) : The expected value
message (string) : The message to print in the runtime error
method equals(this, expression, expected, message)
assert if expression and expected are equal, if they don't match a runtime error will be thrown. This version is testing length, order and values
Namespace types: Test
Parameters:
this (Test)
expression (string ) : The array to test
expected (string ) : The expected array
message (string) : The message to print in the runtime error
method equals(this, expression, expected, message)
assert if expression and expected are equal, if they don't match a runtime error will be thrown. This version is testing length, order and values
Namespace types: Test
Parameters:
this (Test)
expression (int ) : The array to test
expected (int ) : The expected array
message (string) : The message to print in the runtime error
method equals(this, expression, expected, message)
assert if expression and expected are equal, if they don't match a runtime error will be thrown. This version is testing length, order and values
Namespace types: Test
Parameters:
this (Test)
expression (float ) : The array to test
expected (float ) : The expected array
message (string) : The message to print in the runtime error
method not_na(this, expression, message)
assert if expression is not na, if it is a runtime error will be thrown.
Namespace types: Test
Parameters:
this (Test)
expression (string) : The value to test
message (string) : The message to print in the runtime error
method not_na(this, expression, message)
assert if expression is not na, if it is a runtime error will be thrown.
Namespace types: Test
Parameters:
this (Test)
expression (int) : The value to test
message (string) : The message to print in the runtime error
method not_na(this, expression, message)
assert if expression is not na, if it is a runtime error will be thrown.
Namespace types: Test
Parameters:
this (Test)
expression (float) : The value to test
message (string) : The message to print in the runtime error
method not_na(this, expression, message)
assert if expression is not na, if it is a runtime error will be thrown.
Namespace types: Test
Parameters:
this (Test)
expression (string ) : The value to test
message (string) : The message to print in the runtime error
method not_na(this, expression, message)
assert if expression is not na, if it is a runtime error will be thrown.
Namespace types: Test
Parameters:
this (Test)
expression (int ) : The value to test
message (string) : The message to print in the runtime error
method not_na(this, expression, message)
assert if expression is not na, if it is a runtime error will be thrown.
Namespace types: Test
Parameters:
this (Test)
expression (float ) : The value to test
message (string) : The message to print in the runtime error
method gt(this, expression1, expression2, message)
assert that expression1 > expression2, if it is not, a runtime error will be thrown.
Namespace types: Test
Parameters:
this (Test)
expression1 (int) : The value that should be greater
expression2 (int) : The value that should be lesser
message (string) : The message to print in the runtime error
method gt(this, expression1, expression2, message)
assert that expression1 > expression2, if it is not, a runtime error will be thrown.
Namespace types: Test
Parameters:
this (Test)
expression1 (float) : The value that should be greater
expression2 (int) : The value that should be lesser
message (string) : The message to print in the runtime error
method gte(this, expression1, expression2, message)
assert that expression1 >= expression2, if it is not, a runtime error will be thrown.
Namespace types: Test
Parameters:
this (Test)
expression1 (int) : The value that should be greater or equal
expression2 (int) : The value that should be lesser or equal
message (string) : The message to print in the runtime error
method gte(this, expression1, expression2, message)
assert that expression1 >= expression2, if it is not, a runtime error will be thrown.
Namespace types: Test
Parameters:
this (Test)
expression1 (float) : The value that should be greater or equal
expression2 (int) : The value that should be lesser or equal
message (string) : The message to print in the runtime error
method lt(this, expression1, expression2, message)
assert that expression1 < expression2, if it is not, a runtime error will be thrown.
Namespace types: Test
Parameters:
this (Test)
expression1 (int) : The value that should be lesser
expression2 (int) : The value that should be greater
message (string) : The message to print in the runtime error
method lt(this, expression1, expression2, message)
assert that expression1 < expression2, if it is not, a runtime error will be thrown.
Namespace types: Test
Parameters:
this (Test)
expression1 (float) : The value that should be lesser
expression2 (int) : The value that should be greater
message (string) : The message to print in the runtime error
method lte(this, expression1, expression2, message)
assert that expression1 <= expression2, if it is not, a runtime error will be thrown.
Namespace types: Test
Parameters:
this (Test)
expression1 (int) : The value that should be lesser or equal
expression2 (int) : The value that should be greater or equal
message (string) : The message to print in the runtime error
method lte(this, expression1, expression2, message)
assert that expression1 <= expression2, if it is not, a runtime error will be thrown.
Namespace types: Test
Parameters:
this (Test)
expression1 (float) : The value that should be lesser or equal
expression2 (int) : The value that should be greater or equal
message (string) : The message to print in the runtime error
Test
Fields:
strict (series__bool)
verbose (series__bool)
logger (|robbatt/lib_log/2;Logger|#OBJ)
lib_logLibrary "lib_log"
library for logging and debugging pine scripts
method init(this)
Namespace types: Logger
Parameters:
this (Logger)
method debug(this, message, condition)
Namespace types: Logger
Parameters:
this (Logger) : Logger to add the entry to
message (string) : The Message to add
condition (bool) : optional flag to enable disable logging of this entry dynamically (default: true)
method info(this, message, condition)
Namespace types: Logger
Parameters:
this (Logger) : Logger to add the entry to
message (string) : The Message to add
condition (bool) : optional flag to enable disable logging of this entry dynamically (default: true)
method success(this, message, condition)
Namespace types: Logger
Parameters:
this (Logger) : Logger to add the entry to
message (string) : The Message to add
condition (bool) : optional flag to enable disable logging of this entry dynamically (default: true)
method warning(this, message, condition)
Namespace types: Logger
Parameters:
this (Logger) : Logger to add the entry to
message (string) : The Message to add
condition (bool) : optional flag to enable disable logging of this entry dynamically (default: true)
method error(this, message, condition)
Namespace types: Logger
Parameters:
this (Logger) : Logger to add the entry to
message (string) : The Message to add
condition (bool) : optional flag to enable disable logging of this entry dynamically (default: true)
method debug_bar(this, message, bar, y, y_offset, last_only, condition)
Namespace types: Logger
Parameters:
this (Logger) : Logger object to check global min level condition
message (string) : The string to print
bar (int) : The bar to print the label at (default: bar_index)
y (float) : The price value to print at (default: high)
y_offset (float) : A price offset from y if you want to print multiple labels at the same spot
last_only (bool)
condition (bool)
method info_bar(this, message, bar, y, y_offset, last_only, condition)
Namespace types: Logger
Parameters:
this (Logger) : Logger object to check global min level condition
message (string) : The string to print
bar (int) : The bar to print the label at (default: bar_index)
y (float) : The price value to print at (default: high)
y_offset (float) : A price offset from y if you want to print multiple labels at the same spot
last_only (bool)
condition (bool)
method success_bar(this, message, bar, y, y_offset, last_only, condition)
Namespace types: Logger
Parameters:
this (Logger) : Logger object to check global min level condition
message (string) : The string to print
bar (int) : The bar to print the label at (default: bar_index)
y (float) : The price value to print at (default: high)
y_offset (float) : A price offset from y if you want to print multiple labels at the same spot
last_only (bool)
condition (bool)
method warning_bar(this, message, bar, y, y_offset, last_only, condition)
Namespace types: Logger
Parameters:
this (Logger) : Logger object to check global min level condition
message (string) : The string to print
bar (int) : The bar to print the label at (default: bar_index)
y (float) : The price value to print at (default: high)
y_offset (float) : A price offset from y if you want to print multiple labels at the same spot
last_only (bool)
condition (bool)
method error_bar(this, message, bar, y, y_offset, last_only, condition)
Namespace types: Logger
Parameters:
this (Logger) : Logger object to check global min level condition
message (string) : The string to print
bar (int) : The bar to print the label at (default: bar_index)
y (float) : The price value to print at (default: high)
y_offset (float) : A price offset from y if you want to print multiple labels at the same spot
last_only (bool)
condition (bool)
LogEntry
Fields:
timestamp (series__integer)
bar (series__integer)
level (series__integer)
message (series__string)
Logger
Fields:
min_level (series__integer)
color_logs (series__bool)
max_lines (series__integer)
line_idx (series__integer)
table_pos (series__string)
display (series__table)
log (array__|LogEntry|#OBJ)
DerivativeAlertPlaceHoldersLibrary "DerivativeAlertPlaceHolders"
TODO: Creation of Placeholders for Alerts, for using in FNO segment.
BasicPH(CustomMessage)
Parameters:
CustomMessage (string) : TODO: Requires Custom Input of Message
Returns: TODO: String with PH
CustomPlaceHoldersFNO(CustomInputMessage, InputPrice)
Parameters:
CustomInputMessage (string) : TODO: Requires Custom Input of Message
InputPrice (float)
Returns: TODO: Alert String with PH used in major FNO alert Segments
DebugLibrary "Debug"
Some debugging functions.
label_on_each_bar(txt, y_position, label_size, label_color, txt_color)
Prints a label on every bar to show text. By default, only the last 50 labels will be shown on the chart. You can increase this amount up to a maximum of 500 by using the max_labels_count parameter in your script’s indicator() or strategy() declaration statement.
Parameters:
txt (string) : New label text.
y_position (float) : New price of the label position.
label_size (string) : Possible values: size.auto, size.tiny, size.small, size.normal, size.large, size.huge. Optional. Default value is `size.small`.
label_color (color) : New label border and arrow color. Optional. Default value is `color.blue`.
txt_color (color) : New text color. Optional. Default value is `color.white`.
Returns: void
label_on_last_bar(txt, y_position, label_size, label_color, txt_color, txt_align)
Prints one label at last bar to show text.
Parameters:
txt (string) : New label text.
y_position (float) : New price of the label position.
label_size (string) : Possible values: size.auto, size.tiny, size.small, size.normal, size.large, size.huge. Optional. Default value is `size.large`.
label_color (color) : New label border and arrow color. Optional. Default value is `color.blue`.
txt_color (color) : New text color. Optional. Default value is `color.white`.
txt_align (string) : Label text alignment. Optional. Possible values: text.align_left, text.align_center, text.align_right. Default value is `text.align_center`.
Returns: void
table_symbol_informations(table_position, table_color, text_color)
Prints a table to show all the Symbol information, including its function names.
Parameters:
table_position (string) : Position of the table. Optional. Possible values are: position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right. Default value is `position.middle_right`.
table_color (color) : The background color of the table. Optional. The default is `color.yellow`.
text_color (color) : The color of the text. Optional. The default is `color.black`.
Returns: void
table_array_float(array_float, table_columns, table_rows, table_position, table_color, txt_color, txt_size)
Prints a table to show float values of an array.
Parameters:
array_float (float ) : The array that will be showed.
table_columns (int)
table_rows (int) : The number of rows to show the values.
table_position (string) : Position of the table. Optional. Possible values are: position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right. Default value is `position.bottom_center`.
table_color (color) : The background color of the table. Optional. By default there is no color.
txt_color (color)
txt_size (string) : Possible values: size.auto, size.tiny, size.small, size.normal, size.large, size.huge. Optional. Default value is `size.normal`.
Returns: void
table_array_int(array_float, table_columns, table_rows, table_position, table_color, txt_color, txt_size)
Prints a table to show int values of an array.
Parameters:
array_float (int ) : The array that will be showed.
table_columns (int)
table_rows (int) : The number of rows to show the values.
table_position (string) : Position of the table. Optional. Possible values are: position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right. Default value is `position.bottom_center`.
table_color (color) : The background color of the table. Optional. By default there is no color.
txt_color (color)
txt_size (string) : Possible values: size.auto, size.tiny, size.small, size.normal, size.large, size.huge. Optional. Default value is `size.normal`.
Returns: void
.print()
You don't need to initialize anything..
After you import the library you can use .print() as easy as that..!
Hope this helps
* use a unique ID for each .print() call
let me know if you run into any bugs
by trying to make it as user friendly as possible i had to do
some not ideal things so there's a chance it could present some bugs with
a lot of labels present on the chart
and if you use label.all to parse and manipulate the labels on the chart..
most likely it will cause an issue but not a lot of people use this so
I don't think that will be a problem.
thanks,
FFriZz | frizlabz
Library "print"
Single function to print any type to console
method str(inp)
`method` convert all types to string
```
(overload)
*.str(any inp) => string
```
Namespace types: series string, simple string, input string, const string
Parameters:
inp (string) : `any` - desc | Required
Returns: `string` formatted string
method str(inp)
Namespace types: series int, simple int, input int, const int
Parameters:
inp (int)
method str(inp)
Namespace types: series float, simple float, input float, const float
Parameters:
inp (float)
method str(inp)
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
inp (bool)
method str(inp)
Namespace types: series linefill
Parameters:
inp (linefill)
method str(inp)
Namespace types: series line
Parameters:
inp (line)
method str(inp)
Namespace types: series box
Parameters:
inp (box)
method str(inp)
Namespace types: series label
Parameters:
inp (label)
method str(inp)
Namespace types: matrix
Parameters:
inp (matrix)
method str(inp)
Namespace types: matrix
Parameters:
inp (matrix)
method str(inp)
Namespace types: matrix
Parameters:
inp (matrix)
method str(inp)
Namespace types: matrix
Parameters:
inp (matrix)
method str(inp)
Namespace types: matrix
Parameters:
inp (matrix)
method str(inp)
Namespace types: matrix
Parameters:
inp (matrix)
method str(inp)
Namespace types: matrix
Parameters:
inp (matrix)
method str(inp)
Namespace types: matrix
Parameters:
inp (matrix)
method str(inp)
Namespace types: linefill
Parameters:
inp (linefill )
method str(inp)
Namespace types: line
Parameters:
inp (line )
method str(inp)
Namespace types: box
Parameters:
inp (box )
method str(inp)
Namespace types: label
Parameters:
inp (label )
method str(inp)
Namespace types: string
Parameters:
inp (string )
method str(inp)
Namespace types: int
Parameters:
inp (int )
method str(inp)
Namespace types: float
Parameters:
inp (float )
method str(inp)
Namespace types: bool
Parameters:
inp (bool )
method arrayShorten(str)
arrayShorten
Namespace types: series string, simple string, input string, const string
Parameters:
str (string) : `string` - the string to shorten | Required
Returns: `string` - a shortened version of the input string if it is an array with more than 7 elements, otherwise the original string
method matrixShorten(str)
matrixShorten
Namespace types: series string, simple string, input string, const string
Parameters:
str (string) : `string` - the string to shorten | Required
Returns: `string` - the shortened matrix string if the input is a matrix, otherwise returns the input string as is
method print(x, ID)
print all types to theh same console with just this `method/function`
```
(overload)
*.print(any x, string ID, bool shorten=true?) => console
"param 'shorten' - only for arrays and matrixs" | true
```
Namespace types: series string, simple string, input string, const string
Parameters:
x (string) : - `any` input to convert
ID (string) : - `string` unique id for label on console `MUST BE UNIQUE`
Returns: adds the `ID` and the `inp` to the console on the chart
method print(x, ID)
Namespace types: series float, simple float, input float, const float
Parameters:
x (float)
ID (string)
method print(x, ID)
Namespace types: series int, simple int, input int, const int
Parameters:
x (int)
ID (string)
method print(x, ID)
Namespace types: series box
Parameters:
x (box)
ID (string)
method print(x, ID)
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
x (bool)
ID (string)
method print(x, ID)
Namespace types: series label
Parameters:
x (label)
ID (string)
method print(x, ID)
Namespace types: series line
Parameters:
x (line)
ID (string)
method print(x, ID)
Namespace types: series linefill
Parameters:
x (linefill)
ID (string)
method print(x, ID, shorten)
Namespace types: string
Parameters:
x (string )
ID (string)
shorten (bool)
method print(x, ID, shorten)
Namespace types: float
Parameters:
x (float )
ID (string)
shorten (bool)
method print(x, ID, shorten)
Namespace types: int
Parameters:
x (int )
ID (string)
shorten (bool)
method print(x, ID, shorten)
Namespace types: box
Parameters:
x (box )
ID (string)
shorten (bool)
method print(x, ID, shorten)
Namespace types: bool
Parameters:
x (bool )
ID (string)
shorten (bool)
method print(x, ID, shorten)
Namespace types: label
Parameters:
x (label )
ID (string)
shorten (bool)
method print(x, ID, shorten)
Namespace types: line
Parameters:
x (line )
ID (string)
shorten (bool)
method print(x, ID, shorten)
Namespace types: linefill
Parameters:
x (linefill )
ID (string)
shorten (bool)
method print(x, ID, shorten)
Namespace types: matrix
Parameters:
x (matrix)
ID (string)
shorten (bool)
method print(x, ID, shorten)
Namespace types: matrix
Parameters:
x (matrix)
ID (string)
shorten (bool)
method print(x, ID, shorten)
Namespace types: matrix
Parameters:
x (matrix)
ID (string)
shorten (bool)
method print(x, ID, shorten)
Namespace types: matrix
Parameters:
x (matrix)
ID (string)
shorten (bool)
method print(x, ID, shorten)
Namespace types: matrix
Parameters:
x (matrix)
ID (string)
shorten (bool)
method print(x, ID, shorten)
Namespace types: matrix
Parameters:
x (matrix)
ID (string)
shorten (bool)
method print(x, ID, shorten)
Namespace types: matrix
Parameters:
x (matrix)
ID (string)
shorten (bool)
method print(x, ID, shorten)
Namespace types: matrix
Parameters:
x (matrix)
ID (string)
shorten (bool)
arraybrowser█ ARRAY BROWSER
Add you arrays to the array browser window and scroll them away left and right.
Flexible formatting options (see below).
Many thanks to @kaigouthro for his beautiful matrixautotable library. (import kaigouthro/matrixautotable/14)
How to use
Copy the "ARRAY BROWSER" commented code section below to your script and uncomment.
See DEMO section in the library for usage examples.
Basically: add() your arrays and draw() on barstate.islast.
If your script adds the arrays every calculation do not forget to clear() before adding.
Otherwise, since the arrays are added by reference, no need to add them on every bar, every time you draw() the actual values are retrieved.
Up to 10 arrays of each type (float/string/line/label/box) are supported (total 50 arrays).
Change offset in the input settings to scroll left/right.
Usage example:
import moebius1977/arraybrowser/1 as arraybrowser // this alias is used in the copied section, so better keep it
arbr.clear() // clears all rows and deletes the table
arbr.add(arrayFloat, format = "0.00") // adds an array with title
arbr.add(arrayInt) // adds an array without title
arbr.add(arrayTimes, "array of times 1", "date time") // format date and time so as to fit in the cell.
arbr.add(arrayTimes, "array of times 2", "{0, time, HH:mm}") // format date and time so as to fit in the cell.
arbr.add(arrayString) //
arbr.add(arrayLine, "arrayLines", "(x1, y1) (x2,y2)") // use your own format combining "x1", "y1", "x2", "y2"
arbr.add(arrayLabel, "arrayLabel", "txt") // only print label text, no coordinates
arbr.add(arrayBox, showIds = true) // show ID's for this array if input setting is "individually"
arbr.draw() // shows the table with arrays, use on barstate.islast
Formatting options
For float/int you can always use format string like "{0, time, HH:mm:ss}" or "{0.00}".
Additional options are
- --- Number formats ---
- "number"
- "0"
- "0.0"
- "0.00"
- "0.000"
- "0.0000"
- "0.00000"
- "0.000000"
- "0.0000000"
- --- Date formats ---
- "date"
- "date : time"
- "dd.MM"
- "dd"
- --- Time formats ---
- "time"
- "HH:mm"
- "mm:ss"
- "date time"
- "date, time"
- "date,time"
- "date\time"
For line and box : Empty `format` returns coordinates as "(x1, y1) - (x2, y2)". Otherwise "x1", "x2", "y1", "y2" in `format` string are replaced by values. (e.g. toS(line, "x1, x2") will only return x1 and x2 separated by comma).
For label : Empty `format` returns coordinates and text as "(x, y): text = text". Otherwise "x1", "y1", "txt" in `format` string are replaced by values. (e.g. toS(label, "txt") will only return text of the label)
JavaScript-style Debug ConsoleThis library provides a JavaScript-style debug console to Pine Coders. It supports the most commonly used utilities from the WHATWG Console Standard including the following:
• console.log
• console.debug
• console.info
• console.warn
• console.error
• console.assert
• console.count
• console.countReset
• console.group
• console.groupEnd
• console.clear
In addition to the WHATWG standard, this library also supports the following methods:
• console.show
• console.hide
FEATURES
• Follows the WHATWG Console Standard, which is widely adopted by all major JavaScript runtimes including browsers and Node.js.
• Provides an out-of-box UI with pre-configured theming, ensuring a clean and professional-looking console.
• Allows for easy UI customizations to fit your personal preferences.
• Has extremely simple import and initialization, making it easy to integrate with your existing codebase.
USAGE
1. Import this library:
import algotraderdev/Console/1
2. Initialize the console object:
var console = Console.new()
// You can also specify optional params to customize the look & feel.
var console = Console.new(
position = position.bottom_right,
max_rows = 50,
width = 0,
text_size = size.normal,
background_color = #000000CC,
timestamp_color = #AAAAAA,
info_message_color = #DDDDDD,
debug_message_color = #AAAAAA,
warn_message_color = #FFEB3B,
error_message_color = #ff3c00)
3. Use the console object to debug your code. Here are some examples:
// Basic logging
console.log('hello world!') // prints 'hello world'
console.warn('warn') // prints 'warn' in yellow
console.error('error') // prints 'error' in red
console.clear() // clears the console
// Assertion
console.assert(a.isEmpty(), 'array should be empty') // prints 'assertion failed: array should be empty' if the array is not empty
// Counter
console.count('fooFunction') // prints 'fooFunction: 1'
console.count('fooFunction') // prints 'fooFunction: 2'
console.countReset('fooFunction') // resets the counter
console.count('fooFunction') // prints 'fooFunction: 1'
// Group
console.log('A')
console.group()
console.log('B')
console.group()
console.log('C')
console.log('D')
console.groupEnd()
console.log('E')
console.groupEnd()
console.log('F')
// prints
// A
// B
// C
// D
// E
// F
// Hide and show
console.hide()
console.show()
loggerLibrary "logger"
◼ Overview
A dual logging library for developers. Tradingview lacks logging capability. This library provides logging while developing your scripts and is to be used by developers when developing and debugging their scripts.
Using this library would potentially slow down you scripts. Hence, use this for debugging only. Once your code is as you would like it to be, remove the logging code.
◼︎ Usage (Console):
Console = A sleek single cell logging with a limit of 4096 characters. When you dont need a large logging capability.
//@version=5
indicator("demo.Console", overlay=true)
plot(na)
import GETpacman/logger/1 as logger
var console = logger.log.new()
console.init() // init() should be called as first line after variable declaration
console.FrameColor:=color.green
console.log(' ')
console.log(' ')
console.log('Hello World')
console.log(' ')
console.log(' ')
console.ShowStatusBar:=true
console.StatusBarAtBottom:=true
console.FrameColor:=color.blue //settings can be changed anytime before show method is called. Even twice. The last call will set the final value
console.ShowHeader:=false //this wont throw error but is not used for console
console.show(position=position.bottom_right) //this should be the last line of your code, after all methods and settings have been dealt with.
◼︎ Usage (Logx):
Logx = Multiple columns logging with a limit of 4096 characters each message. When you need to log large number of messages.
//@version=5
indicator("demo.Logx", overlay=true)
plot(na)
import GETpacman/logger/1 as logger
var logx = logger.log.new()
logx.init() // init() should be called as first line after variable declaration
logx.FrameColor:=color.green
logx.log(' ')
logx.log(' ')
logx.log('Hello World')
logx.log(' ')
logx.log(' ')
logx.ShowStatusBar:=true
logx.StatusBarAtBottom:=true
logx.ShowQ3:=false
logx.ShowQ4:=false
logx.ShowQ5:=false
logx.ShowQ6:=false
logx.FrameColor:=color.olive //settings can be changed anytime before show method is called. Even twice. The last call will set the final value
logx.show(position=position.top_right) //this should be the last line of your code, after all methods and settings have been dealt with.
◼︎ Fields (with default settings)
▶︎ IsConsole = True Log will act as Console if true, otherwise it will act as Logx
▶︎ ShowHeader = True (Log only) Will show a header at top or bottom of logx.
▶︎ HeaderAtTop = True (Log only) Will show the header at the top, or bottom if false, if ShowHeader is true.
▶︎ ShowStatusBar = True Will show a status bar at the bottom
▶︎ StatusBarAtBottom = True Will show the status bar at the bottom, or top if false, if ShowHeader is true.
▶︎ ShowMetaStatus = True Will show the meta info within status bar (Current Bar, characters left in console, Paging On Every Bar, Console dumped data etc)
▶︎ ShowBarIndex = True Logx will show column for Bar Index when the message was logged. Console will add Bar index at the front of logged messages
▶︎ ShowDateTime = True Logx will show column for Date/Time passed with the logged message logged. Console will add Date/Time at the front of logged messages
▶︎ ShowLogLevels = True Logx will show column for Log levels corresponding to error codes. Console will log levels in the status bar
▶︎ ReplaceWithErrorCodes = True (Log only) Logx will show error codes instead of log levels, if ShowLogLevels is switched on
▶︎ RestrictLevelsToKey7 = True Log levels will be restricted to Ley 7 codes - TRACE, DEBUG, INFO, WARNING, ERROR, CRITICAL, FATAL
▶︎ ShowQ1 = True (Log only) Show the column for Q1
▶︎ ShowQ2 = True (Log only) Show the column for Q2
▶︎ ShowQ3 = True (Log only) Show the column for Q3
▶︎ ShowQ4 = True (Log only) Show the column for Q4
▶︎ ShowQ5 = True (Log only) Show the column for Q5
▶︎ ShowQ6 = True (Log only) Show the column for Q6
▶︎ ColorText = True Log/Console will color text as per error codes
▶︎ HighlightText = True Log/Console will highlight text (like denoting) as per error codes
▶︎ AutoMerge = True (Log only) Merge the queues towards the right if there is no data in those queues.
▶︎ PageOnEveryBar = True Clear data from previous bars on each new bar, in conjuction with PageHistory setting.
▶︎ MoveLogUp = True Move log in up direction. Setting to false will push logs down.
▶︎ MarkNewBar = True On each change of bar, add a marker to show the bar has changed
▶︎ PrefixLogLevel = True (Console only) Prefix all messages with the log level corresponding to error code.
▶︎ MinWidth = 40 Set the minimum width needed to be seen. Prevents logx/console shrinking below these number of characters.
▶︎ TabSizeQ1 = 0 If set to more than one, the messages on Q1 or Console messages will indent by this size based on error code (Max 4 used)
▶︎ TabSizeQ2 = 0 If set to more than one, the messages on Q2 will indent by this size based on error code (Max 4 used)
▶︎ TabSizeQ3 = 0 If set to more than one, the messages on Q2 will indent by this size based on error code (Max 4 used)
▶︎ TabSizeQ4 = 0 If set to more than one, the messages on Q2 will indent by this size based on error code (Max 4 used)
▶︎ TabSizeQ5 = 0 If set to more than one, the messages on Q2 will indent by this size based on error code (Max 4 used)
▶︎ TabSizeQ6 = 0 If set to more than one, the messages on Q2 will indent by this size based on error code (Max 4 used)
▶︎ PageHistory = 0 Used with PageOnEveryBar. Determines how many historial pages to keep.
▶︎ HeaderQbarIndex = 'Bar#' (Logx only) The header to show for Bar Index
▶︎ HeaderQdateTime = 'Date' (Logx only) The header to show for Date/Time
▶︎ HeaderQerrorCode = 'eCode' (Logx only) The header to show for Error Codes
▶︎ HeaderQlogLevel = 'State' (Logx only) The header to show for Log Level
▶︎ HeaderQ1 = 'h.Q1' (Logx only) The header to show for Q1
▶︎ HeaderQ2 = 'h.Q2' (Logx only) The header to show for Q2
▶︎ HeaderQ3 = 'h.Q3' (Logx only) The header to show for Q3
▶︎ HeaderQ4 = 'h.Q4' (Logx only) The header to show for Q4
▶︎ HeaderQ5 = 'h.Q5' (Logx only) The header to show for Q5
▶︎ HeaderQ6 = 'h.Q6' (Logx only) The header to show for Q6
▶︎ Status = '' Set the status to this text.
▶︎ HeaderColor Set the color for the header
▶︎ HeaderColorBG Set the background color for the header
▶︎ StatusColor Set the color for the status bar
▶︎ StatusColorBG Set the background color for the status bar
▶︎ TextColor Set the color for the text used without error code or code 0.
▶︎ TextColorBG Set the background color for the text used without error code or code 0.
▶︎ FrameColor Set the color for the frame around Logx/Console
▶︎ FrameSize = 1 Set the size of the frame around Logx/Console
▶︎ CellBorderSize = 0 Set the size of the border around cells.
▶︎ CellBorderColor Set the color for the border around cells within Logx/Console
▶︎ SeparatorColor = gray Set the color of separate in between Console/Logx Attachment
◼︎ Methods (summary)
● init ▶︎ Initialise the log
● log ▶︎ Log the messages. Use method show to display the messages
● page ▶︎ Clear messages from previous bar while logging messages on this bar.
● show ▶︎ Shows a table displaying the logged messages
● clear ▶︎ Clears the log of all messages
● resize ▶︎ Resizes the log. If size is for reduction then oldest messages are lost first.
● turnPage ▶︎ When called, all messages marked with previous page, or from start are cleared
● dateTimeFormat ▶︎ Sets the date time format to be used when displaying date/time info.
● resetTextColor ▶︎ Reset Text Color to library default
● resetTextBGcolor ▶︎ Reset Text BG Color to library default
● resetHeaderColor ▶︎ Reset Header Color to library default
● resetHeaderBGcolor ▶︎ Reset Header BG Color to library default
● resetStatusColor ▶︎ Reset Status Color to library default
● resetStatusBGcolor ▶︎ Reset Status BG Color to library default
● setColors ▶︎ Sets the colors to be used for corresponding error codes
● setColorsBG ▶︎ Sets the background colors to be used for corresponding error codes. If not match of error code, then text color used.
● setColorsHC ▶︎ Sets the highlight colors to be used for corresponding error codes.If not match of error code, then text bg color used.
● resetColors ▶︎ Reset the colors to library default (Total 36, not including error code 0)
● resetColorsBG ▶︎ Reset the background colors to library default
● resetColorsHC ▶︎ Reset the highlight colors to library default
● setLevelNames ▶︎ Set the log level names to be used for corresponding error codes. If not match of error code, then empty string used.
● resetLevelNames ▶︎ Reset the log level names to library default. (Total 36) 1=TRACE, 2=DEBUG, 3=INFO, 4=WARNING, 5=ERROR, 6=CRITICAL, 7=FATAL
● attach ▶︎ Attaches a console to an existing Logx, allowing to have dual logging system independent of each other
● detach ▶︎ Detaches an already attached console from Logx
method clear(this)
Clears all the queue, including bar_index and time queues, of existing messages
Namespace types: log
Parameters:
this (log)
method resize(this, rows)
Resizes the message queues. If size is decreased then removes the oldest messages
Namespace types: log
Parameters:
this (log)
rows (int) : The new size needed for the queues. Default value is 40.
method dateTimeFormat(this, format)
Re/set the date time format used for displaying date and time. Default resets to dd.MMM.yy HH:mm
Namespace types: log
Parameters:
this (log)
format (string)
method resetTextColor(this)
Resets the text color of the log to library default.
Namespace types: log
Parameters:
this (log)
method resetTextColorBG(this)
Resets the background color of the log to library default.
Namespace types: log
Parameters:
this (log)
method resetHeaderColor(this)
Resets the color used for Headers, to library default.
Namespace types: log
Parameters:
this (log)
method resetHeaderColorBG(this)
Resets the background color used for Headers, to library default.
Namespace types: log
Parameters:
this (log)
method resetStatusColor(this)
Resets the text color of the status row, to library default.
Namespace types: log
Parameters:
this (log)
method resetStatusColorBG(this)
Resets the background color of the status row, to library default.
Namespace types: log
Parameters:
this (log)
method resetFrameColor(this)
Resets the color used for the frame around the log table, to library default.
Namespace types: log
Parameters:
this (log)
method resetColorsHC(this)
Resets the color used for the highlighting when Highlight Text option is used, to library default
Namespace types: log
Parameters:
this (log)
method resetColorsBG(this)
Resets the background color used for setting the background color, when the Color Text option is used, to library default
Namespace types: log
Parameters:
this (log)
method resetColors(this)
Resets the color used for respective error codes, when the Color Text option is used, to library default
Namespace types: log
Parameters:
this (log)
method setColors(this, c)
Sets the colors corresponding to error codes
Index 0 of input array c is color is reserved for future use.
Index 1 of input array c is color for debug code 1.
Index 2 of input array c is color for debug code 2.
There are 2 modes of coloring
1 . Using the Foreground color
2 . Using the Foreground color as background color and a white/black/gray color as foreground color
This is denoting or highlighting. Which effectively puts the foreground color as background color
Namespace types: log
Parameters:
this (log)
c (color ) : Array of colors to be used for corresponding error codes. If the corresponding code is not found, then text color is used
method setColorsHC(this, c)
Sets the highlight colors corresponding to error codes
Index 0 of input array c is color is reserved for future use.
Index 1 of input array c is color for debug code 1.
Index 2 of input array c is color for debug code 2.
There are 2 modes of coloring
1 . Using the Foreground color
2 . Using the Foreground color as background color and a white/black/gray color as foreground color
This is denoting or highlighting. Which effectively puts the foreground color as background color
Namespace types: log
Parameters:
this (log)
c (color ) : Array of highlight colors to be used for corresponding error codes. If the corresponding code is not found, then text color BG is used
method setColorsBG(this, c)
Sets the highlight colors corresponding to debug codes
Index 0 of input array c is color is reserved for future use.
Index 1 of input array c is color for debug code 1.
Index 2 of input array c is color for debug code 2.
There are 2 modes of coloring
1 . Using the Foreground color
2 . Using the Foreground color as background color and a white/black/gray color as foreground color
This is denoting or highlighting. Which effectively puts the foreground color as background color
Namespace types: log
Parameters:
this (log)
c (color ) : Array of background colors to be used for corresponding error codes. If the corresponding code is not found, then text color BG is used
method resetLevelNames(this, prefix, suffix)
Resets the log level names used for corresponding error codes
With prefix/suffix, the default Level name will be like => prefix + Code + suffix
Namespace types: log
Parameters:
this (log)
prefix (string) : Prefix to use when resetting level names
suffix (string) : Suffix to use when resetting level names
method setLevelNames(this, names)
Resets the log level names used for corresponding error codes
Index 0 of input array names is reserved for future use.
Index 1 of input array names is name used for error code 1.
Index 2 of input array names is name used for error code 2.
Namespace types: log
Parameters:
this (log)
names (string ) : Array of log level names be used for corresponding error codes. If the corresponding code is not found, then an empty string is used
method init(this, rows, isConsole)
Sets up data for logging. It consists of 6 separate message queues, and 3 additional queues for bar index, time and log level/error code. Do not directly alter the contents, as library could break.
Namespace types: log
Parameters:
this (log)
rows (int) : Log size, excluding the header/status. Default value is 50.
isConsole (bool) : Whether to init the log as console or logx. True= as console, False = as Logx. Default is true, hence init as console.
method log(this, ec, m1, m2, m3, m4, m5, m6, tv, log)
Logs messages to the queues , including, time/date, bar_index, and error code
Namespace types: log
Parameters:
this (log)
ec (int) : Error/Code to be assigned.
m1 (string) : Message needed to be logged to Q1, or for console.
m2 (string) : Message needed to be logged to Q2. Not used/ignored when in console mode
m3 (string) : Message needed to be logged to Q3. Not used/ignored when in console mode
m4 (string) : Message needed to be logged to Q4. Not used/ignored when in console mode
m5 (string) : Message needed to be logged to Q5. Not used/ignored when in console mode
m6 (string) : Message needed to be logged to Q6. Not used/ignored when in console mode
tv (int) : Time to be used. Default value is time, which logs the start time of bar.
log (bool) : Whether to log the message or not. Default is true.
method page(this, ec, m1, m2, m3, m4, m5, m6, tv, page)
Logs messages to the queues , including, time/date, bar_index, and error code. All messages from previous bars are cleared
Namespace types: log
Parameters:
this (log)
ec (int) : Error/Code to be assigned.
m1 (string) : Message needed to be logged to Q1, or for console.
m2 (string) : Message needed to be logged to Q2. Not used/ignored when in console mode
m3 (string) : Message needed to be logged to Q3. Not used/ignored when in console mode
m4 (string) : Message needed to be logged to Q4. Not used/ignored when in console mode
m5 (string) : Message needed to be logged to Q5. Not used/ignored when in console mode
m6 (string) : Message needed to be logged to Q6. Not used/ignored when in console mode
tv (int) : Time to be used. Default value is time, which logs the start time of bar.
page (bool) : Whether to log the message or not. Default is true.
method turnPage(this, turn)
Set the messages to be on a new page, clearing messages from previous page.
This is not dependent on PageHisotry option, as this method simply just clears all the messages, like turning old pages to a new page.
Namespace types: log
Parameters:
this (log)
turn (bool)
method show(this, position, hhalign, hvalign, hsize, thalign, tvalign, tsize, show, attach)
Display Message Q, Index Q, Time Q, and Log Levels
All options for postion/alignment accept TV values, such as position.bottom_right, text.align_left, size.auto etc.
Namespace types: log
Parameters:
this (log)
position (string) : Position of the table used for displaying the messages. Default is Bottom Right.
hhalign (string) : Horizontal alignment of Header columns
hvalign (string) : Vertical alignment of Header columns
hsize (string) : Size of Header text Options
thalign (string) : Horizontal alignment of all messages
tvalign (string) : Vertical alignment of all messages
tsize (string) : Size of text across the table
show (bool) : Whether to display the logs or not. Default is true.
attach (log) : Console that has been attached via attach method. If na then console will not be shown
method attach(this, attach, position)
Attaches a console to Logx, or moves already attached console around Logx
All options for position/alignment accept TV values, such as position.bottom_right, text.align_left, size.auto etc.
Namespace types: log
Parameters:
this (log)
attach (log) : Console object that has been previously attached.
position (string) : Position of Console in relation to Logx. Can be Top, Right, Bottom, Left. Default is Bottom. If unknown specified then defaults to bottom.
method detach(this, attach)
Detaches the attached console from Logx.
All options for position/alignment accept TV values, such as position.bottom_right, text.align_left, size.auto etc.
Namespace types: log
Parameters:
this (log)
attach (log) : Console object that has been previously attached.
libhs_td5Library "libhs_td5"
td5 Test Data Library for Logx Testing
fill(dbus, fillData)
Parameters:
dbus (matrix)
fillData (bool)
libhs_td4Library "libhs_td4"
td4 Test Data Library for Console Testing
fill(dbus, fillData)
Parameters:
dbus (matrix)
fillData (bool)
typeandcastLibrary "typeandcast"
Contains the following methods:
_type() - Returns the type of the variable in the forms "int", "array", "matrix"
_type_item() - Returns the type of the variable or of the element (for array/matrix). (e.g. `arrayFloat._type_item()` returns 'float').
_type_struct() - Returns the type of the structure only (i.e. "array" or "matrix"), for simple types (like e.g. `int`) returns "simple". (e.g. `arrayFloat._type_struct()` returns 'array').
_tona() - Casts na to the type of the parent object. (e.g. for an `int x` calling `x.tona()` returns `int(na)`
(inspired by the works of @kaigouthro and @faiyaz7283)
The _type() / _type_item() / _type_struct() methods are available for the following types:
int
float
bool
string
color
line
label
box
table
linefill
int
float
bool
string
color
line
label
box
table
linefill
matrix
matrix
matrix
matrix
matrix
matrix
matrix
matrix
matrix
matrix
The `tona()' method is available only for the simple types (except `linefill`, coundn't make it work for it)
Please see the descriptions in the script.
Console📕 Console Library
🔷 Introduction
This script is an adaptation of the classic JavaScript console script. It provides a simple way to display data in a console-like table format for debugging purposes.
While there are many nice console/logger scripts out there, my personal goal was to achieve inline functionality and visual object (label, lines) logging .
🔷 How to Use
◼ 1. Import the Console library into your script:
import cryptolinx/Console/1
- or -
Instead of the library namespace, you can define a custom namespace as alias.
import cryptolinx/Console/1 as c
◼ 2. Create and init a new `` object.
The `init()` method is used to initialize the console object with default settings. It can be used to customize it.
// When using the `var` keyword in a declaration, the logs will act as ever-forwarding.
// Without `var`, the `console` variable will be redeclared every time `bar` is called.
// var console = Console.terminal.new(log_position=position.bottom_left, prefix = '> ', show_no = true)
- or -
If you has set up an alias before.
var console = c.terminal.new().init()
◼ 3. Logging
// inline ✨
array testArray = array.new(3, .0).log(console)
// basic
console.log(testArray)
// inline ✨
var testLabel = label.new(bar_index, close, 'Label Text').log(console)
// basic
console.log(testLabel)
// It is also possible to use `().` for literals ✨.
int a = 100
testCalc = (5 * 100).log(console) + a.log(console) // SUM: 600
console.
.empty()
.log('SUM' + WS + testCalc.tostring())
◼ 4. Visibility
Finally, we need to call the `show()` method to display the logged messages in the console.
console.show(true) // True by default. Simply turn it on or off
DiddlyUtilityLibrary "DiddlyUtility"
TODO: add library description here
getStringTimeMinus1Minute(london_ssth, london_sstm)
Parameters:
london_ssth
london_sstm
getLadderStepIncrement(_price)
Parameters:
_price
getLadderIndexForPrice(_price, _ladderRange)
Parameters:
_price
_ladderRange
getLadderStartPriceRange(_price, _ladderRange)
Parameters:
_price
_ladderRange
get_volume_string(_volume)
Parameters:
_volume
floorDown(number, decimals)
Parameters:
number
decimals
countDigitsBeforeDecimal(n)
Parameters:
n
countDigitsAfterDecimal(n)
Parameters:
n
getChartTimePeriodAsSeconds(_chartPeriod)
Parameters:
_chartPeriod
debug(_txt)
Parameters:
_txt
FrizBugLibrary "FrizBug"
Debug Tools | Pinescript Debugging Tool Kit
All in one Debugger - the benefit of wrapper functions to simply wrap variables or outputs and have the code still execute the same. Perfect for Debugging on Pine
str(inp)
Overloaded tostring like Function for all type+including Object Variables will also do arrays and matricies of all Types
Parameters:
inp : All types
Returns: string
print_label(str, x_offset, y, barstate, style, color, textcolor, text_align, size)
Label Helper Function - only needs the Str input to work
Parameters:
str :
x_offset : offset from last bar + or -
y : price of label
barstate : barstate built in variable
style : label style settin7
color : color setting
textcolor : textcolor
text_align : text align setting
size : text_sise
Returns: label
init()
initializes the database arrays
Returns: tuple | 2 matrix (1 matrix is varip(live) the other is reagular var (Bar))
update(log, live, live_console, log_console, live_lbl, log_lbl)
Put at the very end of your code / This updates all of the consoles
Parameters:
log : This matrix is the one used for Bar updates
live : This matrix is the one used for Real Time updates
live_console : on_offs for the consoles and lbls - call in the update function
log_console : on_offs for the consoles and lbls - call in the update function
live_lbl : on_offs for the consoles and lbls - call in the update function
log_lbl : on_offs for the consoles and lbls - call in the update function
Returns: void
log(log, inp, str_label, off, rows, index_cols, bars_back)
Function Will push to the Console offset to the right of Current bar, This is the main Console - it has 2 Feeds left and right (changeable)"
Parameters:
log : Matrix - Log or Live
inp : All types
str_label : (optional) This input will label it on the feed
off : Useful for when you don't want to remove the function"
rows : when printing or logging a matrix this will shorten the output will show last # of rows"
index_cols : When printing or logging a array or matrix this will shorten the array or the columns of a matrix by the #"
bars_back : Adjustment for Bars Back - Default is 1 (0 for barstate.islast)"
Returns: inp - all types (The log and print functions can be used as wrapper functions see usage below for examples)
Print(log, str_label, off, bars_back)
Function can be used to send information to a label style Console, Can be used as a wrapper function, Similar to str.format use with str()
Parameters:
log :
str_label : (optional) Can be used to label Data sent to the Console
off : Useful for when you don't want to remove the function
bars_back : Adjustment for Bars Back - Default is 1 (0 for barstate.islast)
Returns: string
print(inp, str_label, off, bars_back)
This Function can be used to send information to a label style Console, Can be used as a wrapper function, Overload print function
Parameters:
inp : All types
str_label : string (optional) Can be used to label Data sent to the Console
off : Useful for when you don't want to remove the function
bars_back : Adjustment for Bars Back - Default is 1 (0 for barstate.islast)
Returns: inp - all types (The log and print functions can be used as wrapper functions see usage below for examples)
Credits:
@kaigouthro - for the font library
@RicardoSantos - for the concept I used to make this
Thanks!
Use cases at the bottom
columnsLibrary "columns"
Error Tolerant Matrix Setter/Getter Operations. Easy ways to add/remove items into start and end of Columns as well as arrays to grow and shrink matrix.
if mismatched sizes occur the typified NA value will be there to prevent catastrophic crashing.
Rows and Columns are split into 2 libraries due to limitations on number of exports as well as ease of style (columns.shift(), rows.pop() )
pop(_matrix)
do pop last Column off of matrix
Parameters:
_matrix : Matrix To Edit
Returns: Array of Last Column, removing it from matrix
shift(_matrix)
do shift the first Column off of matrix
Parameters:
_matrix : Matrix To Edit
Returns: Array of First Column, removing it from matrix
get(_matrix, _clmnNum)
retrieve specific Column of matrix
Parameters:
_matrix : Matrix To Edit
_clmnNum : Column being Targeted
Returns: Array of selected Column number, leaving in place
push(_matrix, _clmnNum, _item)
add single item onto end of Column
Parameters:
_matrix : Matrix To Edit
_clmnNum : Column being Targeted
_item : Item to Push on Column
Returns: shifted item from Column start
push(_matrix, _array)
add single item onto end of matrix
Parameters:
_matrix : Matrix To Edit
_array : Array to Push on Matrix
Returns: Void
unshift(_matrix, _clmnNum, _item)
slide single item into start of Column remove last
Parameters:
_matrix : Matrix To Edit
_clmnNum : Column being Targeted
_item : Item to Unshift on Column
Returns: popped item from Column end
unshift(_matrix, _array)
add single item into first Column of matrix
Parameters:
_matrix : Matrix To Edit
_array : Array to unshift into Matrix
Returns: Void
set(_matrix, _clmnNum, _array)
replace an array to an existing Column
Parameters:
_matrix : Matrix To Edit
_clmnNum : Column being Targeted
_array : Array to place in Matrix
Returns: Column that was replaced
insert(_matrix, _clmnNum, _array)
insert an array to a new Column
Parameters:
_matrix : Matrix To Edit
_clmnNum : Column being Targeted
_array : Array to place in Matrix
Returns: void
slideDown(_matrix, _array)
add single item onto end of Column
Parameters:
_matrix : Matrix To Edit
_array : Array to push to Matrix
Returns: shifted first Column
slideUp(_matrix, _array)
add single item onto end of Column
Parameters:
_matrix : Matrix To Edit
_array : Array to unshift to Matrix
Returns: poppeed last Column
pullOut(_matrix, _clmnNum)
add single item onto end of Column
Parameters:
_matrix : Matrix To Edit
_clmnNum : Column being Targeted
Returns: removed selected Column
rowsLibrary "rows"
Error Tolerant Matrix Setter/Getter Operations. Easy ways to add/remove items into start and end of rows as well as arrays to grow and shrink matrix.
if mismatched sizes occur the typified NA value will be there to prevent catastrophic crashing.
columns and rows are split into 2 libraries due to limitations on number of exports as well as ease of style (columns.shift(), rows.pop() )
pop(_matrix)
do pop last row off of matrix
Parameters:
_matrix : Matrix To Edit
Returns: Array of Last row, removing it from matrix
shift(_matrix)
do shift the first row off of matrix
Parameters:
_matrix : Matrix To Edit
Returns: Array of First row, removing it from matrix
get(_matrix, _rowNum)
retrieve specific row of matrix
Parameters:
_matrix : Matrix To Edit
_rowNum : Row being Targeted
Returns: Array of selected row number, leaving in place
push(_matrix, _rowNum, _item)
add single item onto end of row
Parameters:
_matrix : Matrix To Edit
_rowNum : Row being Targeted
_item : Item to Push on Row
Returns: shifted item from row start
push(_matrix, _array)
add single item onto end of matrix
Parameters:
_matrix : Matrix To Edit
_array : Array to Push on Matrix
Returns: Void
unshift(_matrix, _rowNum, _item)
slide single item into start of row remove last
Parameters:
_matrix : Matrix To Edit
_rowNum : Row being Targeted
_item : Item to Unshift on Row
Returns: popped item from row end
unshift(_matrix, _array)
add single item into first row of matrix
Parameters:
_matrix : Matrix To Edit
_array : Array to unshift into Matrix
Returns: Void
set(_matrix, _rowNum, _array)
replace an array to an existing row
Parameters:
_matrix : Matrix To Edit
_rowNum : Row being Targeted
_array : Array to place in Matrix
Returns: row that was replaced
insert(_matrix, _rowNum, _array)
insert an array to a new row
Parameters:
_matrix : Matrix To Edit
_rowNum : Row being Targeted
_array : Array to place in Matrix
Returns: void
slideDown(_matrix, _array)
add single item onto end of row
Parameters:
_matrix : Matrix To Edit
_array : Array to push to Matrix
Returns: shifted first row
slideUp(_matrix, _array)
add single item onto end of row
Parameters:
_matrix : Matrix To Edit
_array : Array to unshift to Matrix
Returns: popped last row
pullOut(_matrix, _rowNum)
add single item onto end of row
Parameters:
_matrix : Matrix To Edit
_rowNum : Row being Targeted
Returns: removed selected row
conditionLibrary "condition"
True/False Condition tools and toggles for booleans and utility.
suggested use is checking if a calculation is required, or can be skipped
speeding up script calculations in realtime and historical scenarios.
isonlywihtout(_first_cond, _second_cond)
output is true only if first true and second false
Parameters:
_first_cond : (bool) First Condition
_second_cond : (bool) Second Condition
Returns: True if coditions met
isonlywih(_first_cond, _second_cond)
output is true only for the first condition if the second condition is also true
Parameters:
_first_cond : (bool) First Condition
_second_cond : (bool) Second Condition
Returns: True if coditions met
isactive(_cond)
output is true active only while actively true
Parameters:
_cond : (bool) Condition met
Returns: True if coditions met
isnotactive(_cond)
output is true only while condition is not active
Parameters:
_cond : (bool) Condition met
Returns: True if coditions met
isontoggle(_cond)
output is true and holds on True activation , na input has no effect, only a false will disengage
Parameters:
_cond : (bool) Condition met
Returns: True if coditions met
isofftoggle(_cond)
output is true and holds on False activation, na input has no effect, only a true will disengage
Parameters:
_cond : (bool) Condition met
Returns: True if coditions met
isnotboth(_first_cond, _second_cond)
output is false only if both are active, either or neither pass true
Parameters:
_first_cond : (bool) First Condition
_second_cond : (bool) Second Condition
Returns: True if coditions met
isneither(_first_cond, _second_cond)
output is false only if both are active, either or neither pass true
Parameters:
_first_cond : (bool) First Condition
_second_cond : (bool) Second Condition
Returns: True if coditions met
isbothtoggled(_first_cond, _second_cond)
output is true and held when both trigger true, and only disengages if both are false at once
Parameters:
_first_cond : (bool) First Condition
_second_cond : (bool) Second Condition
Returns: True if coditions met
ConsoleLibrary "Console"
█ OVERVIEW
An easy way to output messages to a console like table using a a simple "print" function that can be called from anywhere in your code including functions.
█ Supports:
- Scrollable console messages
- Customisable number of displayed messages
- More than one "console" for different types of output if required
- The ability to choose which message to start viewing from (useful if the message list is long)
- The ability to place the console table at different positions on the chart to mitigate against
overwriting an existing table.
█ Limitations:
The "scrollbar" handle is actually a modified time widget handle. As the handle is grabbed and moved left or right across the chart bars, this script calculates the offset of the bar being pointed to from the last bar in the chart and uses that as the console message offset. However, It isn't possible to position this on the last chart bar with code.
So there are two solutions:
1) Manually change timestamp of the variable scrollStart to the current time (roughly)
eg. scrollStart = "25 Dec 2022 14:30 +0000"
2) Use a higher timeframe (Weeks or Months) and visually find the scroll bar. If it is to the right of the chart bars the console output will read NaN. Grab the handle and move it left and it will snap to the last chart candle position. If it is to the left then find it and move it to the right as needed.
█ Notes On Usage
- Import the library as console (the call will be console.print(...) )
- Assign a console variable name and call the console.initialise function
eg. var con1=console.initialise()
- Use the console.print() function to print a message or messages
This takes two parameters:
_consoleName :this is the console name you are printing to
_message: this is the message that you want to display. It is a string and can be built in the normal way using any pinescript string functions like str.tostring() etc
- Use the console.display function to display the messages.
To work as intended this display function should be placed at the last line with the following code
if i_showMessages
....if i_displayTable == "con1"
........display(con1, i_lineOffset, i_rowsToDisplay, i_gotoMsg, posn)
(More "consoles" can be written to and the example code provided with the library shows this in more detail. Also, the indents don't show in these notes)
Lastly, placement of a console.print() without a qualifying "if" statement will occur for every bar. This may be desired. If not then use under an if statement (example in the supplied code).
Happy debugging :)
-----------------------------------------------------------------------------------------------------------
initialise()
initialise: creates the message array
Parameters:
none :
Returns: message array: this is assigned to the "console" identifier
print(_consoleName, _message)
used to output the desired text string to the console
Parameters:
_consoleName : : the message array
_message : : the console message
Returns: none
display(_consoleName, _lineOffset, _rowsToDisplay, _gotoMsg, _posn)
display: placed in the last section of code. Displays the console messages
Parameters:
_consoleName : : the message array
_lineOffset : : the setting of the scroll bar (time widget)
_rowsToDisplay : : how many rows to show in the console table
_gotoMsg : : which message to display from (default is 0)
_posn : : where the console table will be displayed
Returns: none