Search code examples
pine-scriptpine-script-v5

Determine the average volume of the MacdLine that is above the ZeroLine Pine Script Tradingview


I want to determine the average of the macdLine values that are above the ZeroLine on the 5m timeframe for the last 5000 bars in pine script tradingview

This was my idea:

//@version=5
indicator('My Script', overlay=false)

[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)

plot(macdLine, color=color.yellow)

sum=0
lenght = 5000
lenght2 = 0
    for i = 1 to length-1
        if 0 < macdLine [i]
            sum := sum + macdLine [i]
            lenght2 := lenght2 + 1

macdlineaverage = sum / lenght2

But i get this error and I don't know if this is the right approach: Mismatched input 'for' expecting 'end of line without line continuation'.

Hope someone can help me.


Solution

  • the for loop in your snippet should start from the new line, also explicitly declared the types of the variables to fix the issue, as is shown below:

    //@version=5
    indicator('My Script', overlay=false)
    
    [macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)
    
    // plot(macdLine, color=color.yellow)
    
    float sum = 0
    var int length = 5000
    int length2 = 0
    for i = 1 to length-1
        if 0 < macdLine[i]
            sum := sum + macdLine[i]
            length2 := length2 + 1
    
    float macdlineaverage = sum / length2
    plot(macdlineaverage)