P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX08003 MACD

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX08003 TripleMACD_XAUUSD_5M — triple MACD layered trend system, full 12-layer stack.

Overview

Pipsgrowth EX08003 MACD is built around a single, specific idea: trade the zero-line crossover of a fast MACD, but only when two slower MACDs agree on the prevailing direction. The fast pair is 5/8, the medium pair is 13/21, the slow pair is 34/144 — all three computed on the working timeframe (M5 by default) with a 1-bar signal line. The triple stack is what makes this EA different from a vanilla MACD cross. A buy fires only when the 34/144 MACD is above zero, the 13/21 MACD is above zero, and the 5/8 MACD has just crossed up through zero on the most recent closed bar. A sell mirrors that condition in the negative direction. Both checks use the bar 1 vs bar 2 readout from CopyBuffer so the signal cannot repaint on the live tick.

That gating sequence is encoded in the CheckSignal() function. The fast 5/8 MACD acts as a trigger, the 13/21 acts as a medium-term trend filter, and the 34/144 acts as a long-term regime filter. The trigger alone produces a constant stream of false signals; the two filters cut the trade rate to only the moments when all three layers are aligned. The EA also blocks any new signal until a fresh bar prints — the static datetime lastBar gate inside OnTick() means the same signal is not re-evaluated dozens of times per second.

Position sizing uses a percentage-of-equity model. CalculateLotSize() divides the risk percent (default 1.0% of effective capital) by the per-lot loss at the configured stop distance, then floors the result to the broker's lot step. The minimum is the symbol's LotsMin() and the maximum is LotsMax(). When InpRiskPercent is set to 0, the EA falls back to a fixed 0.01 lot. The effective capital itself is governed by the optional capital cap: when InpCapitalCapAmount is greater than 0, the EA treats the smaller of (account equity, cap amount) as the base for risk math, so a user who funds the account with $10,000 but sets cap to $2,000 will see lot sizes that match a $2,000 book, not a $10,000 book.

The trade is opened with a fixed stop and take-profit, not a structural swing stop. Default values are SL 400 points and TP 1200 points, a 1:3 risk-reward ratio. Order construction in OpenBuy() and OpenSell() calls OrderCalcMargin first and refuses the order if free margin cannot cover the lot size, then sends a market order through the CTrade wrapper with up to 3 retry attempts 150 ms apart. The comment field is fixed to "Psgrowth.com Expert_08003". The filling mode is negotiated at init: the EA probes the symbol's SYMBOL_FILLING_MODE, prefers FOK, falls back to IOC, then RETURN. This avoids the common 10014 error you get when the strategy assumes FOK on an IOC-only broker.

The trade management layer is a pure trailing stop — there is no break-even step, no partial close, no scaling out. ManageProfitLock() iterates the position list every tick and, for each position on the magic, lifts the stop-loss to Bid − InpTrailDistance (150 pts) once the position is more than InpTrailStart (300 pts) in profit. For sells the math mirrors with Ask. The check is one-sided: the new SL must be strictly above the existing SL for a buy (below for a sell) — there is no step-size gating, so the stop ratchets every tick the moment the threshold is crossed. Note that InpTrailStep is exposed in the input panel as 100 but is not actually consumed by the trailing code, so changing it has no effect on the live behaviour.

Pyramiding is the second scaling layer. When InpEnablePyramid is true and the same-side count is below InpMaxPositions (default 3), the EA will open an additional position on a fresh M1-cross signal. The gate is in IsGridSafe(): it scans the existing same-side positions and refuses to add unless the oldest qualifying position is at least InpMinProfitPoints (300 pts) in profit. That means the EA can stack up to three longs in a confirmed uptrend, but it will not blind-add to a losing leg. There is no martingale, no lot multiplier, no anti-martingale — every layer is sized independently through the same 1%-risk formula.

The hardening stack is unusually heavy for a single-symbol M5 EA. IsSafeToTrade() rejects new entries when: equity is below 95% of the original starting balance, the realised loss for the day exceeds 3% of effective capital, the realised loss for the week exceeds 6%, three consecutive losses have triggered a 30-minute cooldown, the trade counter for the day has hit 50, the broker server is in the weekend gap (closed from Friday 22:00 GMT through Sunday 22:00 GMT), the current GMT time is outside the active session windows, or the news filter is enabled and a session open is within InpNewsFilterMinutes (15). Session windows are London 7–16 GMT, New York 12–21 GMT, and Asian 0–7 GMT. The Asia block is on by default; the EA trades only when the time is inside London or New York, and it does not trade the Asian session by itself. GMT offset is auto-detected at init by DetectGMTOffset(): it scans H1 bars looking for the weekend gap, then computes the offset from the prior bar's hour. If the user knows the broker clock, InpServerGMTOffset overrides the auto-detect.

