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 :)
/////////////////////
Display
ObjectStackLibrary "ObjectStack"
init()
push()
push()
push()
push()
push()
nextIndex()
nextIndex()
nextIndex()
nextIndex()
nextIndex()
delete()
delete()
delete()
delete()
delete()
cleanOldest()
cleanOldest()
cleanOldest()
cleanOldest()
cleanOldest()
CRCHud - HUD Library (Heads Up Display)Library "CRCHud"
Library of functions which will contain functions that allow reusable HUD (Heads up Display) components to used from within other scripts
add_cell_change() - Adds a new cell to designated table which displays the data source value, the line color, data title, and automatically calculated %percent change stats based on lookback value supplied (default - previous bar)
UnicodeReplacementFunctionLibrary "UnicodeReplacementFunction"
Unicode Characters Replacement function for strings.
replaceFont(_str, _fontType) Unicode Character Replace Function
Parameters:
_str : String input
_fontType : Font Type Selector
Returns: Replaced Char String with any custom font type choosed
LabelHelperLibrary "LabelHelper"
Utility for managing active labels on the chart.
add(level, txt, labelColor, textColor) For displaying a lable at the last bar.
Parameters:
level : The value to display the label at.
txt : The text to show on the label.
labelColor : The color of the label.
textColor : The text color of the label.
Returns: The label being managed.
DrawIndicatorOnTheChartLibrary "DrawIndicatorOnTheChart"
this library is used to show an indicator (such RSI, CCI, MOM etc) on the main chart with indicator's horizontal lines in a window. Location of the window is calculated dynamically by last price movemements
drawIndicator(indicatorName, indicator, indicatorcolor, period, indimax_, indimin_, levels, precision, xlocation) draws the related indicator on the chart
Parameters:
indicatorName : is the indicator name as string such "RSI", "CCI" etc
indicator : is the indicator you want to show, such rsi(close, 14), mom(close, 10) etc
indicatorcolor : is the color of indicator line
period : is the length of the window to show
indimax_ : is the maximum value of the indicator, for example for RSI it's 100.0, if the indicator (such CCI, MOM etc) doesn't have maximum value then use "na"
indimin_ : is the minimum value of the indicator, for example for RSI it's 0.0, if the indicator (such CCI, MOM etc)doesn't have maximum value then use "na"
levels : is the levels of the array for the horizontal lines. for example if you want horizontal lines at 30.0, and 70.0 then use array.from(30.0, 70.0). if no horizontal lines then use array.from(na)
precision : is the precision/number of decimals that is used to show indicator values, for example for RSI set it 2
xlocation : is end location of the indicator window, for example if xlocation = 0 window is created on the index of the last bar/candle
Returns: none
amibrokerLibrary "amibroker"
This library consists of functions from amibroker that doesn't exist on tradingview pinescript. The example of these are the ExRem and Flip.
In the example below, I used ExRem to remove the excessive buy and sell signals. Meanwhile, I used the Flip to highlight the bg color when there is an open position.
exrem(series1, series2) Removes excessive signals. Pinescript version of ExRem in Amibroker (www.amibroker.com)
Parameters:
series1 : boolean
series2 : boolean
Returns: boolean
flip(series1, series2) works as a flip/flop device or "latch". Pinescript version of Flip in Amibroker: (www.amibroker.com)
Parameters:
series1 : boolan
series2 : boolean
Returns: boolean.
LabelsLibrary "Labels"
Functions to create labels, from simple to complex.
labelSimple()
Creates a label each time a condition is true. All label parameters can be customised.
_condition The condition which must evaluate true for the label to be printed.
_x The x location.
_y The y location.
_text The text to print on the label.
_color The colour of the label.
_textColor The colour of the text.
_style The style of the label.
_yloc The y location type.
Returns
An unnamed label object with the supplied characteristics. To give it a name, assign the output of the function to a label variable, as in the example below.
labelLast()
Creates a label each time a condition is true. All label parameters can be customised. + Option to keep only the most recent label. + Option to display the label a configurable number of bars ahead.
_offset How many bars ahead to draw the label.
_keepLast If true (the default), keeps only the most recent label. If false, prints labels up to the TradingView limit.
_condition The condition which must evaluate true for the label to be printed.
_y The y location.
_text The text to print on the label.
_color The colour of the label.
_textColor The colour of the text.
_style The style of the label.
_yloc The y location type.
Returns A named label object with the supplied characteristics.
labelTextAndFloat()
Creates a label each time a condition is true. All label parameters can be customised. Option to keep only the most recent label. Option to display the label a configurable number of bars ahead; otherwise the x location is fixed at the bar time. + Prints (optional) text and a floating-point number on the next line.
_offset How many bars ahead to draw the label.
_float The floating-point number that you want to display on the label.
_keepLast If true (the default), keeps only the most recent label. If false, prints labels up to the TradingView limit.
_condition The condition which must evaluate true for the label to be printed.
_y The y location.
_text The text to print on the label.
_color The colour of the label.
_textColor The colour of the text.
_style The style of the label.
_yloc The y location type.
Returns A named label object with the supplied characteristics.
labelTextAndFloatSigFig()
Creates a label each time a condition is true. All label parameters can be customised. Option to keep only the most recent label. Option to display the label a configurable number of bars ahead; otherwise the x location is fixed at the bar time. Prints (optional) text and a floating-point number on the next line + to a given number of significant figures.
_offset How many bars ahead to draw the label.
_sigNumFig The number of significant figures to display the floating-point number to.
_float The floating-point number that you want to display on the label.
_keepLast If true (the default), keeps only the most recent label. If false, prints labels up to the TradingView limit.
_condition The condition which must evaluate true for the label to be printed.
_y The y location.
_text The text to print on the label.
_color The colour of the label.
_textColor The colour of the text.
_style The style of the label.
_yloc The y location type.
Returns A named label object with the supplied characteristics.
labelTextAndFloatDecimals()
Creates a label each time a condition is true. All label parameters can be customised. Option to keep only the most recent label. Option to display the label a configurable number of bars ahead. Prints (optional) text and a floating-point number on the next line + to a given number of decimal places.
_offset How many bars ahead to draw the label.
_decimals The number of decimal places to display the floating-point number to.
_float The floating-point number that you want to display on the label.
_keepLast If true (the default), keeps only the most recent label. If false, prints labels up to the TradingView limit.
_condition The condition which must evaluate true for the label to be printed.
_y The y location.
_text The text to print on the label.
_color The colour of the label.
_textColor The colour of the text.
_style The style of the label.
_yloc The y location type.
Returns A named label object with the supplied characteristics.
Bursa_SectorLibrary "Bursa_Sector"
: List of stocks classified by sector in Bursa Malaysia (As of Oct 2021)
getSector()
This function will get the sector of current stock that listed in Bursa Malaysia
CreateAndShowZigzagLibrary "CreateAndShowZigzag"
Functions in this library creates/updates zigzag array and shows the zigzag
getZigzag(zigzag, prd, max_array_size) calculates zigzag using period
Parameters:
zigzag : is the float array for the zigzag (should be defined like "var zigzag = array.new_float(0)"). each zigzag points contains 2 element: 1. price level of the zz point 2. bar_index of the zz point
prd : is the length to calculate zigzag waves by highest(prd)/lowest(prd)
max_array_size : is the maximum number of elements in zigzag, keep in mind each zigzag point contains 2 elements, so for example if it's 10 then zigzag has 10/2 => 5 zigzag points
Returns: dir that is the current direction of the zigzag
showZigzag(zigzag, oldzigzag, dir, upcol, dncol) this function shows zigzag
Parameters:
zigzag : is the float array for the zigzag (should be defined like "var zigzag = array.new_float(0)"). each zigzag points contains 2 element: 1. price level of the zz point 2. bar_index of the zz point
oldzigzag : is the float array for the zigzag, you get copy the zigzag array to oldzigzag by "oldzigzag = array.copy(zigzay)" before calling get_zigzag() function
dir : is the direction of the zigzag wave
upcol : is the color of the line if zigzag direction is up
dncol : is the color of the line if zigzag direction is down
Returns: null
LineGetPriceOnLogScaleLibrary "LineGetPriceOnLogScale"
This library provides a way to calculate the y-coordinate of a line on a specified bar when the chart scale is Log.
The built-in `line.get_price()` function only works with linear scale and gives incorrect results when the chart is in Log scale.
The library only works with `bar_index` values and `xloc.bar_index`-based lines, `time`-based lines will cause errors to appear.
coordGetPriceLog(x1, y1, x2, y2, xi) Calculates the y-coordinate on the specified bar on the logarithmic scale.
Only coordinates based on bar index are applicable, bar time will throw an error.
Parameters:
x1 : First X coordinate of a line, index of the bar where the line starts.
y1 : First Y coordinate of a line, price on the price scale.
x2 : Second X coordinate of a line, index of the bar where the line ends.
y2 : Second Y coordinate of a line, price on the price scale.
xi : Index of the bar for which the price should be calculated.
Returns: Price of the line on the bar specified in `xi`, on the logarithmic scale.
lineGetPriceLog(_line, xi) Calculates the y-coordinate on the specified bar for the logarithmic scale. Takes a line.
Only lines drawn based on `xloc.bar_index` are applicable, `xloc.bar_time` will throw and error.
Parameters:
_line : The line for which the price is calculated.
xi : Index of the bar for which the bar should calculate the price.
Returns: Price of the line on the bar specified in `xi`, on the logarithmic scale.
SignificantFiguresLibrary "SignificantFigures"
sigFig(float _float, int _figures)
@description Takes a floating-point number - one that can, but doesn't have to, include a decimal point - and converts it to a floating-point number with only a certain number of digits left. For example, say you want to display a variable from your script to the user and it comes out to something like 45.366666666666666666666667 or whatever. That looks awful when you, for example, print it in a label. Now you could round it up to the nearest integer easily using a built-in function, or even to a certain number of decimal places using a reasonably simple custom function. But that's a bit arbitrary. Suppose you don't know what asset the script will be used on, and so you can't predict what the price is, and what the value will turn out to be. It could be 0.00045366666666666666666666667 instead. Now if you round it up to 3 decimal places it comes out as 0.000, which is useless. My function will round that number to 0.0004536 instead, if told to do it to 4 significant digits.
I think this is more friendly.
@function Converts float with arbitrary number of digits to one with a specified number of significant figures.
@param float _float is the floating-point number to manipulate.
@param int _figures is the number of significant figures you want.
@returns Returns a float with the specified number of significant figures
FunctionDatestringLibrary "FunctionDatestring"
Methods to stringify date/time, altho there is already builtin support for it.
datetime(unixtime) a stringified date stamp at specified unix time.
Parameters:
unixtime : int unix timestamp.
Returns: string
date_(unixtime) a stringified date stamp at specified unix time.
Parameters:
unixtime : int unix timestamp.
Returns: string
time_(unixtime) a stringified date stamp at specified unix time.
Parameters:
unixtime : int unix timestamp.
Returns: string
STRATEGY TESTER ENGINE - ON CHART DISPLAY - PLUG & PLAYSo i had this idea while ago when @alexgrover published a script and dropped a nugget in between which replicates the result of strategy tester on chart as an indicator.
So it seemed fair to use one of his strategy to display the results.
This strategy tester can now be used in replay mode like an indicator and you can see what happen at a particular section of the chart which was is not possible in default strategy tester results of TV.
Please read how each result is calculated so you will know what you are using.
This engine shows most common results of strategy tester in a single screen, which are as follows:
1. Starting Capital
2. Current Profit Percentage
3. Max Profit Percentage
4. Gross Profit
5. Gross Loss
6. Total Closed Trades
7. Total Trades Won
8. Total Trades Lost
9. Percentage Profitable
10. Profit Factor
11. Current Drawdown
12. Max Drawdown
13. Liquidation
So elaborating on what is what:
1. Starting Capital - This stays 0, which signifies your starting balance as 0%. It is set to 0 so we can compare all other results without any change in variables. If set to 100, then all the results will be increased by 100. Some users might find it useful to set it to 100, then they can change code on line 41 from to and it should show starting balance as 100%.
2. Current Profit Percentage - This shows your current profit adjusted to current price of the candle, not like TV which shows after candle is close. There is a comment on the line 38 which can be removed and your can see unrealized profit as well in this section. Please note that this will affect Draw-down calculations later in this section.
3. Max Profit Percentage - This will show you your max profit achieved during your strategy run, which was not possible yet to see via strategy tester. So, now you can see how much profit was achieved by your strategy during the run and you can compare it with chart to see what happens during bull-run or bear-run, so you can further optimize your strategy to best suit your desired results.
4. Gross Profit - This is total percentage of profit your strategy achieved during entire run as if you never had any losses.
5. Gross Loss - This is total percentage of loss your strategy achieved during entire run as if you never had any profits.
6. Total Closed Trades - This is total number of trades that your strategy has executed so far.
7. Total Trades Won - This is the total number of trades that your strategy has executed that resulted in positive increase in equity.
8. Totals Trades Lost - This is the total number of trades that your strategy has executed that resulted in decrease in equity.
9. Percentage Profitable - This is the ratio between your current total winning trades divided by total closed trades, and finally multiplied by 100 to get percentage results.
10. Profit Factor - This is the ratio between Gross Profit and Gross Loss, so if profit factor is 2, then it indicates that you are set to gain 2 times per your risk per trade on average when total trades are executed.
11. Current Drawdown - This is important section and i want you to read this carefully. Here draw-down is calculated very differently than what TV shows. TV has access to candle data and calculates draw-down accordingly as per number of trades closed, but here DD is calculated as difference between max profit achieved and current profit. This way you can see how much percentage you are down from max peak of equity at current point in time. You can do back-test of the data and see when peak was achieved and how much your strategy did a draw-down candle by candle.
12. Max Drawdown - This is also calculated differently same as above, current draw-down. Here you can see how much max DD your strategy did from a peak profit of equity. This is not set as max profit percentage is set because you will see single number on display, while idea is to keep it custom. I will explain.
So lets say, your max DD on TV is 30%. Here this is of no use to see Max DD , as some people might want to see what was there max DD 1000 candles back or 10 candle back. So this will show you your max DD from the data you select. TV shows 25000 candle data in a chart if you go back, you can set the counter to 24999 and it will show you max DD as shown on TV, but if you want custom section to show max DD , it is now possible which was not possible before.
Also, now let's say you put DD as 24999 and open a chart of an asset that was listed 1 week ago, now on 1H chart max DD will never show up until you reach 24999 candle in data history, but with this you can now enter a manual number and see the data.
13. Liquidation - This is an interesting feature, so now when your equity balance is less than 0 and your draw-down goes to -100, it will show you where and at what point in time you got liquidated by adding a red background color in the entire section. This is the most fun part of this script, while you can only see max DD on TV.
------------------------------------------------------------------------------
How to Use -
1 word, plug and play. Yes. Actual codes start from line 33.
select overlay=false or remove it from the title in your strategy on first line,
Just copy the codes from line 33 to 103,
then go to end section of your strategy and paste the entire code from line 33 to line 103,
see if you have any duplicate variable, edit it,
Add to chart.
What you see above is very contracted view. Here is how it looks when zoomed in.
imgur.com
----------------------------------------------------------------------------------
Feel free to edit and share and use. If you use it in your scripts, drop me tag. Cheers.
Label Display DemoA label function for display an arbitrary value above or below the chart.
There is no convenient way to display the value of a variable in pinescript. This is most convenient way I found.
It will follow the current bar (the position is calculated with highest/lowest and atr value, as such it will never display over the chart)
In this script we display ATR for the example
Price above/below EMAThis script will give you red/green columns to indicate if price is above or below a certain EMA. With Candlestick charting, we are looking for price in relation to the 8 ema Trigger Line (T-Line). You can adjust this indicator to fit your need. Simple, but nice to quickly see.
Oops. Last line's title should be "Sell". Doesn't affect display though.