P
PipsGrowth
Mean ReversionOpen Source – Free

Pipsgrowth EX09010 MeanReversion

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX09010 Thanos Snap XAUUSD 5M — RSI+CCI contrarian reversal + optional recovery grid, full 12-layer stack.

Overview

The Pipsgrowth EX09010 "Thanos Snap" sits squarely in the Mean Reversion family, but its personality comes from a single signature feature: a recovery grid that snaps in below the original entry when the first trade goes against it. Despite the dramatic name, the grid is hard-capped, multiplier-bounded, and disabled by default — turn it on, and the EA behaves like a controlled martingale; leave it off, and it runs as a clean dual-oscillator reversal system. That binary is the most consequential choice a user will make.

Signal construction is the second distinguishing trait. EX09010 reads both RSI(14) and CCI(14) on the last closed M5 bar and only fires when both oscillators agree at the threshold — RSI below 30 paired with CCI below -100 for a long entry, RSI above 70 paired with CCI above +100 for a short entry. A confidence score is logged (50 + 2× the depth beyond the threshold, clamped 20-100) but is informational, not gating. The signal will not fire off either oscillator alone; that AND-logic is what filters the bulk of the false reversals on trending days and makes the dual-threshold design worth more than the sum of its parts. Other Mean Reversion EAs in this family mix RSI with an EMA, or CCI with a Stochastic cycle swing, or use a candlestick-pattern gate — this one is specifically dual-oscillator AND-confirm.

The trade is then handed to a confirmation layer that reads the H1 EMA(50) and requires price to be extended at least 0.25×ATR(14) from it. For a long reversal, the EA wants the bid sitting more than a quarter-ATR below the H1 line; for a short reversal, more than a quarter-ATR above. This is the "pullback context" check, and it is what separates a genuine overshoot from a mid-range noise spike. Without it, a Mean Reversion EA will keep trying to fade healthy intraday pullbacks inside an H1 trend; with it, EX09010 only triggers when the M5 has stretched meaningfully away from where the higher timeframe thinks value lives.

Regime is handled by a 7-state classifier that runs on ADX(14), Bollinger Bands (20, 2.0) width ratio, and ATR(14) percentile. The states are StrongTrend, Expand, WeakTrend, Range, Compress, Choppy, and an unknown fallback. The NoTrade gate explicitly blocks StrongTrend and Expand — both flags the EA reads as "do not fade a trend in motion." WeakTrend, Range, and Compress are the productive states for the dual-oscillator reversal. Choppy is permitted for the entry itself but is what force-closes an open position if the regime flips after entry. This is a deliberate separation: a Choppy open is fine to enter, but a Choppy post-entry regime is treated as a deteriorating condition that should not be held.

Risk is sized at 0.5% of effective capital per trade, with the lot calculation reading both tick_value and tick_size off the symbol and dividing the risk budget by the per-lot loss at the configured SL distance. SL is set at ATR(14)×2.0 (InpSignalATRMult=2) and floored at 1.2× the broker's stop level so it never sits inside the freeze zone. TP sits at 2.0R from entry (InpTP_R=2.0), which gives an asymmetric R:R that the partial-close logic further exploits. The capital allocation cap layer applies a hard ceiling: InpCapitalCapAmount, when set above zero, replaces real account equity with min(cap, equity) for all percentage-based math. A floor of 50 USD (InpCapitalCapFloor) blocks new entries entirely when equity falls below it. The realized PnL windows (3% daily, 6% weekly) are tracked per-magic and reset at the day and week boundaries.

The position management layer stacks five exit paths. The +1R break-even fires first: when unrealized profit reaches one unit of risk, the stop is moved to entry+0.2R (so the trade is essentially free unless the market round-trips to entry). The 50% partial close at +1R follows, but only if the remaining volume clears 1.5× the broker minimum lot — small accounts and small-size grid layers can skip the partial. The ATR(14)×2.5 trailing stop activates at +0.8R and only ratchets forward, never back. The 80-bar time stop on M5 (= 6 hours 40 minutes of bars) is the hard ceiling for any single trade. The fifth path is the regime-flip: if the classifier reports Choppy at any manage tick, the open position is force-closed immediately.