A practical note on the InpNewsFilter input: it ships disabled. The 15-minute buffer around the London open (07:00 GMT) and the New York open (12:00 GMT) is a low-cost toggle for traders who do not want to be in a fresh position into the NFP / CPI print. The default-off state reflects the EA's design assumption that the trend filter (34/144 MACD above zero) already absorbs most event-driven noise.

The optimiser fitness function in OnTester() is the standard Pipsgrowth composite: (net * profit_factor) / (1 + balance_dd_percent), with a hard minimum of 30 trades. This is a long-form trend-fitness metric: it rewards raw profit, weights it by profit factor (so high-win-rate low-payoff curves lose to a few large winners), and divides by drawdown to penalise wide equity swings. In a Strategy Tester pass on XAUUSD M5, expect a relatively low trade count (the triple-MACD filter is strict) with comparatively large average win size, because the EA only enters when all three MACD layers are aligned. The 1:3 fixed TP and the 150-point chandelier-style trail mean each trade has a generous upside but the EA will still take the full 1:3 payout whenever price reaches the TP before the trailing stop catches it.

For live use, the realistic deployment is XAUUSD on M5, on an ECN or raw-spread broker, with a $100 minimum balance (per the database field) — though a $300–$500 buffer is more honest because the 1% risk on $100 means a 400-point stop is roughly 0.01 lots, which is the floor on most gold accounts. The capital cap input makes this EA well suited to prop-firm style scaling: a trader who wants to risk only $1,000 of a $20,000 account can set InpCapitalCapAmount = 1000 and the lot sizes will compute against that $1,000 ceiling, not the full account. The 95% equity floor, the 3%/6% loss caps, and the 3-consecutive-loss cooldown work together as a drawdown firewall that should keep the EA from bleeding the account through a regime shift that the slow MACD has not yet adapted to.

Strategy Deep Dive

Three MACD indicators on the M5 chart stack into a layered trend filter. The fast 5/8 MACD fires the zero-line crossover as a trigger; the medium 13/21 and slow 34/144 MACDs gate the trigger by requiring both to sit on the same side of zero. The combined condition collapses most chop into silence and only releases a signal when all three layers agree on direction. Pyramiding is same-direction only, capped at 3 positions, and each new leg requires the oldest same-side position to be in at least 300 points of profit. Trade management is a pure trailing stop — no break-even, no partial close, no basket TP. The hardening stack rejects new entries on weekends, outside the London/NY windows, after 3 consecutive losses (30-min cooldown), when equity dips below 95% of starting balance, when daily loss exceeds 3% or weekly loss exceeds 6%, or when the spread is above 250 points.

Entry Signal

Buy when MACD 34/144 > 0 AND MACD 13/21 > 0 AND MACD 5/8 crosses above zero on the most recent closed bar (bar 1 was ≤ 0, bar 2 > 0). Sell mirrors the same triple condition in the negative direction. The CheckSignal() function reads bar 1 and bar 2 of the fast MACD buffer to avoid repaint on the live tick, and a static lastBar gate ensures the same signal is only evaluated once per fresh bar.

Exit Signal

Exit by either hitting the fixed 1200-point take-profit or by the trailing stop catching the trade after InpTrailStart (300 pts) of profit. The trailing logic in ManageProfitLock() lifts the stop to Bid − InpTrailDistance (150 pts) on every tick once the threshold is crossed, so the stop ratchets continuously rather than in discrete steps. The signal engine does not auto-close on a reverse crossover — the position is held until TP or the trail.

Stop Loss

Initial stop is fixed at 400 points (InpStopLoss) on every entry — a static-distance stop, not a swing-based structural stop. Once the trade is in profit beyond 300 points, ManageProfitLock() ratchets the stop to Bid − 150 pts (Ask + 150 for shorts) and continues to lift it on every tick. InpTrailStep is exposed in the input panel but is not actually consumed by the trailing code, so the live trail tracks every tick rather than in 100-pt increments.

Take Profit

Fixed take-profit of 1200 points (InpTakeProfit) on every entry, a 1:3 risk-to-reward ratio against the 400-point stop. The TP is set at order open, so each position has a hard pre-defined exit ceiling. Pyramiding legs carry the same fixed TP ratio as the first entry — there is no trailing-based or basket-based TP fallback.

Best For

Deploy on XAUUSD M5 on an ECN or raw-spread broker with a recommended minimum balance of $100 (a $300–$500 buffer is more honest at the 1% risk / 400-point stop default). The London and New York session gates mean the EA is built for the London open (07:00–09:00 GMT) and the New York open (12:00–14:00 GMT) overlap windows; Asian-session XAUUSD range will not generate signals. The capital-cap input makes it well suited to prop-firm-style accounts where you want to size positions off a sub-portion of the funded balance. Risk level: MEDIUM. Magic number 22208003.

