VonnyPublicLibraryLibrary "VonnyPublicLibrary"
A collection functions commonly used within my scripts
EntryBull(float, float)
Calculate when a bullish condition occurs. (When you have two variables)
Parameters:
float : Enter first variable
float : Enter second variable
Returns: True the first bar of your bullish condition
EntryBear(float, float)
Calculate when a bearish condition occurs. (When you have two variables)
Parameters:
float : Enter first variable
float : Enter second variable
Returns: True the first bar of your bearish condition
LowestPivot(bool, bool, bool, float, float)
Calculate the low of your bearish condition
Parameters:
bool : bullish condition
bool : bearish condition
bool : candle buffer to prevent the script from crashing. Since were working with a Dynamic Length
float : Enter what you want to see the low off? Low of the bar OR Close of the bar
float : Enter what you want to see the low off? Low of the bar OR Open of the bar..... might seem pointless but some times the Lowest open is lower then the Lowest Close
Returns: Lowest point of your sell condition when ever your buy condition is triggered
HighestPivot(bool, bool, bool, float, float)
Calculate the high of your bullish condition
Parameters:
bool : bullish condition
bool : bearish condition
bool : candle buffer to prevent the script from crashing. Since were working with a Dynamic Length
float : Enter what you want to see the high off? High of the bar OR Close of the bar
float : Enter what you want to see the high off? High of the bar OR Open of the bar..... might seem pointless but some times the Highest open is Higher then the Highest Close
Returns: Highest point of your buy condition when ever your sell condition is triggered
lookBack(bool, bool)
Calculate how many bars since your bullish condition and bearish condition.
Parameters:
bool : enter bullish condition
bool : enter bearish condition
Returns: How many bars elapsed since the most recent condition. Bullish or bearish
Debugging
catchChecksLibrary "catchChecks"
Type Check for Function Builders to allow Single item to be
passed in, and determine what to do with the item, ie: need an x value?
function that allows label, line, box, float, or even a string..
check item type? string ? 'str.tonumber(_item)' can be in the same
switch as a 'line.get_price(_item, bar_index)' both outputting float
or for pulling a value from simple, array, or matrix, one function
that can switch between them. reduce overhead of many functions.
there are many ways to use this tool, the simplest may be
string/floats on one switch or grabbing colors from line/fill/label
please Share any great recipes you come up with!
typeIs(_temp, _doMeth)
Input anything..
Determine what it is.
Parameters:
_temp : (any) Matrix, Array, or Simple Item
_doMeth : (bool) True for M/A/S , false for int/float/string.. etc..
Returns: (string) Type of item checked. ('bool' .. or 'array'.. etc..)
MiteTricksLibrary "MiteTricks"
Matrix Global Registry.
Get, Set, automatic growing, universal get/set,
multi-matrix dictionaries, multi-dictionary matrixes..
add slice matrixes of any type, share one common global key registry
pull up an item from a category, and item name ie a table of info.
same cell needs a color, a size, a string, a value, etc..
all of which can be pulled up with the same group id, and key id.
just swap which matrix you pull the value from.
this has a side benefit of non-repainting and recalculating
when pulling values, changing inputs..
makes for very fast/clean usage..
benefit :
floats = value
strings = names
lines = drawn items
table =table of data items for this key
colors = color for line/table/fill,label..
all of those can be pulled with "get(_VALUES,_groupIDX,_keyIDX)" where only the values matrix needs be swapped, and the same item/coordinates remains for all the possible matrixes that item appears in.
also useful as a dictionary/registry for any given type of item,,
and goes very handy with floats/strings/colors/bools with my matrixautotable
very helpful when prototyping or doing development work as a shortcut.
initRegistry()
Registry inititalizer
Returns: registry of string matrix type
newbool(optional, optional, optional)
create bool type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is bool (na)
Returns: bool matrix of specified size and fill, or blank 2x2 for registry use
newbox(optional, optional, optional)
create box type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is box (na)
Returns: box matrix of specified size and fill, or blank 2x2 for registry use
newcolor(optional, optional, optional)
create color type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is color (na)
Returns: color matrix of specified size and fill, or blank 2x2 for registry use
newfloat(optional, optional, optional)
create float type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is float (na)
Returns: float matrix of specified size and fill, or blank 2x2 for registry use
newint(optional, optional, optional)
create int type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is int (na)
Returns: int matrix of specified size and fill, or blank 2x2 for registry use
newlabel(optional, optional, optional)
create label type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is label (na)
Returns: label matrix of specified size and fill, or blank 2x2 for registry use
newline(optional, optional, optional)
create line type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is line (na)
Returns: line matrix of specified size and fill, or blank 2x2 for registry use
newlinefill(optional, optional, optional)
create linefill type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is linefill(na)
Returns: linefill matrix of specified size and fill, or blank 2x2 for registry use
newstring(optional, optional, optional)
create string type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is string (na)
Returns: string matrix of specified size and fill, or blank 2x2 for registry use
newtable(optional, optional, optional)
create table type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is table (na)
Returns: table matrix of specified size and fill, or blank 2x2 for registry use
newfrom(INIT_FILL)
newfrom Matrix full of item input
Parameters:
INIT_FILL: item to fill (2x2) the matri and set type. a type(na) works
addrow(m, v)
addrow Add new row to matrix
Parameters:
m: matrix of type being added to
v: value of type being added to ( best leave NA on string for registry purposes)
addcolumn(matrix, value)
addcolumn
Parameters:
matrix: of type being added to
value: of type being added to ( best leave NA on string for registry purposes)
get(_VALS, _KEYREG, _GROUP, _KEY)
get Grabs value and returns single item
Parameters:
_VALS: Matrix Values slice
_KEYREG: Registry values matrix (strings)
_GROUP: name of group/category or int group key
_KEY: name of item to fetch from value registry or int key id
Returns: item
get(_VALS, _GROUP, _KEY)
get Grabs value and returns single item
Parameters:
_VALS: Matrix Values slice
_GROUP: name of group/category
_KEY: name of item to fetch from value registry
getgid(_KEYREG, _GROUP)
getgid
Parameters:
_KEYREG: Reg to pull group id from
_GROUP: group index int, or string name to get the other missing type
getkid(_KEYREG, _GROUP, _KEY)
getkid
Parameters:
_KEYREG: Reg to pull Key id from
_GROUP: group index int, or string name
_KEY: index of string key id to get it's ID int
getkey(_KEYREG, _GROUP, _KEY)
getkey
Parameters:
_KEYREG: Reg to pull Key id from
_GROUP: group index int, or string name for getting key string
_KEY: index of string key id to get it's match of other type
set(_VALS, _KEYREG, _GROUP, _KEY, _value)
set items to reg and matrix container
Parameters:
_VALS: Values matrix container
_KEYREG: Key registry
_GROUP: (string) Group/Category name
_KEY: (string) Key for item
_value: item
Returns: void
del(_VALS, _KEYREG, _GROUP, _KEY)
del grroup id
Parameters:
_VALS: Matrix Values slice
_KEYREG: Registry values matrix (strings)
_GROUP: name of group/category
_KEY: name of item to Delete from values and key
detached(_GROUP, _KEY, _VALUE)
detached make detached registry/val matrix
Parameters:
_GROUP: Name of first group
_KEY: Name of first item
_VALUE: Item of any type, sets the output type too.
threengine_global_automation_libraryLibrary "threengine_global_automation_library"
A collection of functions used for trade automation
getBaseCurrency()
Gets the base currency for the chart's ticker. Supported trade pairs are USD, USDT, USDC, BTC, and PERP.
Returns: Base currency as a string
getChartSymbol()
Get the current chart's symbol without the base currency appended to it. Supported trade paris are USD, USDT, USDC, BTC, and PERP.
Returns: Ssymbol and base currency
getDecimals()
Calculates how many decimals are on the quote price of the current market
Returns: The current deimal places on the market quote price
checkVar()
Plot a string as a label on the chart to test variable value. Use str.tostring() for any variable that isn't a string.
Returns: Label with stringified variable
getStrategyAlertMessage()
Generates stringified JSON for a limit order that can be passed to the strategy alert_message for a long entry.
Returns: Stringifed JSON for a long entry
taGetAdx()
Calculates the Average Directional Index
Returns: The value of ADX as a float
taGetEma()
Calculates the EMA based on a type, source, and length. Supported types are EMA, SMA, RMA, and WMA.
Returns: The value of the selected EMA
isBetweenTwoTimes()
Checks to see if within a rage based on two times
@retunrs true/false boolean
getAllTradeIDs()
This gets all closed trades and open trades
@retunrs an array of all open and closed trade ID's
getOpenTradeIDs()
This gets all open trades
@retunrs an array of all open trade ID's
orderAlreadyExists()
This checks to see if a provided order id uses the getAllTradeIDs() function to check
@retunrs an array of all open and closed trade ID's
orderCurrentlyExists()
This checks to see if a provided order id uses the getAllTradeIDs() function to check
Returns: an array of all open and closed trade ID's
getContractCount()
calulates the number of contracts you can buy with a set amount of capital and a limit price
Returns: number of contracts you can buy based on amount of capital you want to use and a price
getLadderSteps()
Returns: array of ladder entry prices and amounts based on total amount you want to invest across all ladder rungs and either a range between ladderStart and LadderStop based on specificed number of ladderRungs OR ladderStart, ladderRungs, and LadderSpacingPercent
UtilityFunctionsLibrary "UtilityFunctions"
Utility functions written by me
printLabelOnLastBar_string(string)
Prints string in a label on the last bar
Parameters:
string : value to print
Returns: void
printLabelOnLastBar_float(float)
Prints float in a label on the last bar
Parameters:
float : value to print
Returns: void
printSeriesInReverseOnLabels(series)
Prints a float series in labels in reverse (the first value is on the last candle, the second value is on the second to last candle, etc.)
Parameters:
series : float values to print
Returns: void
isPeriodDailyBased(string)
Returns true/false if the period is Daily based (1D, 3D, ...)
Parameters:
string : timeframe period
Returns: true/false
get_multiplier(string)
Gets the mutliplier of the timeframe passed compared to the current timeframe. If current TF is 5m and the passed timeframe period is 30m, the result will be 6
Parameters:
string : timeframe param
Returns: simple float of the multiplier
[LIB] Array / Matrix DisplayLibrary "ArrayMatrixHUD"
Show Array or Matrix Elements In Table
For Arrays: Set the number of rows you want the data displayed in and it will generate a table, calculating the columns based on the size of the array being displayed.
For Matrix: It will automatically match the Rows and Columns to the values in the matrix.
Note: On the left, the table shows the index of the array/matrix value starting at 1. So, to call that value from inside the array, subtract 1 from the index value to the left. For matrices, keep in mind that the row and column are also starting at one when trying to call a value from the matrix. The numbering of the values on the left is for display purposes only.
viewArray(_arrayName, _pos, _txtSize, _tRows)
Array Element Display (Supports float, int, string, and bool)
Parameters:
_arrayName : ID of Array to be Displayed
_pos : Position for Table
_txtSize : Size of Table Cell Text
_tRows : Number of Rows to Display Data In (columns will be calculated accordingly)
Returns: A Display of Array Values in a Table
viewMatrix(_matrixName, _pos, _txtSize)
Matrix Element Display (Supports float, int, string, and bool)
Parameters:
_matrixName : ID of Matrix to be Displayed
_pos : Position for Table
_txtSize : Size of Table Cell Text
Returns: A Display of Matrix Values in a Table
HTV_LibraryLibrary "HTV_LibraryV2"
up_bar() 'up_bar' checks true for every candle that closed above open price.
Returns: custom Series Bool
last_up_bar() 'last_up_bar' checks true for every last candle that closed above open price.
Returns: custom Series Bool
down_bar() 'down_bar' checks true for every candle that closed below open price.
Returns: custom Series Bool
last_down_bar() 'last_down_bar' checks true for every last candle that closed below open price.
Returns: custom Series Bool
TBR_Up() 'TBR_Up' checks true for every last confirmed 2 Bar Reversal.
Returns: custom Series Bool
TBR_Down() 'TBR_Down' checks true for every last confirmed 2 Bar Reversal.
Returns: custom Series Bool
TCR_Up() 'TCR_Up' checks true for every last confirmed 3 Candle Reversal.
Returns: custom Series Bool
TCR_Down() 'TCR_Down' checks true for every last confirmed 3 Candle Reversal.
Returns: custom Series Bool
f_fib() 'f_fib' gives a fibonacci number based on rising numericial order starting from 0
Returns: custom Series Bool
WHITE() uses color.rgb(r,g,b,t) function
Returns: literal color
WHITE_25T()
WHITE_50T()
WHITE_90T()
BLACK()
BLACK_25T()
BLACK_50T()
BLACK_90T()
RED()
RED_25T()
RED_50T()
RED_90T()
GREEN()
GREEN_25T()
GREEN_50T()
GREEN_90T()
BLUE()
BLUE_25T()
BLUE_50T()
BLUE_90T()
GREY()
GREY_25T()
GREY_50T()
GREY_90T()
NEON_YELLOW()
NEON_YELLOW_25T()
NEON_YELLOW_50T()
NEON_YELLOW_90T()
NEON_GREEN()
NEON_GREEN_25T()
NEON_GREEN_50T()
NEON_GREEN_90T()
NEON_PINK()
NEON_PINK_25T()
NEON_PINK_50T()
NEON_PINK_90T()
PURPLE()
PURPLE_25T()
PURPLE_50T()
PURPLE_90T()
SMA()
EMA()
WMA()
VWMA()
RMA()
HMA()
STMA()
ETMA()
_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.
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