The Thanos Snap recovery grid is the section most users will read first. When InpEnableRecovery is true (false by default), ManageRecovery() watches the most recently opened position of the EA's magic. If price moves against it by InpRecoveryStep=300 points and the count is below both InpMaxConcurrent=5 and the hard-coded RECOVERY_MAX_LEVELS=5, the EA opens a same-direction layer sized at lastLot × min(InpRecoveryMult=1.4, RECOVERY_MAX_MULT=1.5). The same NoTrade gates apply — no recovery during weekends, no recovery when spread exceeds InpMaxSpread=250 points, no recovery during Choppy regimes. The hard caps on count and multiplier are deliberate: the EA explicitly refuses to convert into a runaway martingale even if the user pushes the inputs high.

A few features this EA does not include are worth flagging. There is no HTF bias (only an HTF extension check), no equity-floor stop, no news feed integration, no time-of-day session filter, and no pyramiding beyond the optional recovery grid. OnTester is implemented as (net × profit_factor) / (1 + equity_dd_pct) with a 30-trade minimum, rewarding both profitability and low drawdown simultaneously. SetTypeFillingBySymbol is auto-called in OnInit so the EA negotiates FOK versus IOC versus RETURN based on what the broker offers. All trade-send retries are 3-iteration loops with 200ms sleep on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED; modify retries use 100ms and only on REQUOTE/TIMEOUT. TryClosePartial exists but is called only by the partial-TP path inside ManagePositions — no other partial-close triggers are wired.

The most important footgun is InpDryRun=true, which is the default. With dry-run on, the EA logs every would-be entry but never actually opens one — useful for paper testing, brutal for anyone who downloads the EA and attaches it to a live chart without flipping the toggle. Pair that with InpKillSwitch (defaults to false) and you have two booleans the operator must check before expecting the EA to actually trade. The dry-run is also the reason recovery logic short-circuits at the top of ManageRecovery(): stacking grid levels in a paper test would generate noise without information.

What to expect on a backtest: the dual-oscillator signal is sparse but clean, so the EA will tend to take 2-5 trades per day on XAUUSD M5 under normal conditions, with most entries clustering on Range and Compress regime days. The recovery grid, when enabled, multiplies the count significantly because every losing first entry becomes the trigger for 1-4 same-direction layers. Expect the equity curve to stair-step when the grid is on — fast recovery on shallow reversals, drawn-out recovery on the deep runs that test the 5-level cap. Without the grid, the curve looks closer to a classic mean-reversion equity: many small wins, occasional full-stop losses, and a steady return profile that depends almost entirely on regime selection rather than signal quality.

Strategy Deep Dive

On every new M5 bar, ComputeSignal() reads RSI(14) and CCI(14) on the last CLOSED bar and votes +1 (long) when RSI<30 AND CCI<-100, or -1 (short) when RSI>70 AND CCI>100 — both oscillators must agree, the AND is intentional. ConfirmDir() then pulls an H1 EMA(50) and refuses the trade unless price is extended by at least 0.25×ATR(14) from that H1 line, a guard that ensures the trade only fires in genuine overshoot rather than mid-range noise. ClassifyRegime() runs a 7-state classifier from ADX(14), Bollinger width ratio (20,2), and ATR(14) percentile, and the NoTrade() gate blocks StrongTrend and Expand regimes outright. Risk is sized at 0.5% of effective capital (capped by InpCapitalCapAmount when set), lot math uses tick_value and tick_size, and the no-trade gate also enforces a 3% daily / 6% weekly loss cap with a 3-trade cooldown. Position management runs the +1R break-even, the 50% partial TP at +1R, the ATR(14)×2.5 trailing stop, the 80-bar time exit, and the Choppy-regime forced close, while the optional Thanos Snap recovery grid can stack up to 5 same-direction levels at 300-point spacing with a 1.4× lot multiplier (capped at 1.5×).

Entry Signal

Buys when the last closed M5 bar prints RSI(14) below 30 with CCI(14) below -100, confirmed only if price is extended more than 0.25×ATR(14) below the H1 EMA(50) (the H1 'pullback context' filter). Sells on the mirror: RSI(14) above 70, CCI(14) above +100, and price stretched above the H1 EMA(50). Both the dual-oscillator threshold AND the H1 extension check must clear — the entry never fires off RSI or CCI alone, which is what gives the signal its false-reversal-blocking quality on Range and Compress regime days.

