Search code examples
pine-scriptpine-script-v5

Count bars lower since new highest high


What I am trying to accomplish is a Pine Script that count how many bars back are inferior to the new highest high since an eventual break-out.

//@version=5
indicator('Test')

len = input(20)
threshold = 0.01
upper = ta.highest(high, len)
u = ta.barssince(close > (upper+threshold))
plot(u)

enter image description here


Solution

  • You can do something like this. You may want to add a variable that if a new high isn't reached after a certain number of days to just take the most recent high in case a stock is well off it's previous highs.

    indicator("My script", overlay = true)
    
    var float highest = 0.0
    var int highIndex = 0
    var barsincehigh = 0 
    
    if close > highest 
        highest := high
        highIndex := bar_index
        barsincehigh := 0
    else
        barsincehigh += 1 
    
    if highest > highest[1] and barsincehigh[1] > 1
        label.new(bar_index, high, str.tostring(barsincehigh[1]), color = color.lime)
    

    Barsince High in lables