Search code examples
pine-scriptseries

how to access pine script previous series value when supplying values to security.request() call


Consider the following simple pine script:

//@version=5

indicator("TestScript", "TestScript", true)


smaRes = ta.sma(close,1)
htf = "1D"
offset=-1
var smaResHi = 0.0

smaResHi := nz(request.security(syminfo.tickerid, htf, nz(smaRes[offset])))

plotchar(smaRes, "smaRes*", "")
plotchar(smaResHi, "smaResHi", "")

When offset==0, it works fine. however when offset==-1, it seems there is a runtime issue, and nothing is plotted. also there a red exclamation mark is displayed. see attached screen shot.

What is the problem?

enter image description here


Solution

  • You can hover your mouse over that exclamation mark and you will see a nice error message.

    But the situation is clear, you cannot index a Series with a negative value, for indexing in Pine you will use positive integers, Series work "backwards".

    The current value of a Series is referenced with zero, like close[0] and in this case you can leave off the [0]. So close == close[0].

    The "previous" value is referenced with [1]. The second previous value is referenced with [2], and so on. "Previous" is always referenced from the "current" candle. So if you use the Replay function and go back in time on the chart, whatever candle is drawn as last, will be "current" and "previous" will be the one that precedes "current".