Strategy Logic

Pipsgrowth EX08003 MACD — Strategy Logic Analysis (from .mq5 source)

Family: MACD Magic: 22208003 Version: 2.00

BRIEF: Triple MACD EA using three timeframe-aligned MACD indicators (fast/medium/slow) for layered trend confirmation with pyramiding, trailing stop, profit lock, and spread filter across a 12-layer architecture. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • CheckSignal()
  • OpenBuy()
  • OpenSell()
  • ManageProfitLock()
  • IsGridSafe()
  • CalculateLotSize()
  • CountPositions()
  • GetEffectiveCapital()
  • OnTradeTransaction()
  • DetectGMTOffset()
  • ServerToGMT()
  • IsMarketOpen()
  • ...and 7 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (39 total across 8 groups):

  • [=== Indicator Settings ===] InpM1Fast = 5 // M1 Fast
  • [=== Indicator Settings ===] InpM1Slow = 8 // M1 Slow
  • [=== Indicator Settings ===] InpM2Fast = 13 // M2 Fast
  • [=== Indicator Settings ===] InpM2Slow = 21 // M2 Slow
  • [=== Indicator Settings ===] InpM3Fast = 34 // M3 Fast
  • [=== Indicator Settings ===] InpM3Slow = 144 // M3 Slow
  • [=== Money Management ===] InpRiskPercent = 1.0 // Risk Percent per Trade
  • [=== Money Management ===] InpFixedLot = 0.01 // Fixed Lot (if Risk=0)
  • [=== Money Management ===] InpStopLoss = 400 // Stop Loss (points)
  • [=== Money Management ===] InpTakeProfit = 1200 // Take Profit (points)
  • [=== Trade Management ===] InpMagicNumber = 22208003 // Magic Number (222 + Expert ID)
  • [=== Trade Management ===] InpTradeComment = "Psgrowth.com Expert_08003" // Trade Comment
  • [=== Trade Management ===] InpMaxSpread = 250 // Max Spread (points)
  • [=== Trade Management ===] InpSlippage = 3 // Slippage
  • [=== Profit Lock / Trailing ===] InpEnableTrail = true // Enable Trailing Stop
  • [=== Profit Lock / Trailing ===] InpTrailStart = 300 // Trail Start Distance (points)
  • [=== Profit Lock / Trailing ===] InpTrailStep = 100 // Trail Step (points)
  • [=== Profit Lock / Trailing ===] InpTrailDistance = 150 // Distance behind price (points)
  • [=== Pyramiding / Scaling ===] InpEnablePyramid = true // Enable Pyramiding
  • [=== Pyramiding / Scaling ===] InpMaxPositions = 3 // Max Open Positions
  • [=== Pyramiding / Scaling ===] InpMinProfitPoints = 300 // Min Profit (points) to Add Next
  • [=== 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: GMT Sessions ===] InpServerGMTOffset = 0 // Server GMT offset hours (0=auto-detect)
  • [=== Hardening: GMT Sessions ===] InpLondonStartHour = 7 // London session start (GMT)
  • [=== Hardening: GMT Sessions ===] InpLondonEndHour = 16 // London session end (GMT)
  • [=== Hardening: GMT Sessions ===] InpNYStartHour = 12 // New York session start (GMT)
  • [=== Hardening: GMT Sessions ===] InpNYEndHour = 21 // New York session end (GMT)
  • [=== Hardening: GMT Sessions ===] InpAvoidAsia = true // Avoid Asian session
  • [=== Hardening: GMT Sessions ===] InpAsiaStartHour = 0 // Asian session start (GMT)
  • [=== Hardening: GMT Sessions ===] InpAsiaEndHour = 7 // Asian session end (GMT)
  • [=== Hardening: GMT Sessions ===] InpNewsFilter = false // Avoid trading near news session opens
  • [=== Hardening: GMT Sessions ===] InpNewsFilterMinutes = 15 // Minutes to avoid around news
Pseudocode
// Pipsgrowth EX08003 MACD — Execution Flow (from source analysis)
// Family: MACD
// Triple MACD EA using three timeframe-aligned MACD indicators (fast/medium/slow) for layered trend confirmation with pyramiding, trailing stop, profit lock, and spread filter 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

Optimized Brokers:
ExnessIC Markets
Optimized Symbols:
XAUUSD
Optimized Timeframes:
M5

