Search code examples
pine-scriptpine-script-v5

check how many of the last 50 bars closed above moving average


I am wondering if there is a better way to check how many of the last 50 bars closed above or below a moving average

The only solution i can come up with is by checking it bar by bar like:

bar1 = close[1] > MA1[1] ? 1 : -1
bar2 = close[2] > MA1[2] ? 1 : -1

etc.

then after this i would need to see what % closed above and below like:

count = bar1 + bar2 + bar3 + bar4 ..... + bar 50

percentage = count / 50 * 100

Is there a function or a better solution for this?


Solution

  • The way to use this is to use math.sum().

    The sum function returns the sliding sum of last y values of x.

    So, you need to pass your condition with length being 50 and it will check your condition within the last 50 bars and return you the sliding sum.

    //@version=5
    indicator("My script", overlay=true)
    
    sma_9 = ta.sma(close, 9)
    condition = (close > sma_9)
    
    cnt = math.sum(condition ? 1 : 0, 50)
    
    plot(sma_9)
    plotchar(cnt, "cnt", "")