Search code examples
pine-scriptmoving-average

How to represent a positively and negatively sloped simple moving average on pinescript


I'm in the starting phases of creating my own strategy using pine script. The long condition for the strategy is that the simple moving averages must be positively sloped and the short condition is the opposite. So far I have:

outA = ta.sma(close, 15)    
outB = ta.sma(close, 30)

plot(outA, color=color.yellow, title="SMA(15)")    
plot(outB, color=color.blue, title="SMA(30)")

Solution

  • Check if the current moving average value is larger than the previous moving average value, to see if the slope is positive. You can see if it is positive by typing outA > outA[1] //current > previous

    Here is an example where the line is coloured green if the slope is positive: tradingview image of indicator

    Code:

    //@version=5
    indicator("sma slope")
    
    outA = ta.sma(close, 15)
    
    positiveSlopeA = outA > outA[1]
    colorA = positiveSlopeA ? color.green : color.red //positive slope -> green, else red
    plot(outA, color=colorA, title="SMA(15)")