Pipsgrowth EX08002 MACD
MT5 Expert Advisor (Open Source) · XAUUSD · M15, H1
Pipsgrowth.com EX08002 GoldScalper_MACDScalp_TrendFollowing — MACD trend scalper with pyramiding, full 12-layer stack.
Overview
EX08002 is a MACD-based trend-following scalper designed primarily for XAUUSD on the M15 timeframe, with H1 as a viable secondary setting. It belongs to the EX08 MACD family (magic 22208002, v2.00) and ships with a complete 12-layer safety stack rather than a stripped-down crossover. The strategy is mechanical: on every new M15 bar, the EA reads the MACD main line and signal line on closed-bar[1] and bar[2] (no repaint from the forming bar), detects a fresh cross between them, optionally confirms it with a histogram expansion, and fires a market order in the direction of the cross. That is the entire signal logic — there is no ADX filter, no higher-timeframe bias, no regime classifier, and no multi-factor score. The 12 layers live downstream of the signal, in trade management, position sizing, and no-trade gating.
The MACD defaults are 12/26/9 on close — the standard Gerald Appel configuration — and the histogram filter is on by default. With the filter on, a bullish cross is only valid when the histogram (MACD − Signal) is positive and expanding, meaning the gap between the two lines is widening in the direction of the trade. This eliminates the weak, doji-like crosses that occur when both lines hover near zero. The histogram filter is the EA's only confirmation step; there is no candle-pattern check, no volume requirement, no RSI divergence, and no second indicator. Turn the filter off and you get raw cross signals, which fires more often but with a higher failure rate near flat MACD regimes.
Position sizing is dynamic by default. With UseMoneyManagement=true and RiskPercent=2.0, the EA sizes each order so that a stop at the calculated distance would risk 2% of effective capital. Effective capital is the smaller of current equity and InpCapitalCapAmount when that cap is enabled above zero; with the cap at its 0.0 default, equity alone is used. The lot is floored to the symbol's volume step and clamped to min/max lot, then checked against free margin — if the requested lot would consume more than 90% of free margin, the EA scales the lot down to fit, and if even the minimum lot would not fit, the trade is skipped. The FixedLotSize fallback of 0.01 is for traders who prefer a flat size regardless of SL distance.
Stop placement is the most consequential part of the EA. The default StopLossPips of 20 pips is treated as a floor, not a fixed number. The actual SL distance is max(ATR(14) × 2.0, 20 pips, 1.5 × minimum stop level). On a quiet M15 bar with ATR near 0.5 USD on gold, ATR×2 comes in well below 20 pips and the user input wins; on a high-volatility bar (NFP, FOMC, Asian flash event) where ATR spikes to 1.5 USD, the ATR floor wins and the stop is widened to roughly 60 pips or more. This makes the stop volatility-adaptive: it never shrinks below the user's safety floor, but it expands automatically when the market does. The take-profit mirrors the same logic at a fixed 2:1 R:R — TP distance is exactly 2× the chosen SL distance, so on a 20-pip stop the TP is 40 pips, on a 60-pip ATR stop the TP is 120 pips. There is no partial close and no breakeven step; trades either run to TP, hit SL, get stopped out by the trailing stop, or get closed by an opposite MACD cross.
Pyramiding is enabled by default with MaxOpenPositions=2 and PyramidDistancePips=20. The pyramid logic is direction-locked: a long signal will not open a short, and a short signal will not open a long — opposite-direction entries are blocked. Pyramiding only adds to the existing direction, and the new entry must be at least 20 pips from the most recent entry on that symbol. With the default 2-position cap, the EA can hold at most 2 buys or 2 sells at a time, not a mixed basket. This is safer than grid-style pyramiding (no averaging into losers) but more aggressive than a single-position EA. The 20-pip spacing is wide enough that a single stop-hunt spike will not trigger a back-to-back entry.
Trailing-stop is enabled by default with TrailingStartPips=15 and TrailingStepPips=5. The trail is a classic server-side ratchet: once price has moved 15 pips in the trade's favor, the stop is set to (current − 15) pips, then on every subsequent 5-pip improvement the stop ratchets forward to (current − 15) pips again. The 5-pip step prevents the broker from being hammered with modify requests on every tick — the trail only fires when price meaningfully moves. The trail is always honored regardless of the MACD cross state, so a position can be trailed out even if the MACD cross would have kept it open.
The no-trade gate is where most of the 42 inputs end up. IsSafeToTrade() runs on every tick and checks, in order: capital cap not exceeded, capital floor not breached, equity above InpMinEquityPercent (default 95%) of initial balance, daily realized loss not below −InpDailyLossLimitPct% (3%) of effective capital, weekly realized loss not below −InpWeeklyLossLimitPct% (6%), not in cooldown after InpMaxConsecLosses (3) consecutive losses, trade count under InpMaxTradesPerDay (50), market is open (no Saturday, no Friday after 21 GMT, no Sunday before 22 GMT), currently in London (07–16 GMT) or New York (12–21 GMT) session with Asia avoided (00–07 GMT) by default, and not within InpNewsFilterMinutes (15) of a session-open news event. If any of these fails, the EA manages existing positions (trailing, opposite-cross exit) but does not open new ones. The OnTradeTransaction hook updates g_realizedToday, g_realizedWeek, g_tradesToday, and g_consecLosses from closed deals in the last 90 days of history.
The OnTester function is a single weighted score: (net_profit × profit_factor) / (1 + balance_dd_percent). The 1 + dd term means a 20% drawdown halves the score relative to a 0% drawdown. The hard requirement of at least 30 trades is enforced by returning 0 below that count, which prevents the optimizer from overfitting to a handful of lucky trades. There is no OnTesterPass hook, no custom fitness criterion per symbol, and no multi-criterion ranking.
The closing trades mechanism uses CTrade with auto-detected filling (FOK → IOC → RETURN), 3-attempt retry loops on REQUOTE / TIMEOUT / PRICE_OFF / PRICE_CHANGED with 200ms sleeps for closes and 100ms sleeps for modifies, and an early-return no-op when the requested SL/TP is within 1 point of the current values. TryClosePartial_EX08002 is declared and would close a partial volume, but it is never called from ManageOpenPositions, OpenPosition, or OnTick — the EA never scales out of a position, only all-in or all-out.
What to expect in backtesting: this is a high-trade-count trend EA. On M15 XAUUSD with default inputs you should see dozens of entries per month, frequent small losses on failed crossovers, and occasional large winners when MACD catches a sustained gold move. The 2:1 R:R TP plus the trailing stop means many trades exit at less than 2:1 in practice (the trail or the opposite cross usually fires first), but the winners that do run typically pay for several losers. The 95% equity floor, the 3%/6% daily/weekly loss caps, and the 3-consec-losses cooldown make the EA's worst-case drawdown profile predictable even when the strategy itself has a choppy losing streak. Backtests will look cleaner on H1 (fewer trades, smoother equity) and noisier on M15 (more trades, more granular P&L, but more commission drag on tight spreads). For live deployment, set InpServerGMTOffset to your broker's actual GMT offset (or leave at 0 for auto-detection via the weekend bar gap) and confirm that the London/NY session window lines up with the hours you actually want the EA active.
Strategy Deep Dive
On every new M15 bar, RefreshIndicators() pulls the last two closed bars of MACD(12,26,9) and the latest ATR(14), computes current and previous histogram values, and IsSafeToTrade() runs the no-trade gate (capital cap/floor, equity floor, daily/weekly loss limits, consec-loss cooldown, daily trade cap, market hours, London+NY session window, news avoidance). GetMACDSignal() then checks for a fresh cross: bullish when prevMACD <= prevSignal and currentMACD > currentSignal, bearish in the mirror — and applies the histogram-expansion confirmation if UseHistogramFilter is on. CanOpenPosition() enforces direction-locked pyramiding (no opposite entries) and the 20-pip minimum distance between consecutive entries of the same direction, capped at MaxOpenPositions=2. OpenPosition() calculates SL as max(ATR×2, 20 pips, 1.5×min stop), TP at 2× that distance, sizes the lot from 2% of effective capital via CalculatePositionSize(), checks free margin, and submits through CTrade with 3-attempt REQUOTE/TIMEOUT retry. ManageOpenPositions() runs every tick (not just on new bars) to apply the trailing-stop ratchet once profit exceeds 15 pips, advancing the SL by 5-pip steps, and to close the position immediately on an opposite MACD cross when ExitOnOppositeCross is true. OnTradeTransaction updates realized P&L, daily/weekly loss counters, and the consecutive-loss streak from closed deals, which feeds the cooldown timer and the daily-trade cap.
Entries fire on a fresh MACD signal-line cross on closed M15 bars. A long entry triggers when the MACD main line crosses above the signal line and (when the histogram filter is on) the histogram is positive and expanding; a short entry is the mirror. The cross is detected on bar[1] vs bar[2] to avoid repaint, and only one direction is taken per bar. Pyramiding is direction-locked: with MaxOpenPositions=2 and PyramidDistancePips=20, the EA can add a second same-direction entry if price has moved 20 pips from the most recent one, but will not open against an existing position.
Exits come from three sources, in priority order: (1) a take-profit hit at exactly 2× the volatility-adaptive SL distance, (2) the trailing stop ratchet once price has moved 15 pips in favor and continues to improve in 5-pip steps, and (3) an opposite MACD cross closing the position early when ExitOnOppositeCross is enabled. There is no breakeven step and no partial close — every position is closed all-or-nothing.
Stop-loss is volatility-adaptive: actual SL distance is max(ATR(14) × 2.0, the user's StopLossPips input, 1.5 × the broker's minimum stop level). With the 20-pip default, SL is 20 pips on quiet M15 bars and widens to 60+ pips when gold ATR spikes. The same distance is used for the dynamic lot sizing calculation, so a wider stop mechanically produces a smaller position size.
Take-profit is a fixed 2:1 R:R anchored to the chosen SL distance — if SL ends up at 20 pips the TP is 40 pips, if ATR widens SL to 60 pips the TP becomes 120 pips. There is no fixed-pip TP override; the 2:1 ratio is the only TP rule.
Best deployed on XAUUSD M15 with a $100 minimum balance and a low-spread ECN broker (max spread under 25 pips). The London+New York session window with Asia avoidance is hardcoded into the safety gate, so the EA is most active during the 07–16 GMT and 12–21 GMT overlaps when gold trends the cleanest. The 2% default risk plus the 3-consec-losses 30-minute cooldown plus the 3%/6% daily/weekly loss caps make this a MEDIUM-risk, high-trade-count trend system suited for traders who want frequent MACD-signal exposure with automated volatility-adaptive stops rather than hand-managed entries. H1 deployment is viable for lower-frequency, smoother-equity operation.
Strategy Logic
Pipsgrowth EX08002 MACD — Strategy Logic Analysis (from .mq5 source)
Family: MACD
Magic: 22208002
Version: 2.00
BRIEF:
MACD trend-following scalper for gold that enters on MACD/signal line crossovers with histogram confirmation, dynamic risk-based position sizing, trailing stops, pyramiding, spread and time filters across a 12-layer architecture. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
SafePositionModify()RefreshIndicators()GetMACDSignal()CanOpenPosition()OpenPosition()CalculatePositionSize()ManageOpenPositions()IsNewBar()GetPipSize()CheckFilters()GetEffectiveCapital()OnTradeTransaction()- ...and 10 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (42 total across 9 groups):
- [=== Risk Management ===]
UseMoneyManagement=true// Use Dynamic Risk % - [=== Risk Management ===]
RiskPercent=2.0// Risk Percent per Trade - [=== Risk Management ===]
FixedLotSize=0.01// Fixed LotSize(if MMfalse) - [===
MACDSettings ===] MACD_Fast = 12 //MACDFastEMA - [===
MACDSettings ===] MACD_Slow = 26 //MACDSlowEMA - [===
MACDSettings ===] MACD_Signal = 9 //MACDSignal Period - [===
MACDSettings ===]UseHistogramFilter=true// Require Histogram Confirmation - [=== Trade Settings ===]
StopLossPips= 20 // StopLoss(pips) - [=== Trade Settings ===]
TakeProfitPips= 40 // TakeProfit(pips) - [=== Trade Settings ===] Slippage = 3 // Max
Slippage(points) - [=== Trade Settings ===]
InpMagicNumber=22208002// MagicNumber(222 + Expert ID) - [=== Trade Settings ===]
InpTradeComment= "Psgrowth.com Expert_08002" // TradeComment - [=== Trailing Stop ===]
UseTrailingStop=true// Use Trailing Stop - [=== Trailing Stop ===]
TrailingStartPips= 15 // TrailingStart(pips) - [=== Trailing Stop ===]
TrailingStepPips= 5 // TrailingStep(pips) - [=== Pyramiding ===]
UsePyramiding=true// Use Pyramiding - [=== Pyramiding ===]
MaxOpenPositions= 2 // Max Open Positions - [=== Pyramiding ===]
PyramidDistancePips= 20 // Distance between entries (pips) - [=== Filters ===]
UseSpreadFilter=true// Use Spread Filter - [=== Filters ===]
MaxSpreadPips=25.0// MaxSpread(pips) - [=== Filters ===]
UseTimeFilter=false// Use Time Filter - [=== Filters ===]
StartTime= "08:00" // StartTime(HH:MM) - [=== Filters ===]
EndTime= "20:00" // EndTime(HH:MM) - [=== Filters ===]
ExitOnOppositeCross=true// Exit on OppositeMACDCross - [=== Hardening: Risk Management ===]
InpMaxConsecLosses= 3 // Max consecutive losses before cooldown (0=disabled) - [=== Hardening: Risk Management ===]
InpCooldownMinutes= 30 // Cooldown minutes after consec losses (0=disabled) - [=== Hardening: Risk Management ===]
InpMaxTradesPerDay= 50 // Maximum trades per day - [=== Hardening: Risk Management ===]
InpMinEquityPercent=95.0// Stop trading if equity < this % of initial balance - [=== Hardening: Risk Management ===]
InpDailyLossLimitPct=3.0// Daily loss limit (% of effective capital) - [=== Hardening: Risk Management ===]
InpWeeklyLossLimitPct=6.0// Weekly loss limit (% of effective capital) - [=== Hardening: Capital Allocation Cap ===]
InpCapitalCapAmount=0.0// Cap amount ($ real money equity) - [=== Hardening: Capital Allocation Cap ===]
InpCapitalCapFloor=50.0//Floor($); block entries below this - [=== Hardening:
GMTSessions ===]InpServerGMTOffset= 0 // ServerGMToffset hours (0=auto-detect) - [=== Hardening:
GMTSessions ===]InpLondonStartHour= 7 // London session start (GMT) - [=== Hardening:
GMTSessions ===]InpLondonEndHour= 16 // London session end (GMT) - [=== Hardening:
GMTSessions ===]InpNYStartHour= 12 // New York session start (GMT) - [=== Hardening:
GMTSessions ===]InpNYEndHour= 21 // New York session end (GMT) - [=== Hardening:
GMTSessions ===]InpAvoidAsia=true// Avoid Asian session - [=== Hardening:
GMTSessions ===]InpAsiaStartHour= 0 // Asian session start (GMT) - [=== Hardening:
GMTSessions ===]InpAsiaEndHour= 7 // Asian session end (GMT) - [=== Hardening:
GMTSessions ===]InpNewsFilter=false// Avoid trading near news session opens - [=== Hardening:
GMTSessions ===]InpNewsFilterMinutes= 15 // Minutes to avoid around news
// Pipsgrowth EX08002 MACD — Execution Flow (from source analysis)
// Family: MACD
// MACD trend-following scalper for gold that enters on MACD/signal line crossovers with histogram confirmation, dynamic risk-based position sizing, trailing stops, pyramiding, spread and time filters across a 12-layer architecture. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
ON_INIT:
Create indicator handles: standard set
Initialize state variables
Detect broker GMT offset
ON_TICK:
1. Refresh indicator buffers (closed-bar shift=1)
2. Manage existing positions:
- Break-even check
- ATR trailing stop
- Profit lock ratchet
- Time-based exit
- Opposite-signal exit
3. If new bar:
a. ClassifyRegime() — ADX/ATR/BB regime detection
b. NoTradeGate() checks:
- Market open + session filter
- Spread limit
- Cooldown after loss
- Consecutive loss limit
- Kill switch
- Max drawdown
- Max concurrent positions
- Daily/weekly loss limits
c. GenerateSignal() — strategy-specific entry logic
d. CheckConfirm() — HTF alignment + R:R + ADX minimum
e. Calculate position size from risk %
f. Execute with retry logic
g. Mark bar to prevent duplicates
ON_TESTER:
Custom fitness = weighted(RecoveryFactor, ROI, ProfitFactor, TradeCount, Sharpe, Drawdown)Optimization Profile
How to Install This EA on MT5
- 1Download the .mq5 file using the button above
- 2Open MetaTrader 5 on your computer
- 3Click File → Open Data Folder in the top menu
- 4Navigate to MQL5 → Experts and paste the .mq5 file there
- 5In MT5, right-click Expert Advisors in the Navigator panel → Refresh
- 6Drag the EA onto an H4 or Daily chart for best results
- 7Configure EMA periods, ADX threshold, and lot size in the dialog
- 8Enable Allow Algo Trading and click OK
EA Parameters
| Parameter | Default | Description |
|---|---|---|
| UseMoneyManagement | true | Use Dynamic Risk % |
| RiskPercent | 2.0 | Risk Percent per Trade |
| FixedLotSize | 0.01 | Fixed Lot Size (if MM false) |
| MACD_Fast | 12 | MACD Fast EMA |
| MACD_Slow | 26 | MACD Slow EMA |
| MACD_Signal | 9 | MACD Signal Period |
| UseHistogramFilter | true | Require Histogram Confirmation |
| StopLossPips | 20 | Stop Loss (pips) |
| TakeProfitPips | 40 | Take Profit (pips) |
| Slippage | 3 | Max Slippage (points) |
| InpMagicNumber | 22208002 | Magic Number (222 + Expert ID) |
| InpTradeComment | "Psgrowth.com Expert_08002" | Trade Comment |
| UseTrailingStop | true | Use Trailing Stop |
| TrailingStartPips | 15 | Trailing Start (pips) |
| TrailingStepPips | 5 | Trailing Step (pips) |
| UsePyramiding | true | Use Pyramiding |
| MaxOpenPositions | 2 | Max Open Positions |
| PyramidDistancePips | 20 | Distance between entries (pips) |
| UseSpreadFilter | true | Use Spread Filter |
| MaxSpreadPips | 25.0 | Max Spread (pips) |
| UseTimeFilter | false | Use Time Filter |
| StartTime | "08:00" | Start Time (HH:MM) |
| EndTime | "20:00" | End Time (HH:MM) |
| ExitOnOppositeCross | true | Exit on Opposite MACD Cross |
| InpMaxConsecLosses | 3 | Max consecutive losses before cooldown (0=disabled) |
| InpCooldownMinutes | 30 | Cooldown minutes after consec losses (0=disabled) |
| InpMaxTradesPerDay | 50 | Maximum trades per day |
| InpMinEquityPercent | 95.0 | Stop trading if equity < this % of initial balance |
| InpDailyLossLimitPct | 3.0 | Daily loss limit (% of effective capital) |
| InpWeeklyLossLimitPct | 6.0 | Weekly loss limit (% of effective capital) |
| InpCapitalCapAmount | 0.0 | Cap amount ($ real money equity) |
| InpCapitalCapFloor | 50.0 | Floor ($); block entries below this |
| InpServerGMTOffset | 0 | Server GMT offset hours (0=auto-detect) |
| InpLondonStartHour | 7 | London session start (GMT) |
| InpLondonEndHour | 16 | London session end (GMT) |
| InpNYStartHour | 12 | New York session start (GMT) |
| InpNYEndHour | 21 | New York session end (GMT) |
| InpAvoidAsia | true | Avoid Asian session |
| InpAsiaStartHour | 0 | Asian session start (GMT) |
| InpAsiaEndHour | 7 | Asian session end (GMT) |
| InpNewsFilter | false | Avoid trading near news session opens |
| InpNewsFilterMinutes | 15 | Minutes to avoid around news |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX08002 GoldScalper_MACDScalp_TrendFollowing — MACD trend scalper with pyramiding, full 12-layer stack."
#include <Trade\Trade.mqh>
//+------------------------------------------------------------------+
//| Inputs |
//+------------------------------------------------------------------+
input group "=== Risk Management ==="
input bool UseMoneyManagement = true; // Use Dynamic Risk %
input double RiskPercent = 2.0; // Risk Percent per Trade
input double FixedLotSize = 0.01; // Fixed Lot Size (if MM false)
input group "=== MACD Settings ==="
input int MACD_Fast = 12; // MACD Fast EMA
input int MACD_Slow = 26; // MACD Slow EMA
input int MACD_Signal = 9; // MACD Signal Period
input bool UseHistogramFilter = true; // Require Histogram Confirmation
input group "=== Trade Settings ==="
input int StopLossPips = 20; // Stop Loss (pips)
input int TakeProfitPips = 40; // Take Profit (pips)
input int Slippage = 3; // Max Slippage (points)
input int InpMagicNumber = 22208002; // Magic Number (222 + Expert ID)
input string InpTradeComment = "Psgrowth.com Expert_08002"; // Trade Comment
input group "=== Trailing Stop ==="
input bool UseTrailingStop = true; // Use Trailing Stop
input int TrailingStartPips = 15; // Trailing Start (pips)
input int TrailingStepPips = 5; // Trailing Step (pips)
input group "=== Pyramiding ==="
input bool UsePyramiding = true; // Use Pyramiding
input int MaxOpenPositions = 2; // Max Open Positions
input int PyramidDistancePips= 20; // Distance between entries (pips)
input group "=== Filters ==="
input bool UseSpreadFilter = true; // Use Spread Filter
input double MaxSpreadPips = 25.0; // Max Spread (pips)
input bool UseTimeFilter = false; // Use Time Filter
input string StartTime = "08:00"; // Start Time (HH:MM)
input string EndTime = "20:00"; // End Time (HH:MM)
input bool ExitOnOppositeCross= true; // Exit on Opposite MACD Cross
input group "=== Hardening: Risk Management ==="
input int InpMaxConsecLosses = 3; // Max consecutive losses before cooldown (0=disabled)
input int InpCooldownMinutes = 30; // Cooldown minutes after consec losses (0=disabled)
input int InpMaxTradesPerDay = 50; // Maximum trades per day
input double InpMinEquityPercent = 95.0; // Stop trading if equity < this % of initial balance
input double InpDailyLossLimitPct= 3.0; // Daily loss limit (% of effective capital)
input double InpWeeklyLossLimitPct= 6.0; // Weekly loss limit (% of effective capital)
input group "=== Hardening: Capital Allocation Cap ==="
// InpCapitalCapEnabled removed — use InpCapitalCapAmount=0 to disable // Enable capital allocation cap
input double InpCapitalCapAmount = 0.0; // Cap amount ($ real money equity)
input double InpCapitalCapFloor = 50.0; // Floor ($); block entries below this
Full source code available on download
Educational purposes only. Do NOT use with real money. Test on demo accounts only.
Clear Warning: Educational Purposes Only
Clear Warning: This Expert Advisor is for educational and testing purposes only. Do NOT use it with real money. Test only on demo accounts. Trading with real money involves substantial risk of capital loss. This does not constitute investment advice.
Recommended Brokers for This EA
These EAs run on MT5 — use a regulated broker with fast execution and tight spreads
Markets.com
Exness
IC Markets
Similar Expert Advisors
View All Expert AdvisorsMore Trend Following strategy EAs from our library
Pipsgrowth EX16080 Trend
Pipsgrowth.com EX16080 EURUSDTrendFollower — triple-EMA H4 trend follower, full 12-layer stack.
Pipsgrowth EX16081 Trend
Pipsgrowth.com EX16081 GoldTrendEA — XAUUSD H4 EMA cross with Fib targets, full 12-layer stack.
Pipsgrowth EX16033 Trend
Pipsgrowth.com EX16033 EA_Price_Action — price-action grid scalper, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.