Search code examples
pine-scriptpine-script-v5

request.security getting different value when changing timeframe


I am trying to collect stochastic rsi 100 and 0 values in an array and use it for a strategy(or an indicator). I am having trouble getting a fixed value for it on timeframes. It works okay when I use the same time frame as collecting timeframe but when I change it to lower time frame on the live chart, it does not collect a correct value. This example below only gets right data when the timeframe is Month but not on lower ones like week or day. Can someone help resolve this issue?

//@version=5 
indicator(title="test", shorttitle="test", format=format.price, precision=2, overlay=true) 
// general options
displayMonthlySto = input(true, "Show Monthly Stoch", group="General Options")

// options for monthly stoRSI
smoothKMon = input.int(3, "K", minval=1, group="Monthly Time Frame Options") 
smoothDMon = input.int(3, "D", minval=1, group="Monthly Time Frame Options") 
lengthRSIMon = input.int(14, "RSI Length", minval=1, group="Monthly Time Frame Options") 
lengthStochMon = input.int(14, "Stochastic Length", minval=1, group="Monthly Time Frame Options") 
srcMon = input(close, title="RSI Source", group="Monthly Time Frame Options") 
rsi1Mon = ta.rsi(srcMon, lengthRSIMon) 
kMon = ta.sma(ta.stoch(rsi1Mon, rsi1Mon, rsi1Mon, lengthStochMon), smoothKMon) 
dMon = ta.sma(kMon, smoothDMon) 

// timeframe for month
stoMonth = request.security(syminfo.tickerid, "M", kMon)

// initialize arrys for stoch
var sto100MonArr = array.new_float() 
var sto0MonArr = array.new_float()

// collect sto100 and 0 data
if ta.change(time_close("1M")) and displayMonthlySto
    if stoMonth == 100 
        array.push(sto100MonArr, close)
    if stoMonth == 0
        array.push(sto0MonArr, close)

plot(array.size(sto100MonArr)>0 ? array.get(sto100MonArr, array.size(sto100MonArr)-1) : na)


Solution

  • Request.security gives inconsistent results when loading lower TF data For Lower TF data, you must use: https://www.tradingview.com/pine-script-reference/v5/#fun_request{dot}security_lower_tf

    This function returns an array of lower TF values

    For a locked bigger TF value, you can try this

    stoMonth = request.security(syminfo.tickerid, "M", kMon[1], barmerge.gaps_off, barmerge.lookahead_on)