TimeLibraryLibrary "TimeLibrary"
TODO: add library description here
Line_Type_Control(Type)
Line_Type_Control: This function changes between common line types options available are "Solid","Dashed","Dotted"
Parameters:
Type (string) : : The string to choose the line type from
Returns: Line_Type : returns the pine script equivalent of the string input
Text_Size_Switch(Text_Size)
Text_Size_Switch : This function changes between common text sizes options are "Normal", "Tiny", "Small", "Large", "Huge", "Auto"
Parameters:
Text_Size (string) : : The string to choose the text type from
Returns: Text_Type : returns the pine script equivalent of the string input
TF(TF_Period, TF_Multip)
TF generates a string representation of a time frame based on the provided time frame unit (`TF_Period`) and multiplier (`TF_Multip`).
Parameters:
TF_Period (simple string)
TF_Multip (simple int)
Returns: A string that represents the time frame in Pine Script format, depending on the `TF_Period`:
- For "Minute", it returns the multiplier as a string (e.g., "5" for 5 minutes).
- For "Hour", it returns the equivalent number of minutes (e.g., "120" for 2 hours).
- For "Day", it appends "D" to the multiplier (e.g., "2D" for 2 days).
- For "Week", it appends "W" to the multiplier (e.g., "1W" for 1 week).
- For "Month", it appends "M" to the multiplier (e.g., "3M" for 3 months).
If none of these cases match, it returns the current chart's time frame.
TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip)
TF_Display generates a string representation of a time frame based on user-defined inputs or the current chart's time frame settings.
Parameters:
Chart_as_Timeframe (bool) : (bool): Determines whether to use the current chart's time frame or a custom time frame.
TF_Period` (string): The time frame unit (e.g., "Minute", "Hour", "Day", "Week", "Month").
TF_Multip` (int): The multiplier for the time frame (e.g., 15 for 15 minutes, 2 for 2 days).
TF_Period (string)
TF_Multip (int)
Returns: If `Chart_as_Timeframe` is `false`, the function returns a time frame string based on the provided `TF_Period` and `TF_Multip` values (e.g., "5Min", "2D").
If `Chart_as_Timeframe` is `true`, the function determines the current chart's time frame and returns it as a string:
For minute-based time frames, it returns the number of minutes with "Min" (e.g., "15Min") unless it's an exact hour, in which case it returns the hour (e.g., "1H").
For daily, weekly, and monthly time frames, it returns the multiplier with the appropriate unit (e.g., "1D" for daily, "1W" for weekly, "1M" for monthly).
MTF_MS_Display(Chart_as_Timeframe, TF_Period, TF_Multip, Swing_Length)
MTF_MS_Display This function calculates and returns a modified swing length value based on the selected time frame and current chart's time frame.
Parameters:
Chart_as_Timeframe (bool)
TF_Period (string)
TF_Multip (int)
Swing_Length (int)
HTF_Structure_Control(Chart_as_Timeframe, Show_Only_On_Lower_Timeframes, TF_Period, TF_Multip)
Parameters:
Chart_as_Timeframe (bool)
Show_Only_On_Lower_Timeframes (bool)
TF_Period (string)
TF_Multip (int)
Mtf
TimeframeComparisonLibrary "TimeframeComparison"
Timeframe comparison for higher and lower timeframe
█ OVERVIEW
This library is used to compare higher / lower timeframe by using timeframe.multiplier.
minMult()
timeframe multiplier in minutes
Returns: float value
MTF_DrawingsLibrary 'MTF_Drawings'
This library helps with drawing indicators and candle charts on all timeframes.
FEATURES
CHART DRAWING : Library provides functions for drawing High Time Frame (HTF) and Low Time Frame (LTF) candles.
INDICATOR DRAWING : Library provides functions for drawing various types of HTF and LTF indicators.
CUSTOM COLOR DRAWING : Library allows to color candles and indicators based on specific conditions.
LINEFILLS : Library provides functions for drawing linefills.
CATEGORIES
The functions are named in a way that indicates they purpose:
{Ind} : Function is meant only for indicators.
{Hist} : Function is meant only for histograms.
{Candle} : Function is meant only for candles.
{Draw} : Function draws indicators, histograms and candle charts.
{Populate} : Function generates necessary arrays required by drawing functions.
{LTF} : Function is meant only for lower timeframes.
{HTF} : Function is meant only for higher timeframes.
{D} : Function draws indicators that are composed of two lines.
{CC} : Function draws custom colored indicators.
USAGE
Import the library into your script.
Before using any {Draw} function it is necessary to use a {Populate} function.
Choose the appropriate one based on the category, provide the necessary arguments, and then use the {Draw} function, forwarding the arrays generated by the {Populate} function.
This doesn't apply to {Draw_Lines}, {LineFill}, or {Barcolor} functions.
EXAMPLE
import Spacex_trader/MTF_Drawings/1 as tf
//Request lower timeframe data.
Security(simple string Ticker, simple string New_LTF, float Ind) =>
float Value = request.security_lower_tf(Ticker, New_LTF, Ind)
Value
Timeframe = input.timeframe('1', 'Timeframe: ')
tf.Draw_Ind(tf.Populate_LTF_Ind(Security(syminfo.tickerid, Timeframe, ta.rsi(close, 14)), 498, color.purple), 1, true)
FUNCTION LIST
HTF_Candle(BarsBack, BodyBear, BodyBull, BordersBear, BordersBull, WickBear, WickBull, LineStyle, BoxStyle, LineWidth, HTF_Open, HTF_High, HTF_Low, HTF_Close, HTF_Bar_Index)
Populates two arrays with drawing data of the HTF candles.
Parameters:
BarsBack (int) : Bars number to display.
BodyBear (color) : Candle body bear color.
BodyBull (color) : Candle body bull color.
BordersBear (color) : Candle border bear color.
BordersBull (color) : Candle border bull color.
WickBear (color) : Candle wick bear color.
WickBull (color) : Candle wick bull color.
LineStyle (string) : Wick style (Solid-Dotted-Dashed).
BoxStyle (string) : Border style (Solid-Dotted-Dashed).
LineWidth (int) : Wick width.
HTF_Open (float) : HTF open price.
HTF_High (float) : HTF high price.
HTF_Low (float) : HTF low price.
HTF_Close (float) : HTF close price.
HTF_Bar_Index (int) : HTF bar_index.
Returns: Two arrays with drawing data of the HTF candles.
LTF_Candle(BarsBack, BodyBear, BodyBull, BordersBear, BordersBull, WickBear, WickBull, LineStyle, BoxStyle, LineWidth, LTF_Open, LTF_High, LTF_Low, LTF_Close)
Populates two arrays with drawing data of the LTF candles.
Parameters:
BarsBack (int) : Bars number to display.
BodyBear (color) : Candle body bear color.
BodyBull (color) : Candle body bull color.
BordersBear (color) : Candle border bear color.
BordersBull (color) : Candle border bull color.
WickBear (color) : Candle wick bear color.
WickBull (color) : Candle wick bull color.
LineStyle (string) : Wick style (Solid-Dotted-Dashed).
BoxStyle (string) : Border style (Solid-Dotted-Dashed).
LineWidth (int) : Wick width.
LTF_Open (float ) : LTF open price.
LTF_High (float ) : LTF high price.
LTF_Low (float ) : LTF low price.
LTF_Close (float ) : LTF close price.
Returns: Two arrays with drawing data of the LTF candles.
Draw_Candle(Box, Line, Offset)
Draws HTF or LTF candles.
Parameters:
Box (box ) : Box array with drawing data.
Line (line ) : Line array with drawing data.
Offset (int) : Offset of the candles.
Returns: Drawing of the candles.
Populate_HTF_Ind(IndValue, BarsBack, IndColor, HTF_Bar_Index)
Populates one array with drawing data of the HTF indicator.
Parameters:
IndValue (float) : Indicator value.
BarsBack (int) : Indicator lines to display.
IndColor (color) : Indicator color.
HTF_Bar_Index (int) : HTF bar_index.
Returns: An array with drawing data of the HTF indicator.
Populate_LTF_Ind(IndValue, BarsBack, IndColor)
Populates one array with drawing data of the LTF indicator.
Parameters:
IndValue (float ) : Indicator value.
BarsBack (int) : Indicator lines to display.
IndColor (color) : Indicator color.
Returns: An array with drawing data of the LTF indicator.
Draw_Ind(Line, Mult, Exe)
Draws one HTF or LTF indicator.
Parameters:
Line (line ) : Line array with drawing data.
Mult (int) : Coordinates multiplier.
Exe (bool) : Display the indicator.
Returns: Drawing of the indicator.
Populate_HTF_Ind_D(IndValue_1, IndValue_2, BarsBack, IndColor_1, IndColor_2, HTF_Bar_Index)
Populates two arrays with drawing data of the HTF indicators.
Parameters:
IndValue_1 (float) : First indicator value.
IndValue_2 (float) : Second indicator value.
BarsBack (int) : Indicator lines to display.
IndColor_1 (color) : First indicator color.
IndColor_2 (color) : Second indicator color.
HTF_Bar_Index (int) : HTF bar_index.
Returns: Two arrays with drawing data of the HTF indicators.
Populate_LTF_Ind_D(IndValue_1, IndValue_2, BarsBack, IndColor_1, IndColor_2)
Populates two arrays with drawing data of the LTF indicators.
Parameters:
IndValue_1 (float ) : First indicator value.
IndValue_2 (float ) : Second indicator value.
BarsBack (int) : Indicator lines to display.
IndColor_1 (color) : First indicator color.
IndColor_2 (color) : Second indicator color.
Returns: Two arrays with drawing data of the LTF indicators.
Draw_Ind_D(Line_1, Line_2, Mult, Exe_1, Exe_2)
Draws two LTF or HTF indicators.
Parameters:
Line_1 (line ) : First line array with drawing data.
Line_2 (line ) : Second line array with drawing data.
Mult (int) : Coordinates multiplier.
Exe_1 (bool) : Display the first indicator.
Exe_2 (bool) : Display the second indicator.
Returns: Drawings of the indicators.
Barcolor(Box, Line, BarColor)
Colors the candles based on indicators output.
Parameters:
Box (box ) : Candle box array.
Line (line ) : Candle line array.
BarColor (color ) : Indicator color array.
Returns: Colored candles.
Populate_HTF_Ind_D_CC(IndValue_1, IndValue_2, BarsBack, BullColor, BearColor, IndColor_1, HTF_Bar_Index)
Populates two array with drawing data of the HTF indicators with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
Parameters:
IndValue_1 (float) : First indicator value.
IndValue_2 (float) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bear color.
IndColor_1 (color) : First indicator color.
HTF_Bar_Index (int) : HTF bar_index.
Returns: Three arrays with drawing and color data of the HTF indicators.
Populate_LTF_Ind_D_CC(IndValue_1, IndValue_2, BarsBack, BullColor, BearColor, IndColor_1)
Populates two arrays with drawing data of the LTF indicators with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
Parameters:
IndValue_1 (float ) : First indicator value.
IndValue_2 (float ) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
IndColor_1 (color) : First indicator color.
Returns: Three arrays with drawing and color data of the LTF indicators.
Populate_HTF_Hist_CC(HistValue, IndValue_1, IndValue_2, BarsBack, BullColor, BearColor, HTF_Bar_Index)
Populates one array with drawing data of the HTF histogram with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
Parameters:
HistValue (float) : Indicator value.
IndValue_1 (float) : First indicator value.
IndValue_2 (float) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
HTF_Bar_Index (int) : HTF bar_index
Returns: Two arrays with drawing and color data of the HTF histogram.
Populate_LTF_Hist_CC(HistValue, IndValue_1, IndValue_2, BarsBack, BullColor, BearColor)
Populates one array with drawing data of the LTF histogram with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
Parameters:
HistValue (float ) : Indicator value.
IndValue_1 (float ) : First indicator value.
IndValue_2 (float ) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
Returns: Two array with drawing and color data of the LTF histogram.
Populate_LTF_Hist_CC_VA(HistValue, Value, BarsBack, BullColor, BearColor)
Populates one array with drawing data of the LTF histogram with color based on: HistValue >= Value ? BullColor : BearColor.
Parameters:
HistValue (float ) : Indicator value.
Value (float) : First indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
Returns: Two array with drawing and color data of the LTF histogram.
Populate_HTF_Ind_CC(IndValue, IndValue_1, BarsBack, BullColor, BearColor, HTF_Bar_Index)
Populates one array with drawing data of the HTF indicator with color based on: IndValue >= IndValue_1 ? BullColor : BearColor.
Parameters:
IndValue (float) : Indicator value.
IndValue_1 (float) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
HTF_Bar_Index (int) : HTF bar_index
Returns: Two arrays with drawing and color data of the HTF indicator.
Populate_LTF_Ind_CC(IndValue, IndValue_1, BarsBack, BullColor, BearColor)
Populates one array with drawing data of the LTF indicator with color based on: IndValue >= IndValue_1 ? BullColor : BearColor.
Parameters:
IndValue (float ) : Indicator value.
IndValue_1 (float ) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
Returns: Two arrays with drawing and color data of the LTF indicator.
Draw_Lines(BarsBack, y1, y2, LineType, Fill)
Draws price lines on indicators.
Parameters:
BarsBack (int) : Indicator lines to display.
y1 (float) : Coordinates of the first line.
y2 (float) : Coordinates of the second line.
LineType (string) : Line type.
Fill (color) : Fill color.
Returns: Drawing of the lines.
LineFill(Upper, Lower, BarsBack, FillColor)
Fills two lines with linefill HTF or LTF.
Parameters:
Upper (line ) : Upper line.
Lower (line ) : Lower line.
BarsBack (int) : Indicator lines to display.
FillColor (color) : Fill color.
Returns: Linefill of the lines.
Populate_LTF_Hist(HistValue, BarsBack, HistColor)
Populates one array with drawing data of the LTF histogram.
Parameters:
HistValue (float ) : Indicator value.
BarsBack (int) : Indicator lines to display.
HistColor (color) : Indicator color.
Returns: One array with drawing data of the LTF histogram.
Populate_HTF_Hist(HistValue, BarsBack, HistColor, HTF_Bar_Index)
Populates one array with drawing data of the HTF histogram.
Parameters:
HistValue (float) : Indicator value.
BarsBack (int) : Indicator lines to display.
HistColor (color) : Indicator color.
HTF_Bar_Index (int) : HTF bar_index.
Returns: One array with drawing data of the HTF histogram.
Draw_Hist(Box, Mult, Exe)
Draws HTF or LTF histogram.
Parameters:
Box (box ) : Box Array.
Mult (int) : Coordinates multiplier.
Exe (bool) : Display the histogram.
Returns: Drawing of the histogram.
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)
LibraryTimeframeHelperLibrary "LibraryTimeframeHelper"
Helper functions to work with timeframes: to get the next higher TF, and to make the string pretty for use in labels. Perhaps I'll add more later.
f_getHigherTF(_TF)
f_getHigherTF(): Converts the input timeframe into the next one up in the list of commonly used timeframes. NOTE: You can NOT use a TF from this function as input to a request.security() call if called from this library because it gets converted to a series (since there's nothing special about this function, I expect this probably goes for any library). However, you CAN copy the code and use it directly in your script, in which case the output is only a simple variable and thus suitable for the timeframe of a request.security() call.
Parameters:
_TF (string) - The timeframe to convert.
Returns: : A string in standard timeframe format.
f_prettifyTF(_TF)
f_prettifyTF(): Converts the input timeframe from standard timeframe format to the format shown by TradingView on a chart. The output is not suitable for use as an input timeframe of a request.security() call.
Parameters:
_TF (string) - The timeframe to convert.
Returns: : A string in prettified timeframe format.
lower_tf█ OVERVIEW
This library is a Pine programmer’s tool containing functions to help those who use the request.security_lower_tf() function. Its `ltf()` function helps translate user inputs into a lower timeframe string usable with request.security_lower_tf() . Another function, `ltfStats()`, accumulates statistics on processed chart bars and intrabars.
█ CONCEPTS
Chart bars
Chart bars , as referred to in our publications, are bars that occur at the current chart timeframe, as opposed to those that occur at a timeframe that is higher or lower than that of the chart view.
Intrabars
Intrabars are chart bars at a lower timeframe than the chart's. Each 1H chart bar of a 24x7 market will, for example, usually contain 60 intrabars at the LTF of 1min, provided there was market activity during each minute of the hour. Mining information from intrabars can be useful in that it offers traders visibility on the activity inside a chart bar.
Lower timeframes (LTFs)
A lower timeframe is a timeframe that is smaller than the chart's timeframe. This framework exemplifies how authors can determine which LTF to use by examining the chart's timeframe. The LTF determines how many intrabars are examined for each chart bar; the lower the timeframe, the more intrabars are analyzed.
Intrabar precision
The precision of calculations increases with the number of intrabars analyzed for each chart bar. As there is a 100K limit to the number of intrabars that can be analyzed by a script, a trade-off occurs between the number of intrabars analyzed per chart bar and the chart bars for which calculations are possible.
█ `ltf()`
This function returns a timeframe string usable with request.security_lower_tf() . It calculates the returned timeframe by taking into account a user selection between eight different calculation modes and the chart's timeframe. You send it the user's selection, along with the text corresponding to the eight choices from which the user has chosen, and the function returns a corresponding LTF string.
Because the function processes strings and doesn't require recalculation on each bar, using var to declare the variable to which its result is assigned will execute the function only once on bar zero and speed up your script:
var string ltfString = ltf(ltfModeInput, LTF1, LTF2, LTF3, LTF4, LTF5, LTF6, LTF7, LTF8)
The eight choices users can select from are of two types: the first four allow a selection from the desired amount of chart bars to be covered, the last four are choices of a fixed number of intrabars to be analyzed per chart bar. Our example code shows how to structure your input call and then make the call to `ltf()`. By changing the text associated with the `LTF1` to `LTF8` constants, you can tailor it to your preferences while preserving the functionality of `ltf()` because you will be sending those string constants as the function's arguments so it can determine the user's selection. The association between each `LTFx` constant and its calculation mode is fixed, so the order of the arguments is important when you call `ltf()`.
These are the first four modes and the `LTFx` constants corresponding to each:
Covering most chart bars (least precise) — LTF1
Covers all chart bars. This is accomplished by dividing the current timeframe in seconds by 4 and converting that number back to a string in timeframe.period format using secondsToTfString() . Due to the fact that, on premium subscriptions, the typical historical bar count is between 20-25k bars, dividing the timeframe by 4 ensures the highest level of intrabar precision possible while achieving complete coverage for the entire dataset with the maximum allowed 100K intrabars.
Covering some chart bars (less precise) — LTF2
Covering less chart bars (more precise) — LTF3
These levels offer a stepped LTF in relation to the chart timeframe with slightly more, or slightly less precision. The stepped lower timeframe tiers are calculated from the chart timeframe as follows:
Chart Timeframe Lower Timeframe
Less Precise More Precise
< 1hr 1min 1min
< 1D 15min 1min
< 1W 2hr 30min
> 1W 1D 60min
Covering the least chart bars (most precise) — LTF4
Analyzes the maximum quantity of intrabars possible by using the 1min LTF, which also allows the least amount of chart bars to be covered.
The last four modes allow the user to specify a fixed number of intrabars to analyze per chart bar. Users can choose from 12, 24, 50 or 100 intrabars, respectively corresponding to the `LTF5`, `LTF6`, `LTF7` and `LTF8` constants. The value is a target; the function will do its best to come up with a LTF producing the required number of intrabars. Because of considerations such as the length of a ticker's session, rounding of the LTF to the closest allowable timeframe, or the lowest allowable timeframe of 1min intrabars, it is often impossible for the function to find a LTF producing the exact number of intrabars. Requesting 100 intrabars on a 60min chart, for example, can only produce 60 1min intrabars. Higher chart timeframes, tickers with high liquidity or 24x7 markets will produce optimal results.
█ `ltfStats()`
`ltfStats()` returns statistics that will be useful to programmers using intrabar inspection. By analyzing the arrays returned by request.security_lower_tf() in can determine:
• intrabarsInChartBar : The number of intrabars analyzed for each chart bar.
• chartBarsCovered : The number of chart bars where intrabar information is available.
• avgIntrabars : The average number of intrabars analyzed per chart bar. Events like holidays, market activity, or reduced hours sessions can cause the number of intrabars to vary, bar to bar.
The function must be called on each bar to produce reliable results.
█ DEMONSTRATION CODE
Our example code shows how to provide users with an input from which they can select a LTF calculation mode. If you use this library's functions, feel free to reuse our input setup code, including the tooltip providing users with explanations on how it works for them.
We make a simple call to request.security_lower_tf() to fetch the close values of intrabars, but we do not use those values. We simply send the returned array to `ltfStats()` and then plot in the indicator's pane the number of intrabars examined on each bar and its average. We also display an information box showing the user's selection of the LTF calculation mode, the resulting LTF calculated by `ltf()` and some statistics.
█ NOTES
• As in several of our recent publications, this script uses secondsToTfString() to produce a timeframe string in timeframe.period format from a timeframe expressed in seconds.
• The script utilizes display.data_window and display.status_line to restrict the display of certain plots.
These new built-ins allow coders to fine-tune where a script’s plot values are displayed.
• We implement a new recommended best practice for tables which works faster and reduces memory consumption.
Using this new method, tables are declared only once with var , as usual. Then, on bar zero only, we use table.cell() calls to populate the table.
Finally, table.set_*() functions are used to update attributes of table cells on the last bar of the dataset.
This greatly reduces the resources required to render tables. We encourage all Pine Script™ programmers to do the same.
Look first. Then leap.
█ FUNCTIONS
The library contains the following functions:
ltf(userSelection, choice1, choice2, choice3, choice4, choice5, choice6, choice7, choice8)
Selects a LTF from the chart's TF, depending on the `userSelection` input string.
Parameters:
userSelection : (simple string) User-selected input string which must be one of the `choicex` arguments.
choice1 : (simple string) Input selection corresponding to "Least precise, covering most chart bars".
choice2 : (simple string) Input selection corresponding to "Less precise, covering some chart bars".
choice3 : (simple string) Input selection corresponding to "More precise, covering less chart bars".
choice4 : (simple string) Input selection corresponding to "Most precise, 1min intrabars".
choice5 : (simple string) Input selection corresponding to "~12 intrabars per chart bar".
choice6 : (simple string) Input selection corresponding to "~24 intrabars per chart bar".
choice7 : (simple string) Input selection corresponding to "~50 intrabars per chart bar".
choice8 : (simple string) Input selection corresponding to "~100 intrabars per chart bar".
Returns: (simple string) A timeframe string to be used with `request.security_lower_tf()`.
ltfStats()
Returns statistics about analyzed intrabars and chart bars covered by calls to `request.security_lower_tf()`.
Parameters:
intrabarValues : (float [ ]) The ID of a float array containing values fetched by a call to `request.security_lower_tf()`.
Returns: A 3-element tuple: [ (series int) intrabarsInChartBar, (series int) chartBarsCovered, (series float) avgIntrabars ].
drawcandlesLibrary "drawcandles"
simple utility to draw different candles using box and lines. Quite useful for drawing candles such as zigzag candles or MTF candles
draw(o, h, l, c, oBar, cBar)
draws candles based on ohlc values
Parameters:
o : Open Price
h : High Price
l : Low Price
c : Close Price
oBar : Open Time
cBar : Close Time
Returns: void
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.
bytimeLibrary "bytime"
TODO: to do something at the specified time.
////Return =>> ht = hour , mt = minute , st = second ,Dt = Day, Mt = month, Yt = year , dateTime = full time format./////////////
Note : Remember to always add import when you call our library and change Gtime() to Timeset.Gtime() is used to access internal data.
import hapharmonic/bytime/1 as Timeset
=Timeset.Gtime()
/////////////Set a time to trigger an alert./////////////
ck = false
///hour : minute : second
if ht == TH and mt == TM and st == TS
//some action
//...
//.
ck := true
Gtime()
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.
Last Available Bar InfoLibrary "Last_Available_Bar_Info"
getLastBarTimeStamp()
getAvailableBars()
This simple library is built with an aim of getting the last available bar information for the chart. This returns a constant value that doesn't change on bar change.
For backtesting with accurate results on non standard charts, it will be helpful. (Especially if you are using non standard charts like Renko Chart).
Methods
getLastBarTimeStamp()
: Returns Timestamp of the last available bar (Constant)
getAvailableBars()
:Returns Number of Available Bars on the chart (Constant)
Example
import paragjyoti2012/Last_Available_Bar_Info/v1 as LastBarInfo
last_bar_timestamp=LastBarInfo.getLastBarTimeStamp()
no_of_bars=LastBarInfo.getAvailableBars()
If you are using Renko Charts, for backtesting, it's necesary to filter out the historical bars that are not of this timeframe.
In Renko charts, once the available bars of the current timeframe (based on your Tradingview active plan) are exhausted,
previous bars are filled in with historical bars of higher timeframe. Which is detrimental for backtesting, and it leads to unrealistic results.
To get the actual number of bars available of that timeframe, you should use this security function to get the timestamp for the last (real) bar available.
tf=timeframe.period
real_available_bars = request.security(syminfo.ticker, tf , LastBarInfo.getAvailableBars() , lookahead = barmerge.lookahead_off)
last_available_bar_timestamp = request.security(syminfo.ticker, tf , LastBarInfo.getLastBarTimeStamp() , lookahead = barmerge.lookahead_off)
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?
GenericTALibrary "GenericTA"
What is it?
The real generic library. Which means it is just covering most built-in indicators / functions, but with more parameters, so the user don't have to write more few lines to achieve something simple and replicative.
Development process?
Will tidy it up, and setting up in later stage.
Welcome to inbox me to improve the library ------
If you are finding a similar thing. That's a good news. Because I am making it.
LibraryCheckNthBarLibrary "LibraryCheckNthBar"
TODO: add library description here
canwestart(UTC, prd) this function can be used if current bar is in last Nth bar
Parameters:
UTC : is UTC of the chart
prd : is the length of last Nth bar
Returns: true if the current bar is in N bar
TimeframeToMinutesLibrary "TimeframeToMinutes"
The timeframeToMinutes() function returns the number of minutes in an arbitrary timeframe string.
timeframeToMinutes()
Returns the number of minutes in the supplied timeframe string, which is arbitrary, i.e. it doesn't have to be the timeframe of the current chart but can be taken from an input.
The sole advantage over the short and neat Pinecoders f_resInMinutes function from their excellent MTF Selection Framework (at ) is that this one doesn't use up a security() call.
To convert the other way, from minutes to timeframe.period format, I would use the f_resFromMinutes function from the Pinecoders' MTF Selection Framework, which does not use security().
ERROR-CHECKING: It has light error-checking to try to make sure the string is in the format timeframe.period, e.g. 15S, 1 (minute), 60 (1H), 1D, 1W, 1M.
It will throw an error for some non-standard timeframes such as 30 hours (1800 minutes). Above 1440 minutes, only whole numbers of days are allowed. This is to be consistent with the security() function.
But it will allow some non-standard timeframes such as 7 hours (420 minutes). Such timeframes must still be supplied in the standard timeframe.period format.
param _tf
The timeframe to convert to minutes. Must be in timeframe.period format.
returns
An integer representing the number of minutes that the timeframe period is equivalent to.