Exit Signal

Exits in five stacked layers: the +1R break-even snaps the stop to entry+0.2R; a 50% partial close fires at +1R (only if remaining volume clears 1.5× the broker minimum); an ATR(14)×2.5 trailing stop activates at +0.8R and only ratchets forward; an 80-bar M5 time stop (≈ 6h40m) closes the trade; and a regime flip to Choppy force-closes the open position. If the optional Thanos Snap recovery grid is enabled, an additional same-direction layer may open at the +300-point step with multiplier 1.4 (capped at 1.5 and 5 levels total).

Stop Loss

Per-trade stop is fixed at ATR(14)×2.0 (InpSignalATRMult=2) from entry, floored at 1.2× the broker's SYMBOL_TRADE_STOPS_LEVEL. The same distance is fed into the lot-sizing math (0.5% of effective capital), so wider ATR periods naturally produce smaller positions.

Take Profit

Take-profit sits at 2.0R from entry (InpTP_R=2.0), so a typical XAUUSD trade targets roughly 2× the ATR distance used for SL. The exit logic is layered: half is typically banked at +1R via the 50% partial close, with the remaining half left to either trail to 2R or get stopped at break-even.

Best For

Minimum recommended balance: $100 (MEDIUM risk). Default XAUUSD M5 is the intended deployment — the 7-state regime classifier needs at least 100 bars of ATR history and 20 bars of Bollinger width to be reliable, which M5 supplies cheaply. The optional Thanos Snap recovery grid is the highest-impact setting: leaving it OFF gives a clean contrarian-reversal EA on Range and Compress days; turning it ON converts the strategy into a capped martingale-style recovery — strictly bounded at 5 levels, multiplier 1.5×, and only fires on Range/Compress/WeakTrend, never on Choppy or news-driven spread spikes. Check InpDryRun (default true) and InpKillSwitch (default false) before going live — both are easy to miss.

Strategy Logic

Pipsgrowth EX09010 MeanReversion — Strategy Logic Analysis (from .mq5 source)

Family: MeanReversion Magic: 22209010 Version: 2.00

BRIEF: Contrarian RSI+CCI reversal on last CLOSED bar in Range/Compress/WeakTrend regimes. Optional ATR-spaced recovery grid (default OFF, hard-capped 5 levels, multiplier-bounded, no martingale during news/high-spread/choppy). 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • NormPrice()
  • NormVolume()
  • StopsLevelPoints()
  • FillingMode()
  • EffectiveCapital()
  • RealizedPnL()
  • DayStart()
  • WeekStart()
  • CountMyPositions()
  • MyPositionDir()
  • ClassifyRegime()
  • ComputeSignal()
  • ...and 11 more

INTERNAL CONSTANTS (25 total):

  • ATR_PERIOD = 14 // ATR period (signal + SL + trail)
  • ATR_PCTILE_LOOKBACK = 100 // Bars for ATR percentile
  • BB_PERIOD = 20 // Bollinger period (regime width)
  • BB_DEVIATION = 2.0 // Bollinger deviation (regime width)
  • ADX_PERIOD = 14 // ADX period (regime)
  • RSI_PERIOD = 14 // RSI period (signal)
  • CCI_PERIOD = 14 // CCI period (signal)
  • HTF_EMA_PERIOD = 50 // HTF trend EMA period
  • HTF_TIMEFRAME = PERIOD_H1 // HTF trend timeframe
  • SIGNAL_LOOKBACK = 1 // Use shift=1 (last CLOSED bar)
  • MIN_RR_RATIO = 1.2 // Minimum reward:risk
  • BE_TRIGGER_R = 1.0 // Break-even at +1R
  • BE_LOCK_R = 0.2 // BE locks +0.2R
  • PARTIAL_TP_R = 1.0 // Partial TP at +1R
  • PARTIAL_PCT = 50 // Partial close percent
  • ...and 10 more

