Search code examples
pine-scripttrading

How to disable some moving averages based on bool input in pine scripts?


I have six moving averages that I use. But I want to disable 7 and 20 when using the daily chart and disable 200 and 300 when using the weekly chart. Hence, I am taking bool input "Daily MA" and "Weekly MA".

I am stuck here and not sure what to do from here. Do I use the if statement?

// Moving Averages
exponential = input(false, title="Exponential MA")
dailyma = input(true, title="Daily MA")
weeklyma = input(true, title="Weekly MA")

ma7 = exponential ? ema(src, 7) : sma(src, 7)
ma20 = exponential ? ema(src, 20) : sma(src, 20)
ma50 = exponential ? ema(src, 50) : sma(src, 50)
ma128 = exponential ? ema(src, 128) : sma(src, 128)
ma200 = exponential ? ema(src, 200) : sma(src, 200)
ma300 = exponential ? ema(src, 300) : sma(src, 300)

plot( ma7, color=orange, style=line, title="MA7", linewidth=1)
plot( ma20, color=black, style=line, title="MA20", linewidth=1)
plot( ma50, color=fuchsia, style=line, title="MA50", linewidth=1)
plot( ma128, color=purple, style=line, title="MA128", linewidth=1)
plot( ma200, color=black, style=line, title="MA200", linewidth=1)
plot( ma300, color=green, style=line, title="MA300", linewidth=1)

Solution

  • You can hide it using conditional colors.

    plot( ma7, color=timeframe.isdaily ? na : orange, style=line, title="MA7", linewidth=1)
    plot( ma20, color=timeframe.isdaily ? na : black, style=line, title="MA20", linewidth=1)
    
    plot( ma200, color=timeframe.isweekly ? na : black, style=line, title="MA200", linewidth=1)
    plot( ma300, color=timeframe.isweekly ? na : green, style=line, title="MA300", linewidth=1)
    

    Edit: with bool input added to the condition

    plot( ma7, color=timeframe.isdaily and dailyma ? na : orange, style=line, title="MA7", linewidth=1)
    plot( ma20, color=timeframe.isdaily and dailyma ? na : black, style=line, title="MA20", linewidth=1)
    
    plot( ma200, color=timeframe.isweekly and weeklyma ? na : black, style=line, title="MA200", linewidth=1)
    plot( ma300, color=timeframe.isweekly and weeklyma ? na : green, style=line, title="MA300", linewidth=1)
    

    Edit: version=4

    plot( ma7, color=timeframe.isdaily and dailyma ? na : color.orange, title="MA7")
    plot( ma20, color=timeframe.isdaily and dailyma ? na : color.black, title="MA20")
    
    plot( ma200, color=timeframe.isweekly and weeklyma ? na : color.black, title="MA200")
    plot( ma300, color=timeframe.isweekly and weeklyma ? na : color.green, title="MA300")