Search code examples
timerpine-script

Timer in Pine Script


Is it possible to code a timer in Pine?

I want to check if a condition is met for an extended period of time, but for the real-time price. For example, if "close" is lingering above MA for 35 seconds, sound an alert.

It seems like it cannot be done, or at least not properly, since even the "countdown" scripts are very wonky and barely responsive.

Edit: Code that I already have, but it's not even remotely working

//@version=4
study("My Script")

int counter = 0
for t=timenow to timenow+29000 by 1000
    bool condition = close > close[1]
    if condition
        counter:=counter+1

isCounter = counter==30
plot(counter)
alertcondition(isCounter, title="alert", message="TEST ALERT")

Solution

  • I think this comes close to what you want.
    I didn't include the closing price is higher than the previous one condition in this conceptual example though.
    The label will turn green if more than 30 seconds have passed since the closing time of the previous bar.
    The drawback is that it's not very accurate, because Pine scripts get executed when the price changes.
    So an exact (continuous) timer cannot be created I'm afraid.

    You can watch it on a BTCUSD 1-minute chart.

    //@version=4
    study("My Script", "My", true)
    
    var     float   last_close      = na
    var     int     last_close_time = na
    var     color   myColor         = na
    var     label   myLabel         = label.new(na, na, "", style=label.style_label_left)
    
    last_close          := close[1]
    last_close_time     := time_close[1]
    
    over_threshold = barstate.isrealtime and (timenow - last_close_time >= 30000)
    myColor := over_threshold ? color.lime : color.blue
    
    label.set_xy(myLabel, bar_index, close)
    label.set_text(myLabel, tostring((timenow - last_close_time)/1000) + " seconds passed" )
    label.set_color(myLabel, myColor)