MACD Strategy for TradingView:
Working PineScript Code + Backtest
This strategy enters long when the MACD line crosses above the signal line (bullish crossover) and exits when the MACD line crosses below the signal line (bearish crossover). The MACD crossover is one of the most widely-used trading signals in technical analysis. Unlike RSI mean reversion, this is a trend-following strategy — it aims to capture the middle of a move, not the reversal.
What is Moving Average Convergence Divergence?
MACD (Moving Average Convergence Divergence) is a trend-following momentum indicator that shows the relationship between two exponential moving averages of price. Created by Gerald Appel in the late 1970s, MACD is calculated by subtracting the 26-period EMA from the 12-period EMA. A 9-period EMA of the MACD line (the signal line) is then plotted on top. Traders watch for crossovers between the MACD line and signal line, as well as the histogram that visualizes the distance between them.
| Parameter | Value |
|---|---|
| fast Length | 12 |
| slow Length | 26 |
| signal Length | 9 |
MACD Crossover Strategy: The Setup
Entry Rules
- ▶Enter long when MACD line crosses above the signal line
- ▶Optionally filter: only enter when both lines are below zero (catching the trend early)
- ▶Position size: 100% of equity per trade
Exit Rules
- ■Exit long when MACD line crosses below the signal line
- ■No fixed stop-loss in base version
- ■Strategy is always in the market (long or flat)
Working PineScript Code
The script uses PineScript's built-in `ta.macd()` function which returns three values via tuple destructuring: the MACD line, signal line, and histogram. The `ta.crossover()` function detects when the MACD line crosses above the signal line (bullish), while `ta.crossunder()` detects the bearish cross. We use `strategy.entry()` for entries and `strategy.close()` for exits. Visual markers are plotted using `plotshape()` — green triangles below bars for buys, red triangles above bars for sells. A subtle green background color shows when the strategy holds a position.
//@version=5
strategy("MACD Crossover", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// === INPUTS ===
fastLength = input.int(12, "Fast Length", minval=1)
slowLength = input.int(26, "Slow Length", minval=1)
signalLength = input.int(9, "Signal Length", minval=1)
src = input.source(close, "Source")
// === CALCULATIONS ===
[macdLine, signalLine, histogram] = ta.macd(src, fastLength, slowLength, signalLength)
// === ENTRY CONDITIONS ===
bullishCross = ta.crossover(macdLine, signalLine)
bearishCross = ta.crossunder(macdLine, signalLine)
// === STRATEGY EXECUTION ===
if bullishCross
strategy.entry("MACD Long", strategy.long)
if bearishCross
strategy.close("MACD Long")
// === VISUAL SIGNALS ===
plotshape(bullishCross, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, title="Buy Signal")
plotshape(bearishCross, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, title="Sell Signal")
// === BACKGROUND COLOR ===
bgcolor(strategy.position_size > 0 ? color.new(color.green, 90) : na)Backtest Results: SPY (1D, 2019-2025)
Total Return
+52.1%
Annualized
+7.2%
Win Rate
44%
Max Drawdown
-18.7%
Sharpe Ratio
0.78
Total Trades
89
Profit Factor
1.54
Past performance does not guarantee future results. Backtest results may not reflect actual trading conditions including slippage, commissions, and liquidity constraints.
Optimization Tips
Add a histogram filter: only enter when the histogram is increasing (momentum is building). This filters out weak crossovers where the lines barely touch.
Combine with RSI to filter entries. Require RSI > 50 for long entries to confirm upward momentum alongside the MACD crossover.
Use the zero line as an additional filter. Bullish crossovers that occur below the zero line often signal the start of a new trend (price was in a downtrend and is reversing).
Experiment with faster MACD settings (8, 17, 9) for shorter-term trades on daily charts, or slower settings (19, 39, 9) for weekly position trades.
Add a trailing stop instead of waiting for the bearish crossover. MACD signals can be slow to exit, giving back significant profits. A 3x ATR trailing stop often improves results.
Common Mistakes with MACD on TradingView
Expecting high win rates from MACD crossover strategies. A 44% win rate is typical — the strategy profits because winning trades are much larger than losing trades. Do not abandon the strategy just because you see several losses in a row.
Using MACD crossover in range-bound markets. MACD is a trend-following indicator and will generate many small losses (whipsaws) when price is moving sideways. Consider pausing the strategy when ADX is below 20.
Confusing the MACD histogram with the MACD line. The histogram shows the distance between MACD and its signal line — it is not the MACD value itself. Crossovers of the histogram through zero equal MACD/signal crossovers.
Not understanding latency. MACD uses 26-period and 12-period EMAs, so it inherently lags price action. By the time a crossover confirms, a significant portion of the move may have already occurred. This is the tradeoff for confirmation.
Build This Strategy in 60 Seconds with SpendDock
Instead of copying and debugging this code, describe your strategy in plain English. SpendDock generates the PineScript code, backtests it against real market data, and lets you iterate until it is right.
Try SpendDock Free