Time█ OVERVIEW
This library is a Pine Script™ programmer’s tool containing a variety of time related functions to calculate or measure time, or format time into string variables.
█ CONCEPTS
`formattedTime()`, `formattedDate()` and `formattedDay()`
Pine Script™, like many other programming languages, uses timestamps in UNIX format, expressed as the number of milliseconds elapsed since 00:00:00 UTC, 1 January 1970. These three functions convert a UNIX timestamp to a formatted string for human consumption.
These are examples of ways you can call the functions, and the ensuing results:
CODE RESULT
formattedTime(timenow) >>> "00:40:35"
formattedTime(timenow, "short") >>> "12:40 AM"
formattedTime(timenow, "full") >>> "12:40:35 AM UTC"
formattedTime(1000 * 60 * 60 * 3.5, "HH:mm") >>> "03:30"
formattedDate(timenow, "short") >>> "4/30/22"
formattedDate(timenow, "medium") >>> "Apr 30, 2022"
formattedDate(timenow, "full") >>> "Saturday, April 30, 2022"
formattedDay(timenow, "E") >>> "Sat"
formattedDay(timenow, "dd.MM.yy") >>> "30.04.22"
formattedDay(timenow, "yyyy.MM.dd G 'at' hh:mm:ss z") >>> "2022.04.30 AD at 12:40:35 UTC"
These functions use str.format() and some of the special formatting codes it allows for. Pine Script™ documentation does not yet contain complete specifications on these codes, but in the meantime you can find some information in the The Java™ Tutorials and in Java documentation of its MessageFormat class . Note that str.format() implements only a subset of the MessageFormat features in Java.
`secondsSince()`
The introduction of varip variables in Pine Script™ has made it possible to track the time for which a condition is true when a script is executing on a realtime bar. One obvious use case that comes to mind is to enable trades to exit only when the exit condition has been true for a period of time, whether that period is shorter that the chart's timeframe, or spans across multiple realtime bars.
For more information on this function and varip please see our Using `varip` variables publication.
`timeFrom( )`
When plotting lines , boxes , and labels one often needs to calculate an offset for past or future end points relative to the time a condition or point occurs in history. Using xloc.bar_index is often the easiest solution, but some situations require the use of xloc.bar_time . We introduce `timeFrom()` to assist in calculating time-based offsets. The function calculates a timestamp using a negative (into the past) or positive (into the future) offset from the current bar's starting or closing time, or from the current time of day. The offset can be expressed in units of chart timeframe, or in seconds, minutes, hours, days, months or years. This function was ported from our Time Offset Calculation Framework .
`formattedNoOfPeriods()` and `secondsToTfString()`
Our final two offerings aim to confront two remaining issues:
How much time is represented in a given timestamp?
How can I produce a "simple string" timeframe usable with request.security() from a timeframe expressed in seconds?
`formattedNoOfPeriods()` converts a time value in ms to a quantity of time units. This is useful for calculating a difference in time between 2 points and converting to a desired number of units of time. If no unit is supplied, the function automatically chooses a unit based on a predetermined time step.
`secondsToTfString()` converts an input time in seconds to a target timeframe string in timeframe.period string format. This is useful for implementing stepped timeframes relative to the chart time, or calculating multiples of a given chart timeframe. Results from this function are in simple form, which means they are useable as `timeframe` arguments in functions like request.security() .
█ NOTES
Although the example code is commented in detail, the size of the library justifies some further explanation as many concepts are demonstrated. Key points are as follows:
• Pivot points are used to draw lines from. `timeFrom( )` calculates the length of the lines in the specified unit of time.
By default the script uses 20 units of the charts timeframe. Example: a 1hr chart has arrows 20 hours in length.
• At the point of the arrows `formattedNoOfPeriods()` calculates the line length in the specified unit of time from the input menu.
If “Use Input Time” is disabled, a unit of time is automatically assigned.
• At each pivot point a label with a formatted date or time is placed with one of the three formatting helper functions to display the time or date the pivot occurred.
• A label on the last bar showcases `secondsSince()` . The label goes through three stages of detection for a timed alert.
If the difference between the high and the open in ticks exceeds the input value, a timer starts and will turn the label red once the input time is exceeded to simulate a time-delayed alert.
• In the bottom right of the screen `secondsToTfString()` posts the chart timeframe in a table. This can be multiplied from the input menu.
Look first. Then leap.
█ FUNCTIONS
formattedTime(timeInMs, format)
Converts a UNIX timestamp (in milliseconds) to a formatted time string.
Parameters:
timeInMs : (series float) Timestamp to be formatted.
format : (series string) Format for the time. Optional. The default value is "HH:mm:ss".
Returns: (string) A string containing the formatted time.
formattedDate(timeInMs, format)
Converts a UNIX timestamp (in milliseconds) to a formatted date string.
Parameters:
timeInMs : (series float) Timestamp to be formatted.
format : (series string) Format for the date. Optional. The default value is "yyyy-MM-dd".
Returns: (string) A string containing the formatted date.
formattedDay(timeInMs, format)
Converts a UNIX timestamp (in milliseconds) to the name of the day of the week.
Parameters:
timeInMs : (series float) Timestamp to be formatted.
format : (series string) Format for the day of the week. Optional. The default value is "EEEE" (complete day name).
Returns: (string) A string containing the day of the week.
secondsSince(cond, resetCond)
The duration in milliseconds that a condition has been true.
Parameters:
cond : (series bool) Condition to time.
resetCond : (series bool) When `true`, the duration resets.
Returns: The duration in seconds for which `cond` is continuously true.
timeFrom(from, qty, units)
Calculates a +/- time offset in variable units from the current bar's time or from the current time.
Parameters:
from : (series string) Starting time from where the offset is calculated: "bar" to start from the bar's starting time, "close" to start from the bar's closing time, "now" to start from the current time.
qty : (series int) The +/- qty of units of offset required. A "series float" can be used but it will be cast to a "series int".
units : (series string) String containing one of the seven allowed time units: "chart" (chart's timeframe), "seconds", "minutes", "hours", "days", "months", "years".
Returns: (int) The resultant time offset `from` the `qty` of time in the specified `units`.
formattedNoOfPeriods(ms, unit)
Converts a time value in ms to a quantity of time units.
Parameters:
ms : (series int) Value of time to be formatted.
unit : (series string) The target unit of time measurement. Options are "seconds", "minutes", "hours", "days", "weeks", "months". If not used one will be automatically assigned.
Returns: (string) A formatted string from the number of `ms` in the specified `unit` of time measurement
secondsToTfString(tfInSeconds, mult)
Convert an input time in seconds to target string TF in `timeframe.period` string format.
Parameters:
tfInSeconds : (simple int) a timeframe in seconds to convert to a string.
mult : (simple float) Multiple of `tfInSeconds` to be calculated. Optional. 1 (no multiplier) is default.
Returns: (string) The `tfInSeconds` in `timeframe.period` format usable with `request.security()`.
Indicators and strategies
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()
AutoFiboRetraceLibrary "AutoFiboRetrace"
TODO: add library description here
fun(x) TODO: add function description here
Parameters:
x : TODO: add parameter x description here
Returns: TODO: add what function returns
ADX FunctionsLibrary "ADX"
adx(dilen, adxLen)
Parameters:
dilen : Length of the Directional Index.
adxLen : Length (smoothing) of the Average Directional Index.
Returns:
honest personal libraryLibrary "honestpersonallibrary"
thestratnumber() this will return the number 1,2 or 3 using the logic from Rob Smiths #thestrat which uses these type of bars for setups
getBodySize() Gets the current candle's body size (in POINTS, divide by 10 to get pips)
Returns: The current candle's body size in POINTS
getTopWickSize() Gets the current candle's top wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's top wick size in POINTS
getBottomWickSize() Gets the current candle's bottom wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's bottom wick size in POINTS
getBodyPercent() Gets the current candle's body size as a percentage of its entire size including its wicks
Returns: The current candle's body size percentage
strictBearPinBar(float, float) This it to find pinbars with a very long wick compared to the body that are bearish
Parameters:
float : minTopMulitplier (default=4) The minimum number of times that the top wick has to be bigger than the candle body size
float : maxBottomMultiplier (default=2) The maximum number of times that the bottom wick can be bigger than the candle body size
Returns: a bool function true if current candle is withing the parameters
strictBullPinBar(float, float) This it to find pinbars with a very long wick compared to the body that are bearish
Parameters:
float : minTopMulitplier (default=4) The minimum number of times that the top wick has to be bigger than the candle body size
float : maxBottomMultiplier (default=2) The maximum number of times that the bottom wick can be bigger than the candle body size
Returns: a bool function true if current candle is withing the parameters
FunctionIntrabarCrossValueLibrary "FunctionIntrabarCrossValue"
intrabar_cross_value(a, b, step) Find the minimum difference of a intrabar cross and return its median value.
Parameters:
a : float, series a.
b : float, series b.
step : float, step to iterate x axis, default=0.01
Returns: float
BitcoinHalvingLibrary "BitcoinHalving"
Displays where Bitcoin's halvings have been
getDates() List of Bitcoin halving dates
Returns: array with timestamp dates
isHalvingDay() Checks if the current day is a halving day
Returns: bool
matrixautotableLibrary "matrixautotable"
Automatic Table from Matrixes with pseudo correction for na values and default color override for missing values. uses overloads in cases of cheap float only, with additional addon for strings next, then cell colors, then text colors, and tooltips last.. basic size and location are auto, include the template to speed this up...
TODO : make bools version
var string group_table = ' Table'
var int _tblssizedemo = input.int ( 10 )
string tableYpos = input.string ( 'middle' , '↕' , inline = 'place' , group = group_table, options= )
string tableXpos = input.string ( 'center' , '↔' , inline = 'place' , group = group_table, options= , tooltip='Position on the chart.')
int _textSize = input.int ( 1 , 'Table Text Size' , inline = 'place' , group = group_table)
var matrix _floatmatrix = matrix.new (_tblssizedemo, _tblssizedemo, 0 )
var matrix _stringmatrix = matrix.new (_tblssizedemo, _tblssizedemo, 'test' )
var matrix _bgcolormatrix = matrix.new (_tblssizedemo, _tblssizedemo, color.white )
var matrix _textcolormatrix = matrix.new (_tblssizedemo, _tblssizedemo, color.black )
var matrix _tooltipmatrix = matrix.new (_tblssizedemo, _tblssizedemo, 'tool' )
// basic table ready to go with the aboec matrixes (replace in your code)
// for demo purpose, random colors, random nums, random na vals
if barstate.islast
varip _xsize = matrix.rows (_floatmatrix) -1
varip _ysize = matrix.columns (_floatmatrix) -1
for _xis = 0 to _xsize -1 by 1
for _yis = 0 to _ysize -1 by 1
_randomr = int(math.random(50,250))
_randomg = int(math.random(50,250))
_randomb = int(math.random(50,250))
_randomt = int(math.random(10,90 ))
bgcolor = color.rgb(250 - _randomr, 250 - _randomg, 250 - _randomb, 100 - _randomt )
txtcolor = color.rgb(_randomr, _randomg, _randomb, _randomt )
matrix.set(_bgcolormatrix ,_yis,_xis, bgcolor )
matrix.set(_textcolormatrix ,_yis,_xis, txtcolor)
matrix.set(_floatmatrix ,_yis,_xis, _randomr)
// random na
_ymiss = math.floor(math.random(0, _yis))
_xmiss = math.floor(math.random(0, _xis))
matrix.set( _floatmatrix ,_ymiss, _xis, na)
matrix.set( _stringmatrix ,_ymiss, _xis, na)
matrix.set( _bgcolormatrix ,_ymiss, _xis, na)
matrix.set( _textcolormatrix ,_ymiss, _xis, na)
matrix.set( _tooltipmatrix ,_ymiss, _xis, na)
// import here
import kaigouthro/matrixautotable/1 as mtxtbl
// and render table..
mtxtbl.matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix, _textSize ,tableYpos ,tableXpos)
matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix, _textSize, tableYpos, tableXpos) matrixtable
Parameters:
_floatmatrix : float vals
_stringmatrix : string
_bgcolormatrix : color
_textcolormatrix : color
_tooltipmatrix : string
_textSize : int
tableYpos : string
tableXpos : string
matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _textSize, tableYpos, tableXpos) matrixtable
Parameters:
_floatmatrix : float vals
_stringmatrix : string
_bgcolormatrix : color
_textcolormatrix : color
_textSize : int
tableYpos : string
tableXpos : string
matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _txtdefcol, _textSize, tableYpos, tableXpos) matrixtable
Parameters:
_floatmatrix : float vals
_stringmatrix : string
_bgcolormatrix : color
_txtdefcol : color
_textSize : int
tableYpos : string
tableXpos : string
matrixtable(_floatmatrix, _stringmatrix, _txtdefcol, _bgdefcol, _textSize, tableYpos, tableXpos) matrixtable
Parameters:
_floatmatrix : float vals
_stringmatrix : string
_txtdefcol : color
_bgdefcol : color
_textSize : int
tableYpos : string
tableXpos : string
matrixtable(_floatmatrix, _txtdefcol, _bgdefcol, _textSize, tableYpos, tableXpos) matrixtable
Parameters:
_floatmatrix : float vals
_txtdefcol : color
_bgdefcol : color
_textSize : int
tableYpos : string
tableXpos : string
Intraday High/LowLibrary "IntradayHighLow"
Provides functions calculating the intraday high/low of values.
IntradayHigh(val) Calculates the intraday high of a series.
Parameters:
val : Series to use ('high' is used if no argument is supplied).
Returns: The intraday high for the series.
IntradayLow(val) Calculates the intraday low of a series.
Parameters:
val : Series to use ('low' is used if no argument is supplied).
Returns: The intraday low for the series.
MonthlyReturnsVsMarketLibrary "MonthlyReturnsVsMarket" is a repackaging of the script here
Credits to @QuantNomad for orginal script
Now you can avoid to pollute your own strategy's code with the monthly returns table code and just import the library and call displayMonthlyPnL(int precision) function
To be used in strategy scripts.
StapleIndicatorsLibrary "StapleIndicators"
This Library provides some common indicators commonly referenced from other studies in Pine Script
squeeze(bbSrc, bbPeriod, bbDev, kcSrc, kcPeriod, kcATR, signalPeriod) Volatility Squeeze
Parameters:
bbSrc : (Optional) Bollinger Bands Source. By default close
bbPeriod : (Optional) Bollinger Bands Period. By default 20
bbDev : (Optional) Bollinger Bands Standard Deviation. By default 2.0
kcSrc : (Optional) Keltner Channel Source. By default close
kcPeriod : (Optional) Keltner Channel Period. By default 20
kcATR : (Optional) Keltner Channel ATR Multiplier. By default 1.5
signalPeriod : (Optional) Keltner Channel ATR Multiplier. By default 1.5
Returns:
adx(diPeriod, adxPeriod, signalPeriod, adxTier1, adxTier2, adxTier3) ADX: Average Directional Index
Parameters:
diPeriod : (Optional) Directional Indicator Period. By default 14
adxPeriod : (Optional) ADX Smoothing. By default 14
signalPeriod : (Optional) Signal Period. By default 13
adxTier1 : (Optional) ADX Tier #1 Level. By default 20
adxTier2 : (Optional) ADX Tier #2 Level. By default 15
adxTier3 : (Optional) ADX Tier #3 Level. By default 10
Returns:
smaPreset(srcMa) Delivers a set of frequently used Simple Moving Averages
Parameters:
srcMa : (Optional) MA Source. By default 'close'
Returns:
emaPreset(srcMa) Delivers a set of frequently used Exponential Moving Averages
Parameters:
srcMa : (Optional) MA Source. By default 'close'
Returns:
maSelect(ma, srcMa) Filters and outputs the selected MA
Parameters:
ma : (Optional) MA text. By default 'Ema-21'
srcMa : (Optional) MA Source. By default 'close'
Returns: maSelected
periodAdapt(modeAdaptative, src, maxLen, minLen) Adaptative Period
Parameters:
modeAdaptative : (Optional) Adaptative Mode. By default 'Average'
src : (Optional) Source. By default 'close'
maxLen : (Optional) Max Period. By default '60'
minLen : (Optional) Min Period. By default '4'
Returns: periodAdaptative
azlema(modeAdaptative, srcMa) Azlema: Adaptative Zero-Lag Ema
Parameters:
modeAdaptative : (Optional) Adaptative Mode. By default 'Average'
srcMa : (Optional) MA Source. By default 'close'
Returns: azlema
ssma(lsmaVar, srcMa, periodMa) SSMA: Smooth Simple MA
Parameters:
lsmaVar : Linear Regression Curve.
srcMa : (Optional) MA Source. By default 'close'
periodMa : (Optional) MA Period. By default '13'
Returns: ssma
jvf(srcMa, periodMa) Jurik Volatility Factor
Parameters:
srcMa : (Optional) MA Source. By default 'close'
periodMa : (Optional) MA Period. By default '7'
Returns:
jBands(srcMa, periodMa) Jurik Bands
Parameters:
srcMa : (Optional) MA Source. By default 'close'
periodMa : (Optional) MA Period. By default '7'
Returns:
jma(srcMa, periodMa, phase) Jurik MA (JMA)
Parameters:
srcMa : (Optional) MA Source. By default 'close'
periodMa : (Optional) MA Period. By default '7'
phase : (Optional) Phase. By default '50'
Returns: jma
maCustom(ma, srcMa, periodMa, lrOffset, almaOffset, almaSigma, jmaPhase, azlemaMode) Creates a custom Moving Average
Parameters:
ma : (Optional) MA text. By default 'Ema'
srcMa : (Optional) MA Source. By default 'close'
periodMa : (Optional) MA Period. By default '13'
lrOffset : (Optional) Linear Regression Offset. By default '0'
almaOffset : (Optional) Alma Offset. By default '0.85'
almaSigma : (Optional) Alma Sigma. By default '6'
jmaPhase : (Optional) JMA Phase. By default '50'
azlemaMode : (Optional) Azlema Adaptative Mode. By default 'Average'
Returns: maTF
AllTimeHighLowLibrary "AllTimeHighLow"
Provides functions calculating the all-time high/low of values.
hi(val) Calculates the all-time high of a series.
Parameters:
val : Series to use (`high` is used if no argument is supplied).
Returns: The all-time high for the series.
lo(val) Calculates the all-time low of a series.
Parameters:
val : Series to use (`low` is used if no argument is supplied).
Returns: The all-time low for the series.
HighTimeframeSamplingLibrary "HighTimeframeSampling"
Library for sampling high timeframe (HTF) data. Returns an array of historical values, an arbitrary historical value, or the highest/lowest value in a range, spending a single security() call.
An optional pass-through for the chart timeframe is included. Other than that case, the data is fixed and does not alter over the course of the HTF bar. It behaves consistently on historical and elapsed realtime bars.
The first version returns floating-point numbers only. I might extend it if there's interest.
🙏 Credits: This library is (yet another) attempt at a solution of the problems in using HTF data that were laid out by Pinecoders - to whom, especially to Luc F, many thanks are due - in "security() revisited" - which I recommend you consult first. Go ahead, I'll wait.
All code is my own.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
WHAT'S THE PROBLEM? OR, WHY NOT JUST USE SECURITY()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are many difficulties with using HTF data, and many potential solutions. It's not really possible to convey it only in words: you need to see it on a chart.
Before using this library, please refer to my other HTF library, HighTimeframeTiming: which explains it extensively, compares many different solutions, and demonstrates (what I think are) the advantages of using this very library, namely, that it's stable, accurate, versatile and inexpensive. Then if you agree, come back here and choose your function.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MOAR EXPLANATION
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
🧹 Housekeeping: To see which plot is which, turn line labels on: Settings > Scales > Indicator Name Label. Vertical lines at the top of the chart show the open of a HTF bar: grey for historical and white for real-time bars.
‼ LIMITATIONS: To avoid strange behaviour, use this library on liquid assets and at chart timeframes high enough to reliably produce updates at least once per bar period.
A more conventional and universal limitation is that the library does not offer an unlimited view of historical bars. You need to define upfront how many HTF bars you want to store. Very large numbers might conceivably run into data or performance issues.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BRING ON THE FUNCTIONS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@function f_HTF_Value(string _HTF, float _source, int _arrayLength, int _HTF_Offset, bool _useLiveDataOnChartTF=false)
Returns a floating-point number from a higher timeframe, with a historical operator within an abitrary (but limited) number of bars.
@param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises. The input timeframe cannot be lower than the chart timeframe or an error is thrown.
@param float _source is the source value that you want to sample, e.g. close, open, etc., or you can use any floating-point number.
@param int _arrayLength is the number of HTF bars you want to store and must be greater than zero. You can't go back further in history than this number of bars (minus one, because the current/most recent available bar is also stored).
@param int _HTF_Offset is the historical operator for the value you want to return. E.g., if you want the most recent fixed close, _source=close and _HTF_Offset = 0. If you want the one before that, _HTF_Offset=1, etc.
The number of HTF bars to look back must be zero or more, and must be one less than the number of bars stored.
@param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
This means that on default settings, on the chart timeframe, it matches the raw source values from security(){0}.
You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
@returns a floating-point value that you requested from the higher timeframe.
@function f_HTF_Array(string _HTF, float _source, int _arrayLength, bool _useLiveDataOnChartTF=false, int _startIn, int _endIn)
Returns an array of historical values from a higher timeframe, starting with the current bar. Optionally, returns a slice of the array. The array is in reverse chronological order, i.e., index 0 contains the most recent value.
@param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises. The input timeframe cannot be lower than the chart timeframe or an error is thrown.
@param float _source is the source value that you want to sample, e.g. close, open, etc., or you can use any floating-point number.
@param int _arrayLength is the number of HTF bars you want to keep in the array.
@param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
This means that on default settings, on the chart timeframe, it matches raw source values from security().
You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
@param int _startIn is the array index to begin taking a slice. Must be at least one less than the length of the array; if out of bounds it is corrected to 0.
@param int _endIn is the array index BEFORE WHICH to end the slice. If the ending index of the array slice would take the slice past the end of the array, it is corrected to the end of the array. The ending index of the array slice must be greater than or equal to the starting index. If the end is less than the start, the whole array is returned. If the starting index is the same as the ending index, an empty array is returned. If either the starting or ending index is negative, the entire array is returned (which is the default behaviour; this is effectively a switch to bypass the slicing without taking up an extra parameter).
@returns an array of HTF values.
@function f_HTF_Highest(string _HTF="", float _source, int _arrayLength, bool _useLiveDataOnChartTF=true, int _rangeIn)
Returns the highest value within a range consisting of a given number of bars back from the most recent bar.
@param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises. The input timeframe cannot be lower than the chart timeframe or an error is thrown.
@param float _source is the source value that you want to sample, e.g. close, open, etc., or you can use any floating-point number.
@param int _arrayLength is the number of HTF bars you want to store and must be greater than zero. You can't have a range greater than this number.
@param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
This means that on default settings, on the chart timeframe, it matches raw source values from security().
You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
@param _rangeIn is the number of bars to include in the range of bars from which we want to find the highest value. It is NOT the historical operator of the last bar in the range. The range always starts at the current bar. A value of 1 doesn't make much sense but the function will generously return the only value it can anyway. A value less than 1 doesn't make sense and will return an error. A value that is higher than the number of stored values will be corrected to equal the number of stored values.
@returns a floating-point number representing the highest value in the range.
@function f_HTF_Lowest(string _HTF="", float _source, int _arrayLength, bool _useLiveDataOnChartTF=true, int _rangeIn)
Returns the lowest value within a range consisting of a given number of bars back from the most recent bar.
@param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises. The input timeframe cannot be lower than the chart timeframe or an error is thrown.
@param float _source is the source value that you want to sample, e.g. close, open, etc., or you can use any floating-point number.
@param int _arrayLength is the number of HTF bars you want to store and must be greater than zero. You can't go back further in history than this number of bars (minus one, because the current/most recent available bar is also stored).
@param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
This means that on default settings, on the chart timeframe, it matches raw source values from security().
You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
@param _rangeIn is the number of bars to include in the range of bars from which we want to find the highest value. It is NOT the historical operator of the last bar in the range. The range always starts at the current bar. A value of 1 doesn't make much sense but the function will generously return the only value it can anyway. A value less than 1 doesn't make sense and will return an error. A value that is higher than the number of stored values will be corrected to equal the number of stored values.
@returns a floating-point number representing the lowest value in the range.
Strings█ OVERVIEW
This library provides string manipulation functions to complement the Pine Script™ `str.*()` built-in functions.
█ CONCEPTS
At the time our String Manipulation Framework was published, there was little in the way of built-in functions to manipulate strings. Since then, we have witnessed several meaningful developments on this front by the nimble Pine team. The newly released functions (including the ones in this blog post ) have deprecated most of our functions. This library captures the small handful of functions we think are still pertinent. It is worth noting that, thanks to the new string built-ins in Pine Script™, these functions greatly outperform their earlier counterparts, both performance-wise and because they can return values of simple form, which are a necessity in some circumstances, such as when used as arguments to some parameters of request.security() .
█ NOTES
`leftOf()` and `rightOf()`
Using the functions in this library is straightforward. The `leftOf()` and `rightOf()` functions extract the part of a string that is to the left or to the right of another string or character. This can be useful to separate the exchange and symbol components of user-entered tickers, for example. The separation is done with the underused str.match() , which can use regular expressions (or regex) to scan a string and separate characters based on a search pattern. The possibilities with regex are virtually endless; they can be used in “find and replace” applications, or to validate phone numbers, emails, passwords, credit card numbers, dates, etc. Note that Pine supports the same regex features as Java .
String operations in Pine Script™
The Pine Script™ runtime is optimized for number crunching. You can thus optimize script performance by limiting operations on strings whenever possible. This includes declaring strings with the var keyword, and containing re-assignments to local if blocks using barstate.islast , for example.
Look first. Then leap.
█ FUNCTIONS
leftOf(str, separator, occurrence)
Extracts the part of the `str` string that is left of the nth `occurrence` of the `separator` string.
Parameters:
str : (series string) Source string.
separator : (series string) Separator string.
occurrence : (series int) Occurrence of the separator string. Optional. The default value is zero (the 1st occurrence).
Returns: (string) The extracted string.
rightOf(str, separator, occurrence)
Extracts the part of the `str` string that is right of the nth `occurrence` of the `separator` string.
Parameters:
str : (series string) Source string.
separator : (series string) Separator string.
occurrence : (series int) Occurrence of the separator string. Optional. The default value is zero (the 1st occurrence).
Returns: (string) The extracted string.
_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.
CanvasLibrary "Canvas"
A library implementing a kind of "canvas" using a table where each pixel is represented by a table cell and the pixel color by the background color of each cell.
To use the library, you need to create a color matrix (represented as an array) and a canvas table.
The canvas table is the container of the canvas, and the color matrix determines what color each pixel in the canvas should have.
max_canvas_size() Function that returns the maximum size of the canvas (100). The canvas is always square, so the size is equal to rows (as opposed to not rows multiplied by columns).
Returns: The maximum size of the canvas (100).
get_bg_color(color_matrix) Get the current background color of the color matrix. This is the default color used when erasing pixels or clearing a canvas.
Parameters:
color_matrix : The color matrix.
Returns: The current background color.
get_fg_color(color_matrix) Get the current foreground color of the color matrix. This is the default color used when drawing pixels.
Parameters:
color_matrix : The color matrix.
Returns: The current foreground color.
set_bg_color(color_matrix, bg_color) Set the background color of the color matrix. This is the default color used when erasing pixels or clearing a canvas.
Parameters:
color_matrix : The color matrix.
bg_color : The new background color.
set_fg_color(color_matrix, fg_color) Set the foreground color of the color matrix. This is the default color used when drawing pixels.
Parameters:
color_matrix : The color matrix.
fg_color : The new foreground color.
color_matrix_rows(color_matrix, rows) Function that returns how many rows a color matrix consists of.
Parameters:
color_matrix : The color matrix.
rows : (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
Returns: The number of rows a color matrix consists of.
pixel_color(color_matrix, x, y, rows) Get the color of the pixel at the specified coordinates.
Parameters:
color_matrix : The color matrix.
x : The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
y : The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
rows : (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
Returns: The color of the pixel at the specified coordinates.
draw_pixel(color_matrix, x, y, pixel_color, rows) Draw a pixel at the specified X and Y coordinates. Uses the specified color.
Parameters:
color_matrix : The color matrix.
x : The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
y : The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
pixel_color : The color of the pixel.
rows : (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
draw_pixel(color_matrix, x, y, rows) Draw a pixel at the specified X and Y coordinates. Uses the current foreground color.
Parameters:
color_matrix : The color matrix.
x : The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
y : The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
rows : (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
erase_pixel(color_matrix, x, y, rows) Erase a pixel at the specified X and Y coordinates, replacing it with the background color.
Parameters:
color_matrix : The color matrix.
x : The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
y : The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
rows : (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
init_color_matrix(rows, bg_color, fg_color) Create and initialize a color matrix with the specified number of rows. The number of columns will be equal to the number of rows.
Parameters:
rows : The number of rows the color matrix should consist of. This can be omitted, but if used, can speed up execution. It can never be greater than "max_canvas_size()".
bg_color : (Optional) The initial background color. The default is black.
fg_color : (Optional) The initial foreground color. The default is white.
Returns: The array representing the color matrix.
init_canvas(color_matrix, pixel_width, pixel_height, position) Create and initialize a canvas table.
Parameters:
color_matrix : The color matrix.
pixel_width : (Optional) The pixel width (in % of the pane width). The default width is 0.35%.
pixel_height : (Optional) The pixel width (in % of the pane height). The default width is 0.60%.
position : (Optional) The position for the table representing the canvas. The default is "position.middle_center".
Returns: The canvas table.
clear(color_matrix, rows) Clear a color matrix, replacing all pixels with the current background color.
Parameters:
color_matrix : The color matrix.
rows : The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
update(canvas, color_matrix, rows) This updates the canvas with the colors from the color matrix. No changes to the canvas gets plotted until this function is called.
Parameters:
canvas : The canvas table.
color_matrix : The color matrix.
rows : The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
RicardoLibraryLibrary "RicardoLibrary"
Ricardo's personal Library
GetPipValue() GetPipValue
Returns: Pip value of Symbol
Calculate_SL(IsLong) Calculate_SL: Calcultes Stop Loss
Parameters:
IsLong : If true, then I am going to enter a long position, if false then Short position
Returns: Stop loss Price
STPFunctionsLibrary "STPFunctions"
These functions are used as part of the STP trading strategy and include commonly used candle patterns, trade triggers and frequently monitored stock parameters
MAs() Determines if the last price is abover or below key moving averages. MAs used on the daily are SMA20, SMA50 and SMA200. SMA20 and SMA50 are used intraday.
Returns: 1 if the last price/close was over the moving averages. -1 is returned if the last price/close is below the moving averages. 0 is returned otherwise.
HTFOrderFlow(HTF1_open, HTF2_open) Determine the state of the higher time frame order flow.
Parameters:
HTF1_open : float value representing the higher time frame open.
HTF2_open : float value representing the higher time frame open.
Returns: 1 if the last price/close was over the higher time frame open. -1 is returned if the last price/close is below the higher time frame open. 0 is returned otherwise.
OrderFlow() Determine the recent order flow... basically are we well bid or well offered
Returns: 1 if the last 2 candles are well bid. -1 is returned if the last 2 candles are well offered. 0 is returned otherwise.
isInside() Used to flag inside candles
Returns: 1 if the close >= open. -1 is returned if the close <= open. 0 is returned otherwise.
isOutside() Used to flag outside or engulfing candles
Returns: 1 if the close >= open. -1 is returned if the close <= open. 0 is returned otherwise.
isUTN() Used to flag the U-turn reversal pattern
Returns: 1 for a BUTN. -1 is returned for a BRUTN. 0 is returned otherwise.
isSNapBack() Flag for Snapback Entries
Returns: 1 for a bullish snapback setup. -1 is returned for a bearish snapback setup. 0 is returned otherwise.
mZigzagLibrary "mZigzag"
Matrix implementation of zigzag to allow further possibilities.
Main advantage of this library over previous zigzag methods is that you can attach any number of indicator/oscillator information to zigzag
calculate(length, ohlc, indicatorHigh, indicatorLow, numberOfPivots) calculates zigzag and related information
Parameters:
length : is zigzag length
ohlc : array of OHLC values to be used for zigzag calculation
indicatorHigh : Array of indicator values calculated based on high price of OHLC
indicatorLow : Array of indicators values calculated based on low price of OHLC
numberOfPivots : Number of pivots to be returned
Returns: pivotMatrix Matrix containing zigzag pivots, pivot bars, direction, ratio, and indicators added via indicatorHigh/indicatorLow
newZG is true if a new pivot is added to array
doubleZG is true if last calculation returned two new pivots (Happens on extreme price change)
draw(length, ohlc, indicatorLabels, indicatorHigh, indicatorLow, numberOfPivots, lineColor, lineWidth, lineStyle, showHighLow, showRatios, showIndicators) draws zigzag and related information
Parameters:
length : is zigzag length
ohlc : array of OHLC values to be used for zigzag calculation
indicatorLabels : Array of name of indicators passed
indicatorHigh : Array of indicator values calculated based on high price of OHLC
indicatorLow : Array of indicators values calculated based on low price of OHLC
numberOfPivots : Number of pivots to be returned
lineColor : zigzag line color. set to blue by default
lineWidth : zigzag line width. set to 1 by default
lineStyle : zigzag line style. set to line.style_solid by default
showHighLow : show HH, HL, LH, LL labels
showRatios : show pivot retracement ratios from previous zigzag
showIndicators : show indicator values
Returns: pivotMatrix Matrix containing zigzag pivots, pivot bars, direction, ratio, and indicators added via indicatorHigh/indicatorLow
zigzaglines array of zigzag lines
zigzaglabels array of zigzag labels
merge_pinbarLibrary "merge_pinbar"
merge_pinbar: merge bars and check whether the bar is a pinbar
merge_pinbar(simple, simple) merge_pinbar: merge bars and check whether the bar is a pinbar
Parameters:
simple : int period: the statistic bar period
simple : int max_bars: the max bars to be merged
Returns: array:
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