Trading Strategy

MACD Strategy

A trend-following momentum indicator that uses the relationship between two moving averages to identify new trends.

The Momentum Engine

Combining the principles of moving averages and oscillators, the MACD identifies changes in the strength, direction, momentum, and duration of a trend. This strategy uses a 200 EMA to ensure trades only occur when aligned with the dominant market direction, significantly increasing the probability of success.

Trend Type
4h Chart Timeframe
Beginner Complexity
Trending Best Market

Signal Logic

Golden Cross

Triggered when MACD line crosses above Signal line, and price is above the 200 EMA trend filter.

Death Cross

Triggered when MACD line crosses below Signal line, and price is below the 200 EMA trend filter.

Implementation

//@version=6
strategy("MACD Strategy", overlay = true, initial_capital = 1000000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, currency = currency.USD)

// ==========================================
// 🔹 INPUTS
// ==========================================

// MACD Settings
fastLength = input.int(12, title="Fast Length", group="MACD Settings")
slowLength = input.int(26, title="Slow Length", group="MACD Settings")
signalSmoothing = input.int(9, title="Signal Smoothing", group="MACD Settings")
src = input.source(close, title="Source", group="MACD Settings")

// Trend Filter Settings
useTrendFilter = input.bool(true, title="Filter Trades with EMA 200?", group="Trend Filter")
trendLength = input.int(200, title="Trend EMA Length", group="Trend Filter")

// Risk Management
useRiskMgt = input.bool(true, title="Use Stop Loss / Take Profit?", group="Risk Management")
stopLossPerc = input.float(5, title="Stop Loss (%)", step=0.1, group="Risk Management") / 100
takeProfitPerc = input.float(10, title="Take Profit (%)", step=0.1, group="Risk Management") / 100

// --- CALCULATIONS ---

// MACD Calculation
[macdLine, signalLine, histLine] = ta.macd(src, fastLength, slowLength, signalSmoothing)

// Trend Filter Calculation (200 EMA)
trendEma = ta.ema(src, trendLength)

// --- STRATEGY LOGIC ---

// Conditions
// Bullish: MACD crosses over Signal AND Price is above 200 EMA (if filter is on)
bullishCrossover = ta.crossover(macdLine, signalLine)
trendIsBullish = useTrendFilter ? (close > trendEma) : true
enterLong = bullishCrossover and trendIsBullish

// Bearish: MACD crosses under Signal AND Price is below 200 EMA (if filter is on)
bearishCrossunder = ta.crossunder(macdLine, signalLine)
trendIsBearish = useTrendFilter ? (close < trendEma) : true
enterShort = bearishCrossunder and trendIsBearish

// --- EXECUTION ---

// Entry Logic
if enterLong
    strategy.entry("Long", strategy.long, comment="MACD Bull")

if enterShort
    strategy.entry("Short", strategy.short, comment="MACD Bear")

// Exit Logic (Stop Loss / Take Profit)
if useRiskMgt
    if strategy.position_size > 0
        // Calculate dynamic exit prices for Long
        longStop = strategy.position_avg_price * (1 - stopLossPerc)
        longTP = strategy.position_avg_price * (1 + takeProfitPerc)
        strategy.exit("Exit Long", "Long", stop = longStop, limit = longTP)
    
    if strategy.position_size < 0
        // Calculate dynamic exit prices for Short
        shortStop = strategy.position_avg_price * (1 + stopLossPerc)
        shortTP = strategy.position_avg_price * (1 - takeProfitPerc)
        strategy.exit("Exit Short", "Short", stop = shortStop, limit = shortTP)

// --- VISUALS ---

// Plot the Trend EMA
plot(trendEma, color = color.orange, linewidth = 2, title = "200 EMA Trend Filter")

// Plot Buy/Sell Signals
plotshape(enterLong, style = shape.triangleup, location = location.belowbar, color = color.green, size = size.small, title = "Buy Signal")
plotshape(enterShort, style = shape.triangledown, location = location.abovebar, color = color.red, size = size.small, title = "Sell Signal")

// Background color to indicate trend context
bgcolor(useTrendFilter and close > trendEma ? color.new(color.green, 95) : useTrendFilter and close < trendEma ? color.new(color.red, 95) : na)