strategy · own pane · open source
MACD Crossover
Running…
Loading chart…
About
Trend-following MACD crossover long-only: enter on a bullish MACD/signal cross, exit on the bearish cross. The histogram visualises momentum strength.
- Raise the spread between
FastandSlowfor fewer, larger swings. - Tighter
Signalsmoothing reacts faster but adds whipsaw in chop. - Combine with an ADX > 25 filter to dodge range-bound whipsaws.
Source code
//@version=5
strategy("MACD Crossover", overlay=false, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.percent, commission_value=0.05)
fast = input.int(12, "Fast Length", minval=2, maxval=30, step=1)
slow = input.int(26, "Slow Length", minval=10, maxval=100, step=1)
sig = input.int(9, "Signal Length", minval=2, maxval=50, step=1)
stopPct = input.float(2, "Stop Loss %", minval=0.5, maxval=10, step=0.1)
tpPct = input.float(6, "Take Profit %", minval=0, maxval=20, step=0.1)
[m, s, h] = ta.macd(close, fast, slow, sig)
longSignal = strategy.position_size == 0 and ta.crossover(m, s)
exitSignal = strategy.position_size > 0 and ta.crossunder(m, s)
if longSignal
strategy.entry("Long", strategy.long)
if strategy.position_size > 0
strategy.exit("Risk", stop=stopPct > 0 ? strategy.position_avg_price * (1 - stopPct / 100) : na, limit=tpPct > 0 ? strategy.position_avg_price * (1 + tpPct / 100) : na)
if exitSignal
strategy.close("Long", comment="MACD cross down")
hline(0, "Zero", color=color.gray, linestyle=hline.style_dotted)
p_MACD = plot(m, "MACD", color=color.blue, linewidth=2)
p_Signal = plot(s, "Signal", color=color.orange)
p_Histogram = plot(h, "Histogram", color=h >= 0 ? color.green : color.red, style=plot.style_columns)
plotshape(longSignal, "Long", style=shape.triangleup, location=location.belowbar, color=color.green, text="L")
plotshape(exitSignal, "Exit", style=shape.triangledown, location=location.abovebar, color=color.red, text="X")
alertcondition(longSignal, "MACD long entry", "MACD crossed above signal")
alertcondition(exitSignal, "MACD exit", "MACD crossed below signal")
No comments yet.
Sign in to comment.