libHTF[without request.security()]Library "libHTF"
libHTF: use HTF values without request.security()
This library enables to use HTF candles without request.security().
Basic data structure
Using to access values in the same manner as series variable.
The last member of HTF array is always latest current TF's data.
If new bar in HTF(same as last bar closes), new member is pushed to HTF array.
2nd from the last member of HTF array is latest fixed(closed) bar.
HTF: How to use
1. set TF
tf_higher() function selects higher TF. TF steps are ("1","5","15","60","240","D","W","M","3M","6M","Y").
example:
tfChart = timeframe.period
htf1 = tf_higher(tfChart)
2. set HTF matrix
htf_candle() function returns 1 bool and 1 matrix.
bool is a flag for start of new candle in HTF context.
matrix is HTF candle data(0:open,1:time_open,2:close,3:time_close,4:high,5:time:high,6:low,7:time_low).
example:
=htf_candle(htf1)
3. how to access HTF candle data
you can get values using .lastx() method.
please be careful, return value is always float evenif it is "time". you need to cast to int time value when using for xloc.bartime.
example:
htf1open=m1.lastx("open")
htf1close=m1.lastx("close")
//if you need to use histrical value.
lastopen=open
lasthtf1open=m1.lastx("open",1)
4. how to store Data of HTF context
you have to use array to store data of HTF context.
array.htf_push() method handles the last member of array. if new_bar in HTF, it push new member. otherwise it set value to the last member.
example:
array a_close=array.new(1,na)
a_close.htf_push(b_new_bar1,m1.lastx("close"))
HTFsrc: How to use
1. how to setup src.
set_src() function is set current tf's src from string(open/high/low/close/hl2/hlc3/ohlc4/hlcc4).
set_htfsrc() function returns src array of HTF candle.
example:
_src="ohlc4"
src=set_src(_src)
htf1src=set_htfsrc(_src,b_new_bar1,m1)
(if you need to use HTF src in series float)
s_htf1src=htf1src.lastx()
HighLow: How to use
1. set HTF arrays
highlow() and htfhighlow() function calculates high/low and return high/low prices and time.
the functions return 1 int and 8arrays.
int is a flag for new high(1) or new low(-1).
arrays are high/low and return high/low data. float for price, int for time.
example
=
highlow()
=
htfhighlow(m1)
2. how to access HighLow data
you can get values using .lastx() method.
example:
if i_renew==1
myhigh=a_high.lastx()
//if you need to use histrical value.
myhigh=a_high.lastx(1)
other functions
functions for HTF candle matrix or HTF src array in this script are
htf_sma()/htf_ema()/htf_rma()
htf_rsi()/htf_rci()/htf_dmi()
method lastx(arrayid, lastindex)
method like array.last. it returns lastindex from the last member, if parameter is set.
Namespace types: float
Parameters:
arrayid (float )
lastindex (int) : (int) default value is "0"(the last member). if you need to access historical value, increment it(same manner as series vars).
Returns: float value of lastindex from the last member of the array. returns na, if fail.
method lastx(arrayid, lastindex)
method like array.last. it returns lastindex from the last member, if parameter is set.
Namespace types: int
Parameters:
arrayid (int )
lastindex (int) : (int) default value is "0"(the last member). if you need to access historical value, increment it(same manner as series vars).
Returns: int value of lastindex from the last member of the array. returns na, if fail.
method lastx(m, _type, lastindex)
method for handling htf matrix.
Namespace types: matrix
Parameters:
m (matrix) : (matrix) matrix for htf candle.
_type (string) : (string) value type of htf candle:
lastindex (int) : (int) default value is "0"(the last member).
Returns: (float) value of htf candle. (caution: need to cast float to int to use time values!)
method set_last(arrayid, val)
method to set a value of the last member of the array. it sets value to the last member.
Namespace types: float
Parameters:
arrayid (float )
val (float) : (float) value to set.
Returns: nothing
method htf_push(arrayid, b, val)
method to push new member to htf context. if new bar in htf, it works as push. else it works as set_last.
Namespace types: float
Parameters:
arrayid (float )
b (bool) : (bool) true:push,false:set_last
val (float) : (float) _f the value to set.
Returns: nothing
method tf_higher(tf)
method to set higher tf from tf string. TF steps are .
Namespace types: series string, simple string, input string, const string
Parameters:
tf (string) : (string) tf string
Returns: (string) string of higher tf.
htf_candle(_tf, _TZ)
build htf candles
Parameters:
_tf (string) : (string) tf string.
_TZ (string) : of timezone. default value is "GMT+3".
Returns: bool for new bar@htf and matrix for snapshot of htf candle
set_src(_src_type)
set src.
Parameters:
_src_type (string) : (string) type of source:
Returns: (series float) src value
set_htfsrc(_src_type, _nb, _m)
set htf src.
Parameters:
_src_type (string) : (string) type of source:
_nb (bool) : (bool) flag of new bar
_m (matrix) : (matrix) matrix for htf candle.
Returns: (array) array of src value
is_up()
last_is_up()
peak_bottom(_latest, _last)
Parameters:
_latest (bool)
_last (bool)
htf_is_up(_m)
Parameters:
_m (matrix)
htf_last_is_up(_m)
Parameters:
_m (matrix)
highlow(_b_bartime_price)
Parameters:
_b_bartime_price (bool)
htfhighlow(_m, _b_bartime_price)
Parameters:
_m (matrix)
_b_bartime_price (bool)
htf_sma(_a_src, _len)
Parameters:
_a_src (float )
_len (int)
htf_rma(_a_src, _new_bar, _len)
Parameters:
_a_src (float )
_new_bar (bool)
_len (int)
htf_ema(_a_src, _new_bar, _len)
Parameters:
_a_src (float )
_new_bar (bool)
_len (int)
htf_rsi(_a_src, _new_bar, _len)
Parameters:
_a_src (float )
_new_bar (bool)
_len (int)
rci(_src, _len)
Parameters:
_src (float)
_len (int)
htf_rci(_a_src, _len)
Parameters:
_a_src (float )
_len (int)
htf_dmi(_m, _new_bar, _len, _ma_type)
Parameters:
_m (matrix)
_new_bar (bool)
_len (int)
_ma_type (string)
HTF
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.
HighTimeframeTimingLibrary "HighTimeframeTiming"
@description Library for sampling high timeframe (HTF) historical data at an arbitrary number of HTF bars back, using a single security() call.
The data is fixed and does not alter over the course of the HTF bar. It also behaves consistently on historical and elapsed realtime bars.
‼ LIMITATIONS: This library function depends on there being a consistent number of chart timeframe bars within the HTF bar. This is almost always true in 24/7 markets like crypto.
This might not be true if the chart doesn't produce an update when expected, for example because the asset is thinly traded and there is no volume or price update from the feed at that time.
To mitigate this risk, use this function on liquid assets and at chart timeframes high enough to reliably produce updates at least once per bar period.
The consistent ratio of bars might also break down in markets with irregular sessions and hours. I'm not sure if or how one could mitigate this.
Another limitation is that because we're accessing a multiplied number of chart bars, you will run out of chart bars faster than you would HTF bars. This is only a problem if you use a large historical operator.
If you call a function from this library, you should probably reproduce these limitations in your script description.
However, all of this doesn't mean that this function might not still be the best available solution, depending what your needs are.
If a single chart bar is skipped, for example, the calculation will be off by 1 until the next HTF bar opens. This is certainly inconsistent, but potentially still usable.
@function f_offset_synch(float _HTF_X, int _HTF_H, int _openChartBarsIn, bool _updateEarly)
Returns the number of chart bars that you need to go back in order to get a stable HTF value from a given number of HTF bars ago.
@param float _HTF_X is the timeframe multiplier, i.e. how much bigger the selected timeframe is than the chart timeframe. The script shows a way to calculate this using another of my libraries without using up a security() call.
@param int _HTF_H is the historical operator on the HTF, i.e. how many bars back you want to go on the higher timeframe. If omitted, defaults to zero.
@param int _openChartBarsIn is how many chart bars have been opened within the current HTF bar. An example of calculating this is given below.
@param bool _updateEarly defines whether you want to update the value at the closing calculation of the last chart bar in the HTF bar or at the open of the first one.
@returns an integer that you can use as a historical operator to retrieve the value for the appropriate HTF bar.
🙏 Credits: This library is an attempt at a solution of the problems in using HTF data that were laid out by Pinecoders in "security() revisited" -
Thanks are due to the authors of that work for an understanding of HTF issues. In addition, the current script also includes some of its code.
Specifically, this script reuses the main function recommended in "security() revisited", for the purposes of comparison. And it extends that function to access historical data, again just for comparison.
All the rest of the code, and in particular all of the code in the exported function, is my own.
Special thanks to LucF for pointing out the limitations of my approach.
~~~~~~~~~~~~~~~~|
EXPLANATION
~~~~~~~~~~~~~~~~|
Problems with live HTF data: Many problems with using live HTF data from security() have been clearly explained by Pinecoders in "security() revisited"
In short, its behaviour is inconsistent between historical and elapsed realtime bars, and it changes in realtime, which can cause calculations and alerts to misbehave.
Various unsatisfactory solutions are discussed in "security() revisited", and understanding that script is a prerequisite to understanding this library.
PineCoders give their own solution, which is to fix the data by essentially using the previous HTF bar's data. Importantly, that solution is consistent between historical and realtime bars.
This library is an attempt to provide an alternative to that solution.
Problems with historical HTF data: In addition to the problems with live HTF data, there are different issues when trying to access historical HTF data.
Why use historical HTF data? Maybe you want to do custom calculations that involve previous HTF bars. Or to use HTF data in a function that has mutable variables and so can't be done in a security() call.
Most obviously, using the historical operator (in this description, represented using { } because the square brackets don't render) on variables already retrieved from a security() call, e.g. HTF_Close{1}, is not very useful:
it retrieves the value from the previous *chart* bar, not the previous HTF bar.
Using {1} directly in the security() call instead does get data from the previous HTF bar, but it behaves inconsistently, as we shall see.
This library addresses these concerns as well.
Housekeeping: To follow what's going on with the example and comparisons, turn line labels on: Settings > Scales > Indicator Name Label.
The following explanation assumes "close" as the source, but you can change it if you want.
To quickly see the difference between historical and realtime bars, set the HTF to something like 3 minutes on a 15s chart.
The bars at the top of the screen show the status. Historical bars are grey, elapsed realtime bars are red, and the realtime bar is green. A white vertical line shows the open of a HTF bar.
A: This library function f_offset_synch(): When supplied with an input offset of 0, it plots a stable value of the close of the *previous* HTF bar. This value is thus safe to use for calculations and alerts.
For a historical operator of {1}, it gives the close of the *last-but-one* bar. Sounds simple enough. Let's look at the other options to see its advantages.
B: Live HTF data: Represented on the line label as "security(){0}". Note: this is the source that f_offset_synch() samples.
The raw HTF data is very different on historical and realtime bars:
+ On historical bars, it uses a flat value from the end of the previous HTF bar. It updates at the close of the HTF bar.
+ On realtime bars, it varies between and within each chart bar.
There might be occasions where you want to use live data, in full knowledge of its drawbacks described above. For example, to show simple live conditions that are reversible after a chart bar close.
This library transforms live data to get the fixed data, thus giving you access to both live and fixed data with only one security() call.
C: Historical data using security(){H}: To see how this behaves, set the {H} value in the settings to 1 and show options A, B, and C.
+ On historical bars, this option matches option A, this library function, exactly. It behaves just like security(){0} but one HTF bar behind, as you would expect.
+ On realtime bars, this option takes the value of security(){0} at the end of a HTF bar, but it takes it from the previous *chart* bar, and then persists that.
The easiest way to see this inconsistency is on the first realtime bar (marked red at the top of the screen). This option suddenly jumps, even if it's in the middle of a HTF bar.
Contrast this with option A, which is always constant, until it updates, once per HTF bar.
D: PineCoders' original function: To see how this behaves, show options A, B, and D. Set the {H} value in the settings to 0, then 1.
The PineCoders' original function (D) and extended function (E) do not have the same limitations as this library, described in the Limitations section.
This option has all of the same advantages that this library function, option A, does, with the following differences:
+ It cannot access historical data. The {H} setting makes no difference.
+ It always updates at the open of the first chart bar in a new HTF bar.
By contrast, this library function, option A, is configured by default to update at the close of the last chart bar in a HTF bar.
This little frontrunning is only a few seconds but could be significant in trading. E.g. on a 1D HTF with a 4H chart, an alert that involves a HTF change set to trigger ON CLOSE would trigger 4 hours later using this method -
but use exactly the same value. It depends on the market and timeframe as to whether you could actually trade this. E.g. at the very end of a tradfi day your order won't get executed.
This behaviour mimics how security() itself updates, as is easy to see on the chart. If you don't want it, just set in_updateEarly to false. Then it matches option D exactly.
E: PineCoders' function, extended to get history: To see how this behaves, show options A and E. Set the {H} value in the settings to 0, then 1.
I modified the original function to be able to get historical values. In all other respects it is the same.
Apart from not having the option to update earlier, the only disadvantage of this method vs this library function is that it requires one security() call for each historical operator.
For example, if you wanted live data, and fixed data, and fixed data one bar back, you would need 3 security() calls. My library function requires just one.
This is the essential tradeoff: extra complexity and less robustness in certain circumstances (the PineCoders function is simple and universal by comparison) for more flexibility with fewer security() calls.
Pivots libraryLibrary "Pivots"
TODO: add library description here
pivots(_type, _open, _high, _low, _clsoe) Calculates the pivot point and returns its value.
Parameters:
_type : Specifies the type of pivot point.
_open : The open price
_high : The high price
_low : The low price
_clsoe : The close price
Returns: Returns the value of the calculated pivot point as a tuple.
cpr(_high, _low, _clsoe) Calculate the Central Pivot Range
Parameters:
_high : The high price
_low : The low price
_clsoe : The close price
Returns: Returns the values as a tuple.
htf_ohlc(_htf) Calculate the HTF values
Parameters:
_htf : Resolution
Returns: Returns the values as a tuple.
MTFindicatorsQuite recently TradingView added the possibility to create and use Libraries in PineScript. With this feature PineScript became higher quality of coding language overnight. Libraries enable splitting your code into multiple files, providing easier access to code reusability.
I was working on a script which included 3000 lines of code, which was recompiling 1:30 min, and recalculating over 1 minute as well. So I split it into 2 parts: main part + library containing "main logic", which I reuse in variety of scripts, but don't change too often. Result? Now recompilation of my main script takes 10 and recalculation 8 seconds!!!. I instantly fell in love with libraries.
Having said that, and being dedicated hater of security() calls, I have decided to publish a library of MTF indicators created with my own approach: "dig into formula". I have explained reasons for such approach in desription to this script:
So this library script will be a set of indicators reaching to higher timeframes. Just include one line at the beginning of the script you are creating:
import Peter_O/MTFindicators/1 as LIB
and then somewhere is the code add this line:
rsimtf=LIB.rsi_mtf(close,5,14)
All of a sudden you have access to rsimtf from 5x higher timeframe without any hassle :)
I start with RSI MTF, next ones will be ADX, Stochastic and some more. I will update this library with them here as well. Feel free to request particular indicators in comments. Maybe PSAR? Maybe Bollinger Bands?