INPUT PARAMETERS (24 total across 8 groups):

  • [=== Identity ===] InpMagicNumber = 22209010 // Magic number (unique per EA)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_09010" // Trade comment
  • [=== Signal (RSI + CCI reversal) ===] InpRSIOversold = 30.0 // RSI oversold threshold (long entry)
  • [=== Signal (RSI + CCI reversal) ===] InpRSIOverbought = 70.0 // RSI overbought threshold (short entry)
  • [=== Signal (RSI + CCI reversal) ===] InpSignalATRMult = 2 // ATR multiplier for SL distance
  • [=== Recovery Grid (Thanos Snap) ===] InpEnableRecovery = false // Enable recovery grid (default OFF, hard-capped)
  • [=== Recovery Grid (Thanos Snap) ===] InpRecoveryMult = 1.4 // Lot multiplier per recovery step (capped)
  • [=== Recovery Grid (Thanos Snap) ===] InpRecoveryStep = 300 // Step distance in points between levels
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (% of effective capital)
  • [=== Risk & Sizing ===] InpDailyLossLimitPercent = 3.0 // Daily loss limit (% of effective capital)
  • [=== Risk & Sizing ===] InpWeeklyLossLimitPercent = 6.0 // Weekly loss limit (% of effective capital)
  • [=== Risk & Sizing ===] InpMaxConcurrent = 5 // Max concurrent positions (recovery levels count)
  • [=== Risk & Sizing ===] InpCooldownLosses = 3 // Cooldown after N consecutive losses
  • [=== Risk & Sizing ===] InpFixedLotMode = false // Use fixed lot (bypass % risk)
  • [=== Capital Allocation Cap ===] InpCapitalCapAmount = 0.0 // Cap amount ($ real money equity)
  • [=== Capital Allocation Cap ===] InpCapitalCapFloor = 50.0 // Floor ($); below = block new entries
  • [=== Regime / Confirm ===] InpRequireRegime = true // Require regime gate (Range/Compress/WeakTrend)
  • [=== Regime / Confirm ===] InpRequireHTF = true // Require HTF EMA oppose-to-revert (extreme pullback)
  • [=== Exit / Manage ===] InpTP_R = 2.0 // Take profit in R multiples
  • [=== Exit / Manage ===] InpUseBreakEven = true // Enable break-even
  • [=== Exit / Manage ===] InpUsePartialTP = true // Enable partial TP
  • [=== Execution / Safety ===] InpMaxSpread = 250 // Max allowed spread (points)
  • [=== Execution / Safety ===] InpDryRun = true // Dry-run: no real order sends
  • [=== Execution / Safety ===] InpKillSwitch = false // Kill switch: stop ALL activity
Pseudocode
// Pipsgrowth EX09010 MeanReversion — Execution Flow (from source analysis)
// Family: MeanReversion
// Contrarian RSI+CCI reversal on last CLOSED bar in Range/Compress/WeakTrend regimes. Optional ATR-spaced recovery grid (default OFF, hard-capped 5 levels, multiplier-bounded, no martingale during news/high-spread/choppy). 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 H1 or H4 chart
  7. 7Set Bollinger Band period, deviation, RSI levels, and lot size
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
InpMagicNumber22209010Magic number (unique per EA)
InpTradeComment"Psgrowth.com Expert_09010"Trade comment
InpRSIOversold30.0RSI oversold threshold (long entry)
InpRSIOverbought70.0RSI overbought threshold (short entry)
InpSignalATRMult2ATR multiplier for SL distance
InpEnableRecoveryfalseEnable recovery grid (default OFF, hard-capped)
InpRecoveryMult1.4Lot multiplier per recovery step (capped)
InpRecoveryStep300Step distance in points between levels
InpRiskPercent0.5Risk per trade (% of effective capital)
InpDailyLossLimitPercent3.0Daily loss limit (% of effective capital)
InpWeeklyLossLimitPercent6.0Weekly loss limit (% of effective capital)
InpMaxConcurrent5Max concurrent positions (recovery levels count)
InpCooldownLosses3Cooldown after N consecutive losses
InpFixedLotModefalseUse fixed lot (bypass % risk)
InpCapitalCapAmount0.0Cap amount ($ real money equity)
InpCapitalCapFloor50.0Floor ($); below = block new entries
InpRequireRegimetrueRequire regime gate (Range/Compress/WeakTrend)
InpRequireHTFtrueRequire HTF EMA oppose-to-revert (extreme pullback)
InpTP_R2.0Take profit in R multiples
InpUseBreakEventrueEnable break-even
InpUsePartialTPtrueEnable partial TP
InpMaxSpread250Max allowed spread (points)
InpDryRuntrueDry-run: no real order sends
InpKillSwitchfalseKill switch: stop ALL activity
Source Code (.mq5)Open Source
Pipsgrowth_com_EX09010.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX09010 Thanos Snap XAUUSD 5M — RSI+CCI contrarian reversal + optional recovery grid, full 12-layer stack."

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

