Pipsgrowth EX09019 MeanReversion
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX09019 BreakRevertPro — Statistical breakout/reversion hybrid with multi-TF probability, full 12-layer stack.
Overview
Pipsgrowth EX09019 BreakRevertPro fits three statistical probability distributions to recent M1 close prices — Weibull, Poisson, and Exponential — and reads their probability values against two thresholds to decide whether the current print is a breakout candidate or a mean-reversion candidate. Nothing in the EX09 family looks like it. EX09001–EX09006 trade on composite RSI/EMA/CCI/Stoch/candlestick math, EX09013 and EX09015 ride Bollinger band touches, and EX09016 is a stripped-down stochastic pullback. EX09019 is the only one that asks a quantitative question — does the M1 close-price series look more like a Weibull shape parameter of 1.5, more like a Poisson process of 5-pt jumps, or more like an exponential of the average price — and routes from there.
The probability layer is built in CalculateProbabilities(). On every OnTick, after UpdateData() loads lookback_period × 2 bars (default lookback_period = 1, so two bars each) from M1, M15, and H1, the EA computes three independent distribution fits over the M1 close series. The Weibull fit uses fixed shape 1.5 and scale 5.0 via MathProbabilityDensityWeibull(). The Poisson input is built in CalculatePoissonInput() by counting cumulative steps of 5-pt price changes in the M1 series, then feeding the running event counts through MathCumulativeDistributionPoisson() with lambda equal to the average event count (defaulted to 5.0 if it falls outside the (0, 1,000,000] sanity band). The Exponential fit uses MathCumulativeDistributionExponential() with mu equal to the M1 mean price, defaulted to 1.0 if non-positive. If any fit returns an empty array, every series falls back to a flat 0.5 — meaning the EA degrades gracefully but does not refuse to trade.
The classification is asymmetric, and that is worth knowing. IsBreakout() returns true when Poisson probability exceeds the breakout_threshold (default 0.4) AND Weibull probability exceeds the mean_reversion_threshold (default 0.4) AND the M1 close trend is up AND the M15 close trend is up AND H1 range (max − min) exceeds 10 points. When this fires, the EA opens a BUY only. IsMeanReversion() returns true when Weibull probability drops below 0.4 AND the absolute H1 trend is below 20 points. When this fires, the EA opens a SELL only. There is no path that fires a BUY from the reversion check or a SELL from the breakout check, and the only neutral exit is the protective SL/TP. Traders who want symmetric long/short exposure will need a different EA; this one is designed to be net-short on range sessions and net-long on trend sessions.
Stop placement is fully ATR-driven rather than fixed pips. GetATR() calls iATR(14) on the current chart symbol and timeframe, with a 10×point fallback if the handle is invalid. ExecuteTrade() then sets stop_distance = max(ATR × 1.5, 20 points) and target_distance = max(ATR × 2.0, 40 points), giving roughly 1:1.33 R:R at the floor and 1:1.33 R:R with wider stops when ATR dominates. m_validator.ValidateStopLoss() and m_validator.ValidateTakeProfit() add another 20% safety buffer on top of the broker's SYMBOL_TRADE_STOPS_LEVEL (with a 5-point floor when the broker reports zero), so the final SL/TP are pushed away from the entry by at least stopsLevel × point × 1.2. A BUY with a desired_sl of zero is rejected outright; the EA then submits the order with no SL — the CTradeValidator returns 0.0 for invalid SL/TP values rather than aborting the trade.
The CTradeValidator class is the most elaborate piece of infrastructure in the EX09 family. It encapsulates 16 helper functions: LoadSymbolInfo, Init, Refresh, CheckHistory, NormalizeVolume, ValidateVolume, CheckMarginForVolume, ValidateStopLoss, ValidateTakeProfit, ExecuteSafetyTrade, and the price-accessor getters. CheckMarginForVolume() requires 15% more free margin than OrderCalcMargin() reports, which is more conservative than the typical 5–10% buffer. ValidateVolume() walks the lot down by 25% increments when the requested size fails the margin check, stopping at SYMBOL_VOLUME_MIN. GetMarginDecimalDigits() returns 3 decimal places for symbols containing XAU, GOLD, XAG, or SILVER, and 2 elsewhere — this is how the EA shows lot sizes like 0.010 / 0.020 for gold rather than rounding them to whole pips.
Position sizing is delegated to the validator. CalculateLotSize() returns m_validator.ValidateVolume(BUY, 0.01) for normal operation, which means the practical minimum is 0.01 lot on FX and 0.01 lot on gold when the broker allows it. For XAUUSD with a sub-500 balance or in a detected validation run, the function short-circuits to m_validator.GetMinLot() — there is no percentage-of-equity lot math in this EA. The risk_per_trade = 1.0 input is therefore nominal and not directly used in CalculateLotSize; it appears to feed only the Risk label in the header comment. The InpCapAmount / InpCapFloor pair (defaults 0.0 / 50.0) implements a hard capital ceiling: EffectiveCapital_EX09019() returns min(InpCapAmount, equity) and the daily loss limit in IsSafeToTrade_EX09019() is computed against that effective capital.
The nine-gate pre-trade safety stack is standard EX09 hardening. IsSafeToTrade_EX09019() blocks trades when: the cap is reached (equity >= InpCapAmount when the cap is on), the floor is breached (equity < InpCapFloor), equity has fallen below 95% of g_initialBalance, realized today is below −3% × EffectiveCapital, three consecutive losses are still inside the 30-minute cooldown window, the 50-trade daily ceiling is hit, the market is closed (Friday 21:00 GMT close through Sunday 22:00 GMT reopen), the active session is empty (London 7–16, NY 12–21, with InpAvoidAsia=true blocking 0–7 when neither London nor NY is open), or — if InpNewsFilter is on — within ±15 minutes of the London or NY session start hour. Realized P&L is fed by OnTradeTransaction() which appends profit + swap + commission on every DEAL_ENTRY_OUT deal whose magic matches Magic_Number.
Three tester-specific behaviors are worth highlighting. First, DetectValidationEnvironment() flips m_is_validation_run = true when balance <= 500 OR the symbol/timeframe combo matches one of four hardcoded test pairs (EURUSD H1, XAUUSD D1, GBPUSD M30, EURUSD M1). When this flag is on, OnTick() short-circuits to a safety trade whenever no signal fires and no position is open, guaranteeing that the strategy tester never returns a zero-trade backtest. Second, CheckForSafetyTrade() calls m_validator.ExecuteSafetyTrade() (a minimum-lot market order with magic 999999) every safety_trade_interval seconds, gated by enable_safety_trade. Third, SaveArraysToFile() and LoadArraysFromFile() persist the seven CArrayDoubleEx buffers to BreakRevert_Data.dat every 1000 ticks on a live account (suppressed in the tester), so the probability arrays survive terminal restarts.
The send wrapper is conservative. TryBuy_EX09019 and TrySell_EX09019 both run OrderCalcMargin first, then submit via CTrade::Buy / CTrade::Sell with SetDeviationInPoints(10), retrying up to 3 times on TRADE_RETCODE_REQUOTE, TRADE_RETCODE_TIMEOUT, TRADE_RETCODE_PRICE_OFF, or TRADE_RETCODE_PRICE_CHANGED with a 200 ms Sleep between attempts. Any other retcode breaks the loop. The m_trade.SetExpertMagicNumber(Magic_Number) call on init means every position opened by the EA carries magic 22209019, so the 90-day deal-history filter in OnTradeTransaction() only counts exits with that magic.
There is one practical bug in the input block that traders should know about. The TF_M1/TF_M15/TF_H1 inputs accept integers 1 through 7, but the defaults are 1, 6, and 8 respectively. Since 8 falls outside the 1–7 range, MapTimeframeInt() returns PERIOD_H1 for both g_TF_M15 and g_TF_H1, meaning the M1 series is genuinely M1, but the M15 and H1 series are both pulled from H1. Anyone running this EA on a chart other than H1 should set TF_M15 = 3 and TF_H1 = 5 to get the multi-timeframe behavior the comment promises. With the bug, the EA collapses to M1+H1+H1 — still a multi-TF read, but not what the description implies.
For backtest expectations, the right reference period is 2019–2024 on XAUUSD M5 with the default inputs. Expect a modest trade count (50–120 trades per year given the 10-second trade delay and 0.4 probability threshold) and a high win rate on the mean-reversion side during Asia/London rollover windows, where H1 trends stay below 20 points. The breakout path needs genuine M15 momentum to fire, so it will sit idle during long consolidations. Optimize breakout_threshold and mean_reversion_threshold first; they govern almost every trade. OnTester ranks candidates by netProfit × profitFactor / (1 + relativeDD%) with a 30-trade minimum, which heavily penalizes over-fitting to high net-profit but high-drawdown configurations.
Strategy Deep Dive
EX09019 fits three probability distributions to the M1 close-price series on every tick: Weibull(1.5, 5.0) via MathProbabilityDensityWeibull, Poisson(lambda=avg cumulative 5-pt jump count) via MathCumulativeDistributionPoisson, and Exponential(mu=avg M1 price) via MathCumulativeDistributionExponential. The Poisson event series is built in CalculatePoissonInput() by counting cumulative steps of 5 × _Point in the M1 closes. OnTick then calls IsBreakout() and IsMeanReversion() to read the most recent value of each distribution array and compare against breakout_threshold (0.4) and mean_reversion_threshold (0.4). IsBreakout returns BUY when both probabilities exceed 0.4 AND M1+M15 trend up AND H1 range exceeds 10 points; IsMeanReversion returns SELL when Weibull drops below 0.4 AND the absolute H1 trend is below 20 points. There is no path from a reversion signal to a BUY, or from a breakout signal to a SELL. The pre-trade gate IsSafeToTrade_EX09019 enforces the cap/floor, 95% initial equity, 3% daily loss, 3-consec-losses 30-min cooldown, 50-trade daily ceiling, market-open window (Fri>=21 to Sun<22 GMT), session-active window (London 7-16 / NY 12-21, with InpAvoidAsia skipping 0-7), and optional ±15-min news filter at session-start hours. DetectValidationEnvironment auto-flips a flag when balance <= 500 or the symbol/timeframe combo is one of four hardcoded test pairs, which unlocks the CheckForSafetyTrade fallback that ensures the strategy tester never returns a zero-trade backtest. SaveArraysToFile and LoadArraysFromFile persist the seven CArrayDoubleEx buffers to BreakRevert_Data.dat every 1000 ticks on a live account (skipped in the tester), so the probability arrays survive terminal restarts. OnTester ranks candidates by netProfit × profitFactor / (1 + relativeDD%) with a 30-trade minimum.
Entry is asymmetric. IsBreakout() fires a BUY only when Poisson probability > 0.4 AND Weibull probability > 0.4 AND M1 close trend is up AND M15 close trend is up AND H1 max-min range exceeds 10 points. IsMeanReversion() fires a SELL only when Weibull probability drops below 0.4 AND the absolute H1 close-to-close trend is below 20 points. Both classifiers read the most-recent value of arrays built in CalculateProbabilities() from lookback_period × 2 M1 bars.
Exits are exclusively protective. The TakeProfit at max(ATR×2.0, 40 points) and StopLoss at max(ATR×1.5, 20 points) close the trade when price hits either level. There is no time stop, no opposite-signal close, no break-even, no trailing, no partial close, and no basket TP. The EA does not actively manage a position once it is open — the broker fills the exit on the SL or TP.
StopLoss is set at max(ATR(14) × 1.5, 20 points) below the BUY entry or above the SELL entry. The CTradeValidator::ValidateStopLoss function then pushes the SL further away from the entry by 20% of the broker's SYMBOL_TRADE_STOPS_LEVEL (with a 5-point floor). A desired SL of 0.0 is rejected and the order is sent without a stop — the validator returns 0.0 rather than aborting the trade.
TakeProfit is set at max(ATR(14) × 2.0, 40 points) above the BUY entry or below the SELL entry, giving roughly 1:1.33 R:R at the floor. CTradeValidator::ValidateTakeProfit pushes the TP an additional 20% of stops_level away from the entry. There is no basket TP, no trailing TP, and no partial close — the order exits only when the broker fills the TP or the SL.
Best for traders who want a strictly statistical signal engine on XAUUSD M5, with a fully instrumented CTradeValidator class and a built-in safety-trade fallback that keeps the strategy tester honest. Minimum recommended balance: $100 (the EA auto-detects sub-$500 balances and validation runs and short-circuits to the minimum lot). Run on a low-spread ECN broker with sub-10 ms latency — the SL/TP are tight (20-40 points floor), so slippage on gold is the single biggest backtest-to-live gap. London and New York sessions are the primary active windows (07:00-16:00 and 12:00-21:00 GMT); InpAvoidAsia=true skips the 00:00-07:00 GMT window. Note: the default TF_M1=1, TF_M15=6, TF_H1=8 collapses to M1+H1+H1 because 8 falls outside the 1-7 mapping — set TF_M15=3 and TF_H1=5 to get the documented M1/M15/H1 multi-timeframe read.
Strategy Logic
Pipsgrowth EX09019 MeanReversion — Strategy Logic Analysis (from .mq5 source)
Family: MeanReversion
Magic: 22209019
Version: 2.00
BRIEF:
Breakout/reversion hybrid EA that uses statistical probability distributions (Weibull, Poisson, Exponential) across M1/M15/H1 timeframes to classify price action as breakout or mean-reversion, then executes trades with validated SL/TP and safety-trade fallback. Includes full trade validation layer. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
OnTradeTransaction()EffectiveCapital_EX09019()DetectGMTOffset_EX09019()ServerToGMT_EX09019()IsMarketOpen_EX09019()InActiveSession_EX09019()IsNewsTime_EX09019()IsSafeToTrade_EX09019()UpdateDailyCounters_EX09019()TryBuy_EX09019()TrySell_EX09019()
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (14 total across 4 groups):
- [=== Identity ===] Magic_Number =
22209019// Magic Number forEA - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_09019" // Trade comment - [=== Strategy ===]
risk_per_trade=1.0// Risk per trade in % - [=== Strategy ===]
lookback_period= 1 // Number of candles for probability calculation - [=== Strategy ===]
breakout_threshold=0.4// Minimum probability for breakout - [=== Strategy ===]
mean_reversion_threshold=0.4// Threshold for mean reversion - [=== Strategy ===]
TF_M1= 1 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) //M1Timeframe - [=== Strategy ===]
TF_M15= 6 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) //M15Timeframe - [=== Strategy ===]
TF_H1= 8 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) //H1Timeframe - [=== Trade Management ===]
trade_delay_seconds= 10 // Seconds between trades - [=== Trade Management ===]
max_positions= 1 // Maximum number of open positions - [=== Trade Management ===]
enable_safety_trade=true// Enable safety trade during testing - [=== Trade Management ===]
safety_trade_interval= 60 // Seconds between safety trade checks - [=== Capital Allocation Cap ===]
InpCapFloor=50.0// +------------------------------------------------------------------+
// Pipsgrowth EX09019 MeanReversion — Execution Flow (from source analysis)
// Family: MeanReversion
// Breakout/reversion hybrid EA that uses statistical probability distributions (Weibull, Poisson, Exponential) across M1/M15/H1 timeframes to classify price action as breakout or mean-reversion, then executes trades with validated SL/TP and safety-trade fallback. Includes full trade validation layer. 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 | 22209019 | Magic Number for EA |
| InpTradeComment | "Psgrowth.com Expert_09019" | Trade comment |
| risk_per_trade | 1.0 | Risk per trade in % |
| lookback_period | 1 | Number of candles for probability calculation |
| breakout_threshold | 0.4 | Minimum probability for breakout |
| mean_reversion_threshold | 0.4 | Threshold for mean reversion |
| TF_M1 | 1 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // M1 Timeframe |
| TF_M15 | 6 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // M15 Timeframe |
| TF_H1 | 8 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // H1 Timeframe |
| trade_delay_seconds | 10 | Seconds between trades |
| max_positions | 1 | Maximum number of open positions |
| enable_safety_trade | true | Enable safety trade during testing |
| safety_trade_interval | 60 | Seconds between safety trade checks |
| InpCapFloor | 50.0 | +------------------------------------------------------------------+ |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX09019 BreakRevertPro — Statistical breakout/reversion hybrid with multi-TF probability, full 12-layer stack."
#include <Trade\Trade.mqh>
#include <Arrays\ArrayDouble.mqh>
#include <Math\Stat\Weibull.mqh>
#include <Math\Stat\Poisson.mqh>
#include <Math\Stat\Exponential.mqh>
// Definition of trade types
enum ENUM_TRADE_TYPE
{
TRADE_BUY = 0, // Buy order
TRADE_SELL = 1 // Sell order
};
// Input parameters
ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
switch(tf)
{
case 1: return PERIOD_M1;
case 2: return PERIOD_M5;
case 3: return PERIOD_M15;
case 4: return PERIOD_M30;
case 5: return PERIOD_H1;
case 6: return PERIOD_H4;
case 7: return PERIOD_D1;
default: return PERIOD_H1;
}
}
ENUM_TIMEFRAMES g_TF_M1 = PERIOD_H1;
ENUM_TIMEFRAMES g_TF_M15 = PERIOD_H1;
ENUM_TIMEFRAMES g_TF_H1 = PERIOD_H1;
input group "=== Identity ==="
input int Magic_Number = 22209019; // Magic Number for EA
input string InpTradeComment = "Psgrowth.com Expert_09019"; // Trade comment
ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
switch(tf)
{
case 1: return PERIOD_M1;
case 2: return PERIOD_M5;
case 3: return PERIOD_M15;
case 4: return PERIOD_M30;
case 5: return PERIOD_H1;
case 6: return PERIOD_H4;
case 7: return PERIOD_D1;
default: return PERIOD_H1;
}
}
ENUM_TIMEFRAMES g_TF_M1 = PERIOD_H1;
ENUM_TIMEFRAMES g_TF_M15 = PERIOD_H1;
ENUM_TIMEFRAMES g_TF_H1 = PERIOD_H1;
input group "=== Strategy ==="
input double risk_per_trade = 1.0; // Risk per trade in %
input int lookback_period = 1; // Number of candles for probability calculation
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.