Search code examples
pine-scriptpine-script-v5

How start a retroactive count in Pinescript once a condition is met


I'm plotting an SMA crossover in Pinescript for Tradingview.

Once the crossover occurs, I'd like a retroactive countdown to be displayed as per the image, starting 9 bars back, with the 9th bar at the crossover point.

Conditional retroactive count

Any tips on how I start a conditional retroactive countdown such as this?

Thank you!

I can code the SMA crossover and plot the characters just fine. I just can't figure out how to start a conditional, retroactive count such as this.


Solution

  • Just use a for loop when there is a cross and call label.new() within the loop.

    //@version=5
    indicator("My script", overlay=true)
    
    sma_9 = ta.sma(close, 9)
    sma_50 = ta.sma(close, 50)
    
    plot(sma_9, color=color.green)
    plot(sma_50, color=color.red)
    
    sma_cross = ta.crossunder(sma_9, sma_50)
    
    plotshape(sma_cross)
    
    if (sma_cross)
        for i = 0 to 8
            label.new(bar_index[i], high, str.tostring(9 - i), yloc=yloc.abovebar, color=color.new(color.white, 100), textcolor=color.green)
    

    enter image description here