pine-scriptpine-script-v5

How to access the previous tick’s value when calc_on_every_tick=true in Pine Script?


I’m working on Pine Script where I need to update calculations on every tick. I have set calc_on_every_tick=true, but I’m struggling with accessing the previous tick’s value.

For example, I want to compare the current tick’s close value to the previous tick’s close value. Using close[1] retrieves the close value of the previous completed bar, not the previous tick.

How can I achieve this in Pine Script? Specifically, I want to determine if the current tick’s close value is higher than the previous tick’s close value. Any advice or code snippets would be greatly appreciated! Thank you.


Solution

  • You script will be executed on every tick. Therefore you need a variable type which will keep its value during those executions on the same bar. Therefore, you need varip variables.

    varip

    varip (var intrabar persist) is the keyword used for the assignment and one-time initialization of a variable or a field of a user-defined type. It’s similar to the var keyword, but variables and fields declared with varip retain their values between executions of the script on the same bar.

    //@version=5
    strategy("My strategy", overlay=true, calc_on_every_tick = true)
    
    varip float prev_tick = na
    varip float last_tick = na
    
    prev_tick := last_tick
    last_tick := close
    
    plotchar(prev_tick, "prev_tick", "")
    plotchar(last_tick, "last_tick", "")