MACD Strategy Pine Script Code
MACD Strategy Pine Script Code
// System Rules:
// 2. Only 1 bar can close above/below the 200 EMA over the past 5 bars
// 3. We take the FIRST MACD cross and ignore subsequent signals until TP/SL is hit
// 4. Stop Loss = 0.5 ATR above/below the recent swing high/low (7 bars lookback)
//
// @version=5
currency="USD",
calc_on_order_fills=true,
use_bar_magnifier=true,
initial_capital=10000,
default_qty_type=strategy.percent_of_equity,
commission_type=strategy.commission.cash_per_contract)
// Import ZenLibrary
// Check if our account currency is the same as the base or quote currency or neither (for risk $
conversion purposes)
if barstate.islastconfirmedhistory
table t = table.new(position.top_right, 1, 2, color.black)
// Calculate MACD
atr = ta.atr(14)
int barsAboveMA = 0
int barsBelowMA = 0
for i = 1 to 5
barsBelowMA += 1
barsAboveMA += 1
// Handle long trade entry (enter position, reset stops & targets)
if longTrade
if syminfo.type == "forex"
tradeStop := longStop
tradeSize := na
else
strategy.entry(id="Long", direction=strategy.long)
tradeStop := na
tradeTarget1 := na
tradeTarget2 := na
// Handle short trade entry (enter position, reset stops & targets)
if shortTrade
if syminfo.type == "forex"
tradeStop := shortStop
tradeSize := na
else
strategy.entry(id="Short", direction=strategy.short)
tradeStop := na
tradeTarget1 := na
tradeTarget2 := na
tradeSize := strategy.position_size
tradeStop := longStop
tradeSize := strategy.position_size
tradeStop := shortStop
tradeSize := strategy.position_size
// Handle both long & short trade break-even stops (do this AFTER first position has exited above ^)
if strategy.position_size != tradeSize
tradeStop := strategy.position_avg_price
tradeTarget1 := na