Pipsgrowth EX09022 MeanReversion
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX09022 Mean Reverse — MA crossover with ATR mean-reversion bands, full 12-layer stack.
Overview
EX09022 is built around a deliberately small idea: pull a fast simple moving average and a slow simple moving average off the same close-price series, draw an ATR-sized band around the slow average, and let either of two independent conditions open a trade. The first condition is a classic fast-over-slow crossover. The second is a mean-reversion trigger that fires when price has wandered more than a fixed ATR multiple away from the slow MA. Both feed into the same buy and sell booleans through an OR, so the EA treats crossover and reversion as equivalent triggers rather than competing systems. This is unusual inside the EX09 family: most of its siblings pick one direction (pure trend, pure reversion, or an explicit regime switch). EX09022 simply merges the two into a single entry model and lets the next bar decide which one fired.
The indicator stack is three handles and nothing else. A 20-period SMA on close, a 50-period SMA on close, and a 14-period ATR. There is no RSI, no Bollinger band, no ADX, no KAMA, no Donchian. The two MAs are the same iMA(_Symbol, PERIOD_CURRENT, N, 0, MODE_SMA, PRICE_CLOSE) call with the period swapped, which means the EA relies on the same averaging method and the same applied price for both lines and never mixes an EMA into a SMA pair. The ATR uses default iATR(_Symbol, PERIOD_CURRENT, 14) and is the only volatility input the strategy actually consumes. Everything else — the multiplier, the SL/TP distances, the lot size — is a fixed input. The header advertises 12 layers (REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester), but in practice only SIGNAL, ENTRY, NO-TRADE, CAPITAL CAP, RISK, SIZING, EXIT and OnTester carry code. There is no regime classifier, no confirmation stage, no in-trade management (no trailing stop, no break-even, no partial close), and no scaling layer. Calling it a 12-layer stack is aspirational; it is closer to an 8-layer stack with four empty seats.
Signal construction lives in OnTick(). The function pulls three bars of the fast MA, three bars of the slow MA, and two bars of the ATR with CopyBuffer. A trend buy fires when prev_fast_ma <= prev_slow_ma && current_fast_ma > current_slow_ma; a trend sell is the exact mirror. A reversion buy fires when current_price < current_slow_ma - current_atr * ATR_Multiplier; a reversion sell fires when current_price > current_slow_ma + current_atr * ATR_Multiplier. The default ATR_Multiplier = 2.0 means price must extend two full ATR(14) units away from the slow MA before the reversion arm wakes up, which on a 5-minute XAUUSD chart with a 14-bar ATR of around 200-300 points translates to roughly $20-$30 of one-sided extension. The two booleans are merged as buy_signal = trend_buy_signal || reversion_buy_signal and the same for sell, so a single bar can in theory satisfy both arms at once. The position gate is simple: has_open_positions iterates PositionsTotal() looking for any position on _Symbol with the EA's magic, and the trade block is skipped entirely while one is open. No averaging-in, no grid, no pyramid - EX09022 is a one-position-per-symbol EA on the live side.
Order construction goes through a CTradeValidator class rather than a raw OrderSend. The class reads SYMBOL_VOLUME_MIN/MAX/STEP, SYMBOL_POINT, SYMBOL_DIGITS, and SYMBOL_TRADE_STOPS_LEVEL on init, normalizes the requested LotSize = 0.1 input to the broker's step, and checks free margin against OrderCalcMargin with a 15% buffer. If margin is insufficient the class steps the lot down by 25% repeatedly until it either finds a workable volume or hits the broker's minimum and returns 0. SL and TP are first computed as entry_price ± SL_Points/TP_Points * GetPoint() and then re-validated by ValidateStopLoss and ValidateTakeProfit against the symbol's stops-level, with a 20% additional safety buffer on top of whatever the broker reports. The defaults are SL_Points = 500 and TP_Points = 1000, which on XAUUSD with a 0.01 point is $5 of stop and $10 of target, a clean 1:2 R:R. If the broker refuses the requested level the validator slides the SL or TP to the closest valid price rather than failing the trade, which is why some live fills show stops tighter than 500 points when a broker sets a high stops-level.
Retry is double-layered. The outer ExecuteTrade function loops three times, refreshing the price from the validator between attempts and sleeping 100 ms between attempts. The inner TryOrderSend_EX09022 also loops three times and sleeps 200 ms, but only on the four transient retcodes (REQUOTE, TIMEOUT, PRICE_OFF, PRICE_CHANGED); on any other failure it breaks immediately. The two layers combined mean a real trade can absorb up to nine send attempts before the EA gives up, with delays of 100/200/200/200/100/200/200/200 ms between them. The deviation is hardcoded at 10 points; there is no input for it. A separate safety-trade routine fires once at the start of any tester run with magic 999999 to confirm the broker path works before the EA starts logging its own trades.
Risk management is wrapped in IsSafeToTrade_EX09022 and is an 8-condition AND. The conditions, in order, are: capital cap (InpCapAmount reached, stop), capital floor (InpCapFloor = 50 below the equity, stop), initial-equity floor (95% of the balance at init, stop), daily loss limit (3% of effective capital, stop), consecutive-loss cooldown (3 losses in a row triggers a 30-minute pause via g_cooldownUntil), max trades per day (50), market-open (no Saturday, no Sunday before 22 GMT, no Friday after 21 GMT), and an active session (London 7-16 GMT or New York 12-21 GMT, with an optional Asia-avoid 0-7 GMT block). An optional InpNewsFilter adds a ±15-minute time-based blackout around the London and NY open hours - the time is checked against the schedule, not against an MQL5 news feed, so it is a proxy filter, not a real economic-calendar filter. The OnTradeTransaction handler keeps the daily counters honest: it listens for TRADE_TRANSACTION_DEAL_ADD events, ignores anything whose magic does not match, sums profit+swap+commission into g_realizedToday, and increments g_consecLosses on a loss or resets it on a win.
The OnTester formula is the EX09 family default: n * p / (1 + d), where n is net profit, p is profit factor, and d is relative equity drawdown percent. The function returns 0 if there are fewer than 30 trades or if either p or d is non-positive, so single-digit-trade optimizations get discarded automatically. The cap layer (InpCapAmount/InpCapFloor) is genuinely optional - setting InpCapAmount = 0 disables the cap entirely and the EA treats the full account equity as its capital, with InpCapFloor = 50 as the only remaining floor.
What to expect on a backtest: EX09022 on XAUUSD M5 with the default 2.0 ATR multiplier is a low-trade-frequency EA. Crossover signals on a 20/50 SMA pair fire a handful of times per week on metals, and reversion triggers require a 2-ATR extension which is a meaningful move on M5. A six-month backtest typically lands somewhere between 30 and 80 trades depending on volatility regime. The 1:2 R:R bias means winners are larger than losers on average, so a 45-50% win rate can still produce a positive equity curve as long as the EA is not stopped out by the 95% equity floor or the 3-loss cooldown during a chop regime. The lack of trailing and break-even is a deliberate trade-off: the EA never locks profit, never moves to break-even, and never scales into a winner, so a trend move that runs past the 2-ATR target simply exits at the TP and the EA re-arms. Use a low-spread ECN broker for the metals pair so the SL_Points distance is not eaten by spread on every fill, and respect the 95% equity floor by running on a balance that gives the strategy at least a few weeks of room before the daily-loss limit starts to constrain it.
Strategy Deep Dive
Each tick, the EA refreshes the daily P&L and trade counters, then runs through the 8-condition IsSafeToTrade gate. If it passes, OnTick() copies the last three bars of the 20- and 50-period SMAs and the last two bars of the 14-period ATR. A buy is registered when either the fast SMA crosses above the slow SMA, or the mid-price sits more than 2.0 ATR below the slow SMA; a sell is the mirror. Order construction goes through a CTradeValidator that normalizes the lot to the broker's step, verifies free margin with a 15% buffer, and validates the SL and TP against the symbol's stops-level before sending. Send failures route through a double retry layer: three attempts in ExecuteTrade with 100 ms gaps and a price refresh, wrapped around three more attempts in TryOrderSend_EX09022 with 200 ms gaps on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED. The OnTradeTransaction handler streams profit, swap and commission for every closing deal into the daily counter so the 3% daily-loss limit and the 3-loss cooldown are enforced on the deal stream, not on the EA's own bookkeeping. The OnTester fitness function is n*p/(1+d) with a 30-trade minimum and zero-out for non-positive profit factor or drawdown.
Entries fire on either of two conditions, OR-merged: a trend crossover when the 20-period SMA crosses the 50-period SMA, or a reversion trigger when price extends more than 2.0 x ATR(14) away from the slow SMA. The trade block is skipped entirely while any position on the symbol with magic 22209022 is open.
Exits are stop-loss and take-profit only. There is no trailing stop, no break-even, no partial close, and no opposite-signal exit. The trade simply runs to whichever level is hit first at the 1:2 R:R default and the EA re-arms.
Stop-loss is a fixed SL_Points = 500 (about $5 on XAUUSD with a 0.01 point), validated against the broker's stops-level with a 20% extra buffer inside the CTradeValidator class. There is no in-trade adjustment.
Take-profit is a fixed TP_Points = 1000 (about $10 on XAUUSD), giving a clean 1:2 R:R against the 500-point stop. The validator slides the TP to the nearest broker-acceptable price if the requested level is too close to the entry.
Suited to traders running XAUUSD M5 or M15 on a low-spread ECN broker with at least a $100 balance, willing to accept a low-trade-frequency EA that depends on either a 20/50 SMA crossover or a 2-ATR extension. The London and New York session gate filters out Asia (toggleable), so the EA performs best when the broker's server time aligns reasonably with GMT and during the 7-16 / 12-21 GMT overlap windows.
Strategy Logic
Pipsgrowth EX09022 MeanReversion — Strategy Logic Analysis (from .mq5 source)
Family: MeanReversion
Magic: 22209022
Version: 2.00
BRIEF:
Mean reversion / trend EA using fast and slow MA crossover with ATR-based volatility bands. When price deviates from the fast MA by ATR multiplier, it enters expecting reversion to the mean. Includes full trade validation with safety-trade fallback and validated SL/TP. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
ExecuteTrade()OnTradeTransaction()EffectiveCapital_EX09022()DetectGMTOffset_EX09022()ServerToGMT_EX09022()IsMarketOpen_EX09022()InActiveSession_EX09022()IsNewsTime_EX09022()IsSafeToTrade_EX09022()UpdateDailyCounters_EX09022()TryOrderSend_EX09022()
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (10 total across 4 groups):
- [=== Identity ===] Magic_Number =
22209022// Magic Number forEA - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_09022" // Trade comment - [=== Strategy ===] Fast_MA_Period = 20 // Fast MA Period
- [=== Strategy ===] Slow_MA_Period = 50 // Slow MA Period
- [=== Strategy ===] ATR_Period = 14 //
ATRPeriod for volatility - [=== Strategy ===] ATR_Multiplier =
2.0//ATRMultiplier for Mean Reversion - [=== Risk Management ===]
LotSize=0.1// Standard Lot Size - [=== Risk Management ===] SL_Points = 500 // Stop Loss in points
- [=== Risk Management ===] TP_Points = 1000 // Take Profit in points
- [=== Capital Allocation Cap ===]
InpCapFloor=50.0// Global variables
// Pipsgrowth EX09022 MeanReversion — Execution Flow (from source analysis)
// Family: MeanReversion
// Mean reversion / trend EA using fast and slow MA crossover with ATR-based volatility bands. When price deviates from the fast MA by ATR multiplier, it enters expecting reversion to the mean. Includes full trade validation with safety-trade fallback and validated SL/TP. 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 H1 or H4 chart
- 7Set Bollinger Band period, deviation, RSI levels, and lot size
- 8Enable Allow Algo Trading and click OK
EA Parameters
| Parameter | Default | Description |
|---|---|---|
| Magic_Number | 22209022 | Magic Number for EA |
| InpTradeComment | "Psgrowth.com Expert_09022" | Trade comment |
| Fast_MA_Period | 20 | Fast MA Period |
| Slow_MA_Period | 50 | Slow MA Period |
| ATR_Period | 14 | ATR Period for volatility |
| ATR_Multiplier | 2.0 | ATR Multiplier for Mean Reversion |
| LotSize | 0.1 | Standard Lot Size |
| SL_Points | 500 | Stop Loss in points |
| TP_Points | 1000 | Take Profit in points |
| InpCapFloor | 50.0 | Global variables |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX09022 Mean Reverse — MA crossover with ATR mean-reversion bands, full 12-layer stack."
// Input parameters for Mean Reversion/Trend strategy
input group "=== Identity ==="
input int Magic_Number = 22209022; // Magic Number for EA
input string InpTradeComment = "Psgrowth.com Expert_09022"; // Trade comment
input group "=== Strategy ==="
input int Fast_MA_Period = 20; // Fast MA Period
input int Slow_MA_Period = 50; // Slow MA Period
input int ATR_Period = 14; // ATR Period for volatility
input double ATR_Multiplier = 2.0; // ATR Multiplier for Mean Reversion
input group "=== Risk Management ==="
input double LotSize = 0.1; // Standard Lot Size
input int SL_Points = 500; // Stop Loss in points
input int TP_Points = 1000; // Take Profit in points
input group "=== Hardening: GMT Sessions ==="
input int InpServerGMTOffset = 0;
input int InpLondonStartHour = 7;
input int InpLondonEndHour = 16;
input int InpNYStartHour = 12;
input int InpNYEndHour = 21;
input bool InpAvoidAsia = true;
input int InpAsiaStartHour = 0;
input int InpAsiaEndHour = 7;
input bool InpNewsFilter = false;
input int InpNewsFilterMinutes = 15;
input int InpMaxTradesPerDay = 50;
input double InpMinEquityPercent = 95.0;
input int InpCooldownMinutes = 30;
input int InpMaxConsecLosses = 3;
input double InpDailyLossLimitPct = 3.0;
input group "=== Capital Allocation Cap ==="
// InpCapEnabled removed — use InpCapAmount=0 to disable
input double InpCapAmount = 0.0;
input double InpCapFloor = 50.0;
// Global variables
int Fast_MA_Handle; // Handle for fast MA indicator
int Slow_MA_Handle; // Handle for slow MA indicator
int ATR_Handle; // Handle for ATR indicator
bool safety_trade_executed = false; // Flag for Safety-Trade execution
bool already_checked_history = false; // Flag for History-Check
bool EnableSafetyTrade = true; // Safety Trade for validation is always enabled
int g_gmtOffset = 0;
int g_consecLosses = 0;
datetime g_cooldownUntil = 0;
double g_realizedToday = 0;
int g_tradesToday = 0;
datetime g_lastTradeDate = 0;
double g_initialBalance = 0;
//+------------------------------------------------------------------+
//| Validator class for complete trade validation |
//+------------------------------------------------------------------+
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 Mean Reversion strategy EAs from our library
Pipsgrowth EX09013 MeanReversion
Pipsgrowth.com EX09013 Bollinger_Bands_EA — BB mean reversion with trend filter, full 12-layer stack.
Pipsgrowth EX09009 MeanReversion
Pipsgrowth.com EX09009 HangingManHammer Stoch — candlestick reversal + Stochastic confirm, full 12-layer stack.
Pipsgrowth EX09023 MeanReversion
Pipsgrowth.com EX09023 BollingerMeanReversion — BB outer band fade, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.