How to Install This EA on MT5

  1. 1Download the .mq5 file using the button above
  2. 2Open MetaTrader 5 on your computer
  3. 3Click File → Open Data Folder in the top menu
  4. 4Navigate to MQL5 → Experts and paste the .mq5 file there
  5. 5In MT5, right-click Expert Advisors in the Navigator panel → Refresh
  6. 6Drag the EA onto an H4 or Daily chart for best results
  7. 7Configure EMA periods, ADX threshold, and lot size in the dialog
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
InpM1Fast5M1 Fast
InpM1Slow8M1 Slow
InpM2Fast13M2 Fast
InpM2Slow21M2 Slow
InpM3Fast34M3 Fast
InpM3Slow144M3 Slow
InpRiskPercent1.0Risk Percent per Trade
InpFixedLot0.01Fixed Lot (if Risk=0)
InpStopLoss400Stop Loss (points)
InpTakeProfit1200Take Profit (points)
InpMagicNumber22208003Magic Number (222 + Expert ID)
InpTradeComment"Psgrowth.com Expert_08003"Trade Comment
InpMaxSpread250Max Spread (points)
InpSlippage3Slippage
InpEnableTrailtrueEnable Trailing Stop
InpTrailStart300Trail Start Distance (points)
InpTrailStep100Trail Step (points)
InpTrailDistance150Distance behind price (points)
InpEnablePyramidtrueEnable Pyramiding
InpMaxPositions3Max Open Positions
InpMinProfitPoints300Min Profit (points) to Add Next
InpMaxConsecLosses3Max consecutive losses before cooldown (0=disabled)
InpCooldownMinutes30Cooldown minutes after consec losses (0=disabled)
InpMaxTradesPerDay50Maximum trades per day
InpMinEquityPercent95.0Stop trading if equity < this % of initial balance
InpDailyLossLimitPct3.0Daily loss limit (% of effective capital)
InpWeeklyLossLimitPct6.0Weekly loss limit (% of effective capital)
InpCapitalCapAmount0.0Cap amount ($ real money equity)
InpCapitalCapFloor50.0Floor ($); block entries below this
InpServerGMTOffset0Server GMT offset hours (0=auto-detect)
InpLondonStartHour7London session start (GMT)
InpLondonEndHour16London session end (GMT)
InpNYStartHour12New York session start (GMT)
InpNYEndHour21New York session end (GMT)
InpAvoidAsiatrueAvoid Asian session
InpAsiaStartHour0Asian session start (GMT)
InpAsiaEndHour7Asian session end (GMT)
InpNewsFilterfalseAvoid trading near news session opens
InpNewsFilterMinutes15Minutes to avoid around news
Source Code (.mq5)Open Source
Pipsgrowth_com_EX08003.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX08003 TripleMACD_XAUUSD_5M — triple MACD layered trend system, full 12-layer stack."

#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>

CTrade         trade;
CPositionInfo  position;
CSymbolInfo    mysymbol;
CAccountInfo   account;

//--- Input Groups
input group "=== Indicator Settings ==="
input int      InpM1Fast         = 5;        // M1 Fast
input int      InpM1Slow         = 8;        // M1 Slow
input int      InpM2Fast         = 13;       // M2 Fast
input int      InpM2Slow         = 21;       // M2 Slow
input int      InpM3Fast         = 34;       // M3 Fast
input int      InpM3Slow         = 144;      // M3 Slow

input group "=== Money Management ==="
input double   InpRiskPercent    = 1.0;      // Risk Percent per Trade
input double   InpFixedLot       = 0.01;     // Fixed Lot (if Risk=0)
input int      InpStopLoss       = 400;      // Stop Loss (points)
input int      InpTakeProfit     = 1200;     // Take Profit (points)

input group "=== Trade Management ==="
input int      InpMagicNumber    = 22208003;                     // Magic Number (222 + Expert ID)
input string   InpTradeComment   = "Psgrowth.com Expert_08003"; // Trade Comment
input int      InpMaxSpread      = 250;      // Max Spread (points)
input int      InpSlippage       = 3;        // Slippage

input group "=== Profit Lock / Trailing ==="
input bool     InpEnableTrail    = true;     // Enable Trailing Stop
input int      InpTrailStart     = 300;      // Trail Start Distance (points)
input int      InpTrailStep      = 100;      // Trail Step (points)
input int      InpTrailDistance  = 150;      // Distance behind price (points)

input group "=== Pyramiding / Scaling ==="
input bool     InpEnablePyramid  = true;     // Enable Pyramiding
input int      InpMaxPositions   = 3;        // Max Open Positions
input int      InpMinProfitPoints= 300;      // Min Profit (points) to Add Next

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.

Tags:ex08003macdpipsgrowthfreemt5xauusd

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

Community

Sign in to contributeSign In

Educational purposes only. Do NOT use with real money. Test on demo accounts only.

File NamePipsgrowth_com_EX08003.mq5
File Size21.8 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M5
Currency Pairs
XAUUSD
Min. Deposit$100