Search code examples
pine-scriptpine-script-v5tradingview-apialgorithmic-trading

what is historical value for series that define in user-build function in pine script5?


I have code below. this is a user-built function. we pass "close" to "src" as an input. i know "src" and "atr" are series. so "up" is series too. after that "upper" is series too.

myfunc(src,length,mult)=>
atr = ta.atr(length)*mult
up = hl2 + atr
upper = 0.
upper := src[1] < upper[1] ? math.min(up,upper[1]) : up

now my question is what is the value of upper[1] when we compare it with src[1]? we dont have any calculation for measuring last values of "upper" before? is all previous values of "upper" equal to zero because we declare it like upper=0. ?


Solution

  • Functions have their own local scope and the historical values are available too just like if it was a global scope.

    See below example:

    //@version=5
    indicator("My script")
    
    foo() =>
        a = 0
        a := nz(a[1]) + 1
    
    a = foo()
    
    plot(a)
    

    On the first bar, a is zero and it will return 1 because 0 + 1 = 1.

    On the second bar, it will access the historical value of a[1], which is 1 and then add 1 to it. So, it will return 2.

    And so on.

    enter image description here