How can I switch between using request.security() and request.security_lower_tf() in Pine Script based on the timeframe?
These functions return two different data types: the first returns a series of float, while the second returns an array of float.
How can I uniform them so that I can switch between them seamlessly?
For switching the function could be something like that:
if timeframe.in_seconds(timeframe.period) < timeframe.in_seconds(tf)
result = request.security_lower_tf(stringaMomentum, timeframe, close - open)
else
result = request.security(stringaMomentum, timeframe, close - open)
but what type should I declare result? The function returns several types.
And how can I calculate the indicators on it (e.g. ta.sma(result, 50)
), if the type is changed (non-series)?
Here is a script providing an array with all the values of the lowest timeframe between the chart timeframe or the asked timeframe choosen by the user
//@version=5
indicator("TimeFrame Switcher")
AskedTimeframe = input.timeframe("D", "Timeframe used for calculation")
if timeframe.in_seconds(timeframe.period) < timeframe.in_seconds(AskedTimeframe)
// Used to prevent error in the line resultLTF = request.security_lower_tf(syminfo.tickerid, AskedTimeframe, close - open)
// if a greater timeframe is asked, we don't need resultLTF
// but in request.security_lower_tf(syminfo.tickerid, AskedTimeframe, close - open)
// the AskedTimeframe must be equal or lower to the chart time frame
AskedTimeframe := timeframe.period
resultLTF = request.security_lower_tf(syminfo.tickerid, AskedTimeframe, close - open)// Array
resultHTF = request.security(syminfo.tickerid ,AskedTimeframe, close - open) // float
var result = array.new_float(0, na)
if timeframe.in_seconds(timeframe.period) > timeframe.in_seconds(AskedTimeframe)
// We need to copy the array in resultLTF to result
result := array.concat(result, resultLTF)
else
// We need to create X times the resultHTF value in the array
// How many bars of the actual timeframe are in one bar of the AskedTimeframe
NbBars = int(timeframe.in_seconds(AskedTimeframe)/timeframe.in_seconds(timeframe.period))
ArrayToAdd = array.new_float(NbBars, na)
array.fill(ArrayToAdd, resultHTF)
result := array.concat(result, ArrayToAdd)
// At this point, result is an array containing All the data from the lowest time frame, in chronological order
// The array is at his max size when the AskedTimeframe is equal or greater than the chart timeframe
if barstate.islast and false // set to thrue to see the size of the array
label.new(bar_index, close, str.tostring(array.size(result)))
SMACalcul = ta.sma(array.get(result, array.size(result)-1), 50)
plot(SMACalcul)