pine-scriptpine-script-v5pine-script-v4

Pinescript block of code executes more than once despite the flag


Can someone tell me, why does this code execute more than once?

var testalert = true
if testalert and timenow > 1724003180000
    strategy.order("TestLong", strategy.long, limit=61000,  qty=0.5, comment="ENTER-LONG_BINANCE-FUTURES_BTCUSDT_Ondrejs-Bot_30M_472398966e86382d84031451")
    label.new(x=bar_index, y = open, text=str.tostring(timenow), color=color.red, style=label.style_label_down, textcolor=color.white, size=size.large)
    testalert := false

For the record, I am setting this in the strategy settings:

calc_on_every_tick=true

But that still doesn't explain it, does it?


Solution

  • var will still allow intra-bar updates. You need 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.

    Run below test code on seconds timeframe and you should see the behavior of var vs varip in the data window.

    //@version=5
    indicator("My script", overlay=true)
    
    var flag1 = false
    varip flag2 = false
    
    var float close1 = na
    varip float close2 = na
    
    if (barstate.isnew)
        flag1 := false
        flag2 := false
    else
        if (not flag1)
            close1 := close
            flag1 := true
        
        if (not flag2)
            close2 := close
            flag2 := true
    
    plotchar(flag1, "flag1", "", color=color.green)
    plotchar(flag2, "flag2", "", color=color.red)
    plotchar(close1, "close1", "", color=color.green)
    plotchar(close2, "close2", "", color=color.red)