Pipsgrowth EX01005 Adaptive
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX01005 AdaptiveGoldPyramid — EMA crossover with ADX filter and ATR pyramiding, configurable timeframe, filling mode detection, spread filter, full 12-layer stack.
Overview
Pipsgrowth EX01005 Adaptive is a pyramid-style trend follower engineered for XAUUSD on the M5 timeframe, though the source ships with a multi-timeframe selector (InpTimeframe 1=M1 through 9=D1) so the same logic can be re-targeted at H1 or M15 without recompilation. The system is built around three indicator handles — a fast EMA(20), a slow EMA(50), an ADX(14) read at threshold 25, and an ATR(14) that drives every distance-based decision in the file. The trade gate is a directional EMA crossover confirmed by a minimum ADX reading, which is the part of the strategy that filters out chop: the EA refuses to engage unless the Average Directional Index is at or above 25 on the previous closed bar, a level that historically separates trending gold sessions from the sideways noise that dominates Asian hours. The pyramid element is what makes the strategy distinctive. When CheckEntryConditions() finds a fresh long or short setup and there are no open positions in that direction, it opens a single trade sized by either InpLotSize (default 0.01) or the risk-percent path. If price then advances an additional 1.0 × ATR from the most recent entry in the same direction, the EA adds a second position. Each new layer triggers MovePreviousTradesToBreakEven(), which walks through every open position in that direction and ratchets its stop loss up to the original open price, locking in a scratch-or-better exit for prior layers before the next leg of the pyramid begins. The default InpMaxLayers is 3, so a sustained trend can accumulate up to three same-direction positions, each separated by one ATR of price progress. The TryModify() function handles the actual SL modifications with three-attempt retry logic and a guard against invalid-stops errors that some brokers throw when a stop is closer than the symbol's minimum stop level. Risk management is layered well beyond the trade level. IsSafeToTrade() runs at the top of every OnTick and refuses to engage if any of the following is true: capital cap reached (InpCapAmount, disabled by default at 0), capital floor breached (InpCapFloor=100), equity fallen below 80% of the initial balance (MinEquityPercent=80), daily loss exceeding 3% of initial balance (MaxDailyLossPercent=3.0), weekly loss exceeding 8% (InpMaxWeeklyLossPct=8.0), three consecutive losing trades within an unexpired 30-minute cooldown (InpMaxConsecLosses=3, InpCooldownMin=30), ten trades already taken today (MaxTradesPerDay=10), weekend market closure detected by IsMarketOpen() which compares the server time against the standard 22:00 GMT Friday to 22:00 GMT Sunday window, the current GMT hour outside the active session window, a news-time overlap with London or New York opens, the manual kill switch flipped on, or total drawdown against the initial balance exceeding 20% (InpMaxDDPct=20.0). That last check is the catastrophic fail-safe — once triggered, the EA prints a KILL SWITCH: total DD= line and halts all trading until the user intervenes. The session logic uses ServerToGMT() and the InpServerGMTOffset input, which can either be hard-set to the broker's GMT offset or auto-detected by DetectGMTOffset() scanning the hourly bars for the weekend gap and computing the offset from the 22:00 anchor. The default windows are London 7-16 GMT and New York 12-21 GMT, with InpAvoidAsia=true and the Asian block defined as 0-7 GMT. The InActiveSession() function returns true if the current GMT minute falls inside either London or New York, with the Asian window only blocking when both London and New York are closed — so a Gold spike during early NY that bleeds into 21:30 GMT still counts as in-session. News avoidance is conservative: IsNewsTime() returns true whenever the current GMT minute is within 30 minutes of either the London open (default 7:00) or the New York open (default 12:00), so the EA stays flat through the typical NFP, CPI, and FOMC release windows. Lot sizing has two paths. When InpRiskPercent is greater than zero (default 1.0), CalculateLotSize() divides the risk amount (effective capital × 1%) by the SL distance in points × the symbol's tick value, producing a lot size that scales with both account growth and the ATR-derived stop. When InpRiskPercent is zero, the EA falls back to the fixed InpLotSize=0.01. Both paths route through NormalizeLot(), which floors the lot to the symbol's volume step and clamps to the symbol min/max and the hard InpMaxLot=100 cap. The effective capital itself is mutated by EffectiveCapital() — if InpCapAmount is set, equity is capped at that level for sizing, which is useful for traders who want to size positions as if they had less than they actually do, leaving a buffer for adding layers later. Exits work in two ways. The first is the opposite-signal exit in UpdatePositionManagement(): if the EA holds a long position and the fast EMA is now below the slow EMA on the closed bar, the position is closed via TryClosePosition() with three retry attempts. The second is the trailing stop, which is recomputed every tick at a distance of InpTrail_ATR_Multiplier (default 1.5 × ATR) from the current bid for longs or current ask for shorts. The trailing logic only ratchets in the profitable direction and only tightens the stop — it never loosens it, so a 1.5 ATR trailing stop on Gold at $2,400 with a 200-point ATR sits roughly $30 behind price and locks in any further move. There is no fixed take-profit; positions are expected to run until either the opposite-signal close, the trailing stop, or the per-trade stop loss fires. OnTester() exposes a custom optimization criterion that multiplies profit by a clamped profit factor (capped at 10) and divides by a drawdown penalty, returning zero if drawdown exceeds InpMaxDDPct, fewer than 20 trades were taken, or the period was net-unprofitable — this gives the MetaTrader optimizer a strong signal to find parameter sets with both profitability and contained risk rather than raw return. Practical deployment notes: the EA defaults to XAUUSD M5 with a $100 minimum, but the pyramid of up to three positions at 1% risk each means a more realistic balance for a single-symbol deployment is $300 to give each layer its stop room without tripping the 80% equity floor. The InpMaxSpread filter defaults to 50 points (0.5 USD on a 5-digit gold feed) and is the single most common reason this EA skips a session — brokers with weekend gold spreads wider than that should be avoided. InpDryRun=true is the recommended first run: it logs the BUY/SELL signal line to the journal without sending any order, which is the fastest way to confirm the EA is reading bars and the session window correctly on a new broker before committing capital. The recommended session is the London and New York overlap from 12:00 to 16:00 GMT, where both InpLondonStartHour and InpNYStartHour windows are open and gold liquidity is deepest; the Asian session is excluded by default but can be re-enabled by setting InpAvoidAsia=false, which is generally not advisable on M5 gold because of the lower-volume, wider-spread conditions that dominate the 0-7 GMT window.
Strategy Deep Dive
On each new M5 bar, the EA refreshes four indicator handles — fast EMA(20), slow EMA(50), ADX(14), ATR(14) — on the closed bar at shift 1, then CheckEntryConditions() rejects the bar immediately if ADX is below 25. If fastEMA > slowEMA and the long count is under InpMaxLayers, it opens a long at ask with SL = ask − 1.5 × ATR; on subsequent bars the same direction's most recent entry is read by GetLastEntryPrice() and a new layer fires only when ask exceeds that price by 1.0 × ATR, with MovePreviousTradesToBreakEven() called first to lock prior layers at breakeven. UpdatePositionManagement() runs on every tick to handle two exit paths: it closes the position if the EMAs flip against it, or ratchets the trailing stop to bid − 1.5 × ATR for longs (and the ask-side mirror for shorts), only tightening, never loosening. IsSafeToTrade() sits at the top of every tick and gates the entire EA on capital cap/floor, equity-floor at 80% of initial balance, daily loss 3%, weekly loss 8%, three-loss cooldown of 30 minutes, ten trades per day cap, market-open check via the GMT weekend guard, session window via InActiveSession() (London 7-16, NY 12-21, Asia avoided by default), and a 30-minute news buffer around London and New York opens, with the 20% total-DD kill switch as the catastrophic fallback that halts everything.
A long entry fires when the fast EMA(20) crosses above the slow EMA(50) on the closed bar with the ADX(14) reading at or above 25, opening the first position sized by either 1% account risk or the fixed 0.01 lot. Each additional pyramid layer triggers when price advances another 1.0 × ATR(14) above the last entry in the same direction, up to the InpMaxLayers=3 cap, and the prior trade's stop is moved to break-even before the new layer is placed.
Positions close on the opposite EMA crossover signal — a long is closed when the fast EMA drops below the slow EMA, and a short is closed when it rises above. There is no fixed take-profit; the trailing stop, recomputed every tick at 1.5 × ATR(14), ratchets only in the profitable direction and never loosens.
Each trade opens with a stop loss placed at 1.5 × ATR(14) from the entry price, normalized to the symbol's digits and the broker's minimum stop level. When a new pyramid layer opens in the same direction, MovePreviousTradesToBreakEven() walks through all prior positions in that direction and ratchets their stop up to the original open price before the new leg is placed.
No fixed take-profit is set on entry — TP is left at 0 and the trailing stop at 1.5 × ATR(14) is the only profit-taking mechanism. The intent is to let the EA ride sustained trends until the opposite EMA crossover forces a close, which is consistent with the pyramid structure of stacking up to three positions in a move.
Run on XAUUSD M5 (the default InpTimeframe=3 mapping) with a realistic balance of $300 to absorb a three-layer pyramid of 1%-risk positions, since the documented $100 minimum only covers a single layer. Recommended session is the London and New York overlap from 12:00 to 16:00 GMT, where both InpLondonStartHour and InpNYStartHour windows are open and gold liquidity is at its deepest; the Asian session is blocked by default via InpAvoidAsia=true. Use an ECN or low-spread broker where typical XAUUSD spreads stay under 50 points (0.5 USD on 5-digit quotes) to avoid constant InpMaxSpread rejections, and start with InpDryRun=true on a demo to verify the session and GMT detection work correctly before going live.
Strategy Logic
Pipsgrowth EX01005 Adaptive — Strategy Logic Analysis (from .mq5 source)
Family: Adaptive
Magic: 22201005
Version: 3.00
BRIEF:
Adaptive gold pyramid EA using EMA crossover with ADX trend filter and ATR-based pyramiding — adds positions in trend direction at ATR intervals, moves prior trades to BE. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
IsNewBar()IsSpreadOK()RefreshIndicatorBuffers()CheckEntryConditions()OpenBuyTrade()OpenSellTrade()CountPositions()GetLastEntryPrice()MovePreviousTradesToBreakEven()TryModify()TryClosePosition()UpdatePositionManagement()- ...and 13 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (24 total across 6 groups):
- [=== Identity ===]
InpTimeframe= 3 // Timeframe: 1=M1,2=M3,3=M5,4=M10,5=M15,6=M30,7=H1,8=H4,9=D1 - [=== Identity ===]
InpMaxSpread= 50 // Max spread in points (0=disabled) - [=== Sizing ===]
InpRiskPercent=1.0// Risk % per trade (0=use fixedInpLotSize) - [=== Risk Management ===]
MaxDailyLossPercent=3.0// Maximum daily loss percentage - [=== Risk Management ===]
MaxTradesPerDay= 10 // Maximum trades per day - [=== Risk Management ===]
MinEquityPercent=80.0// Stop trading if equity falls below this % of initial balance - [=== Risk Management ===]
InpMaxConsecLosses= 3 // Max consecutive losses before cooldown (0=disabled) - [=== Risk Management ===]
InpCooldownMin= 30 // Cooldown minutes after consec losses (0=disabled) - [=== Risk Management ===]
InpMaxWeeklyLossPct=8.0// Max weekly loss % (0=disabled) - [=== Capital Cap ===]
InpCapAmount=0.0// Capital cap amount (stop trading at this equity) - [=== Capital Cap ===]
InpCapFloor=100.0// Capital floor (stop trading below this equity) - [=== Sessions
Management(GMT) ===]InpServerGMTOffset= 0 // ServerGMToffset in hours (0=auto-detect via weekend gap) - [=== Sessions
Management(GMT) ===]InpLondonStartHour= 7 // London session start (GMT) - [=== Sessions
Management(GMT) ===]InpLondonEndHour= 16 // London session end (GMT) - [=== Sessions
Management(GMT) ===]InpNYStartHour= 12 // New York session start (GMT) - [=== Sessions
Management(GMT) ===]InpNYEndHour= 21 // New York session end (GMT) - [=== Sessions
Management(GMT) ===]InpAvoidAsia=true// Avoid Asian session - [=== Sessions
Management(GMT) ===]InpAsiaStartHour= 0 // Asian session start (GMT) - [=== Sessions
Management(GMT) ===]InpAsiaEndHour= 7 // Asian session end (GMT) - [=== Sessions
Management(GMT) ===]AvoidNews=true// Avoid trading during news - [=== Safety Caps ===]
InpMaxDDPct=20.0// Max total drawdown % (0=disabled, triggers kill switch) - [=== Safety Caps ===]
InpKillSwitch=false// Kill switch (stops all trading immediately) - [=== Safety Caps ===]
InpDryRun=false// Dry-run mode: log signals without trading - [=== Safety Caps ===]
InpMaxLot=100.0// Maximum lot size cap
// Pipsgrowth EX01005 Adaptive — Execution Flow (from source analysis)
// Family: Adaptive
// Adaptive gold pyramid EA using EMA crossover with ADX trend filter and ATR-based pyramiding — adds positions in trend direction at ATR intervals, moves prior trades to BE. 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 a chart matching the recommended timeframe
- 7Configure parameters according to the table on this page
- 8Enable Allow Algo Trading and click OK
EA Parameters
| Parameter | Default | Description |
|---|---|---|
| InpTimeframe | 3 | Timeframe: 1=M1,2=M3,3=M5,4=M10,5=M15,6=M30,7=H1,8=H4,9=D1 |
| InpMaxSpread | 50 | Max spread in points (0=disabled) |
| InpRiskPercent | 1.0 | Risk % per trade (0=use fixed InpLotSize) |
| MaxDailyLossPercent | 3.0 | Maximum daily loss percentage |
| MaxTradesPerDay | 10 | Maximum trades per day |
| MinEquityPercent | 80.0 | Stop trading if equity falls below this % of initial balance |
| InpMaxConsecLosses | 3 | Max consecutive losses before cooldown (0=disabled) |
| InpCooldownMin | 30 | Cooldown minutes after consec losses (0=disabled) |
| InpMaxWeeklyLossPct | 8.0 | Max weekly loss % (0=disabled) |
| InpCapAmount | 0.0 | Capital cap amount (stop trading at this equity) |
| InpCapFloor | 100.0 | Capital floor (stop trading below this equity) |
| InpServerGMTOffset | 0 | Server GMT offset in hours (0=auto-detect via weekend gap) |
| 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) |
| AvoidNews | true | Avoid trading during news |
| InpMaxDDPct | 20.0 | Max total drawdown % (0=disabled, triggers kill switch) |
| InpKillSwitch | false | Kill switch (stops all trading immediately) |
| InpDryRun | false | Dry-run mode: log signals without trading |
| InpMaxLot | 100.0 | Maximum lot size cap |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "3.00"
#property strict
#property description "Pipsgrowth.com EX01005 AdaptiveGoldPyramid — EMA crossover with ADX filter and ATR pyramiding, configurable timeframe, filling mode detection, spread filter, full 12-layer stack."
#include <Trade\Trade.mqh>
//--- Timeframe mapping: 1=M1, 2=M3, 3=M5, 4=M10, 5=M15, 6=M30, 7=H1, 8=H4, 9=D1
ENUM_TIMEFRAMES MapTimeframe(int tf)
{
switch(tf)
{
case 1: return PERIOD_M1;
case 2: return PERIOD_M3;
case 3: return PERIOD_M5;
case 4: return PERIOD_M10;
case 5: return PERIOD_M15;
case 6: return PERIOD_M30;
case 7: return PERIOD_H1;
case 8: return PERIOD_H4;
case 9: return PERIOD_D1;
default: return PERIOD_M5;
}
}
//+------------------------------------------------------------------+
//| Input Parameters |
//+------------------------------------------------------------------+
input group "=== Identity ==="
input ulong InpMagicNumber = 22201005;
input string InpTradeComment = "Psgrowth.com Expert_01005";
input int InpTimeframe = 3; // Timeframe: 1=M1,2=M3,3=M5,4=M10,5=M15,6=M30,7=H1,8=H4,9=D1
input int InpMaxSpread = 50; // Max spread in points (0=disabled)
input group "=== Sizing ==="
input double InpLotSize = 0.01;
input int InpMaxLayers = 3;
input double InpRiskPercent = 1.0; // Risk % per trade (0=use fixed InpLotSize)
input group "=== Signal ==="
input int InpFastEMAPeriod = 20;
input int InpSlowEMAPeriod = 50;
input group "=== Confirm ==="
input int InpADXPeriod = 14;
input int InpADXLevel = 25;
input group "=== Exit ==="
input int InpATRPeriod = 14;
input double InpSL_ATR_Multiplier = 1.5;
input double InpStep_ATR_Multiplier = 1.0;
input double InpTrail_ATR_Multiplier = 1.5;
input group "=== Risk Management ==="
input double MaxDailyLossPercent = 3.0; // Maximum daily loss percentage
input int MaxTradesPerDay = 10; // Maximum trades per day
input double MinEquityPercent = 80.0; // Stop trading if equity falls below this % of initial balance
input int InpMaxConsecLosses = 3; // Max consecutive losses before cooldown (0=disabled)
input int InpCooldownMin = 30; // Cooldown minutes after consec losses (0=disabled)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 Other strategy EAs from our library
Pipsgrowth EX01007 Adaptive
Pipsgrowth.com EX01007 Adaptive XAUUSD 5M — multi-indicator signal scorer with regime filter, full 12-layer stack, configurable timeframe, trailing/BE/profit-lock toggles, pyramid gate, spread filter, new-bar gate, filling mode detection.
Pipsgrowth EX01019 Adaptive
Pipsgrowth.com EX01019 Self-Adaptive Market EA Fixed — multi-regime adaptive EA, full 12-layer stack.
Pipsgrowth EX15029 SMC-OrderBlock
Pipsgrowth.com EX15029 SMCBreakoutEA — SMC breakout CHOCH/liquidity sweep EA, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.