//================================================================
// NON-INPUT CONSTANTS (operator-tunable surface stays lean)
//================================================================
#define ATR_PERIOD          14      // ATR period (signal + SL + trail)
#define ATR_PCTILE_LOOKBACK 100     // Bars for ATR percentile
#define BB_PERIOD           20      // Bollinger period (regime width)
#define BB_DEVIATION        2.0     // Bollinger deviation (regime width)
#define ADX_PERIOD          14      // ADX period (regime)
#define RSI_PERIOD          14      // RSI period (signal)
#define CCI_PERIOD          14      // CCI period (signal)
#define HTF_EMA_PERIOD      50      // HTF trend EMA period
#define HTF_TIMEFRAME       PERIOD_H1 // HTF trend timeframe
#define SIGNAL_LOOKBACK     1       // Use shift=1 (last CLOSED bar)
#define MIN_RR_RATIO        1.2     // Minimum reward:risk
#define BE_TRIGGER_R        1.0     // Break-even at +1R
#define BE_LOCK_R           0.2     // BE locks +0.2R
#define PARTIAL_TP_R        1.0     // Partial TP at +1R
#define PARTIAL_PCT         50      // Partial close percent
#define TRAIL_ATR_MULT      2.5     // ATR trailing multiplier
#define TRAIL_TRIGGER_R     0.8     // Trail kicks in at +0.8R
#define MAX_BARS_IN_TRADE   80      // Time-based exit (bars)
#define COOLDOWN_BARS       3       // Bars between entries
#define REGIME_MIN_ADX      18.0    // ADX >= this = trend territory
#define REGIME_BREAKOUT_ADX 28.0    // ADX >= this = strong/expanding
#define SPREAD_ROLL_WINDOW  50      // Bars for rolling spread avg
#define MAX_SLIPPAGE_POINTS 20      // Max slippage deviation (points)
#define RECOVERY_MAX_LEVELS 5       // Hard cap on recovery-grid levels
#define RECOVERY_MAX_MULT   1.5    // Hard cap on per-step lot multiplier

//================================================================
// INPUTS  (count: 19 — within 12-22 hard cap)
//================================================================
input group "=== Identity ==="
input int      InpMagicNumber    = 22209010;    // Magic number (unique per EA)
input string   InpTradeComment   = "Psgrowth.com Expert_09010"; // Trade comment

input group "=== Signal (RSI + CCI reversal) ==="
input double   InpRSIOversold    = 30.0;       // RSI oversold threshold (long entry)
input double   InpRSIOverbought  = 70.0;       // RSI overbought threshold (short entry)
input int      InpSignalATRMult  = 2;          // ATR multiplier for SL distance

input group "=== Recovery Grid (Thanos Snap) ==="
input bool     InpEnableRecovery = false;      // Enable recovery grid (default OFF, hard-capped)
input double   InpRecoveryMult   = 1.4;        // Lot multiplier per recovery step (capped)
input int      InpRecoveryStep   = 300;        // Step distance in points between levels

input group "=== Risk & Sizing ==="
input double   InpRiskPercent    = 0.5;        // Risk per trade (% of effective capital)
input double   InpDailyLossLimitPercent = 3.0; // Daily loss limit (% of effective capital)

Full source code available on download

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

Tags:ex09010meanreversionpipsgrowthfreemt5xauusd

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_EX09010.mq5
File Size36.5 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyMean Reversion
Risk LevelMedium Risk
Timeframes
M5
Currency Pairs
XAUUSD
Min. Deposit$100