How It Trades
- Compute the MACD line (the 12-bar EMA minus the 26-bar EMA) and its signal line, a 9-bar EMA of the MACD itself.
- Buy when the MACD line crosses above its signal line: momentum has turned up faster than its own recent trend.
- Sell when the MACD line crosses back below the signal line.
Example Strategy
Pine Script
Paste it into TradingView’s Pine Editor to run these rules on any chart.
//@version=6
// MACD Signal Crossover — sort.finance. Fills at the signal bar's close, 0.02% fee a side,
// whole account per trade, as the backtest. History and indicator warm-up
// differ from the site's, so expect close to the same trades, not identical.
strategy("MACD Signal Crossover", overlay=false,
initial_capital=100, default_qty_type=strategy.percent_of_equity,
default_qty_value=100, commission_type=strategy.commission.percent,
commission_value=0.02, process_orders_on_close=true, pyramiding=0)
// The bar the current position opened on, and the bar the last one closed on.
var int entryBar = na
var int exitBar = -1
// ── Signals ──────────────────────────────────────────────────────────────
[macdLine, signalLine, histogram] = ta.macd(close, 12, 26, 9)
above = macdLine > signalLine
enterNow = above and not above[1]
exitNow = not above and above[1]
// ── Orders ───────────────────────────────────────────────────────────────
// Open on the first bar the entry holds while flat; close on the first
// later bar the exit holds; never reopen on the bar a position closed.
inTrade = strategy.position_size != 0
if inTrade and bar_index > entryBar and exitNow
strategy.close("Long")
exitBar := bar_index
else if not inTrade and bar_index > exitBar and enterNow
strategy.entry("Long", strategy.long)
entryBar := bar_index
// ── Drawing ──────────────────────────────────────────────────────────────
plot(macdLine, "MACD", color=#4d8dff)
plot(signalLine, "Signal", color=#e0a03a)
hline(0, "Zero", color=color.new(#8a92a0, 40), linestyle=hline.style_dashed)