A classic trend-following strategy that uses two moving averages to identify trend changes. Buy when the fast MA crosses above the slow MA, sell when it crosses below.
When the fast moving average (e.g., 9-period) crosses above the slow moving average (e.g., 21-period), it indicates a potential uptrend. Enter a long position.
When the fast moving average crosses below the slow moving average, it indicates a potential downtrend. Exit the long position.
| Parameter | Default | Description |
|---|---|---|
| Fast MA Length | 9 | Period for fast moving average |
| Slow MA Length | 21 | Period for slow moving average |
| Source | close | Price source for calculations |
//@version=5
strategy("Moving Average Crossover", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)
// Input parameters
fastLength = input.int(9, title="Fast MA Length", minval=1)
slowLength = input.int(21, title="Slow MA Length", minval=1)
src = input.source(close, title="Source")
// Calculate Moving Averages
fastMA = ta.sma(src, fastLength)
slowMA = ta.sma(src, slowLength)
// Plot Moving Averages
plot(fastMA, color=color.blue, title="Fast MA")
plot(slowMA, color=color.orange, title="Slow MA")
// Generate signals
bullishCrossover = ta.crossover(fastMA, slowMA)
bearishCrossunder = ta.crossunder(fastMA, slowMA)
// Entry conditions
if (bullishCrossover)
strategy.entry(id="Long", direction=strategy.long)
if (bearishCrossunder)
strategy.close(id="Long")
// Plot signals on chart
plotshape(bullishCrossover, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.tiny, text="BUY")
plotshape(bearishCrossunder, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.tiny, text="SELL")
// Alert conditions
alertcondition(bullishCrossover, title="Buy Alert", message="Bullish Crossover - Enter Long")
alertcondition(bearishCrossunder, title="Sell Alert", message="Bearish Crossunder - Exit Long")