Pipsgrowth EX09014 MeanReversion
MT5 Expert Advisor (Open Source) · XAUUSD · M15
Pipsgrowth.com EX09014 GoldScalper_RSIReversion — RSI extreme reversion for Gold, full 12-layer stack.
Overview
Pipsgrowth EX09014 MeanReversion is a single-position gold scalper that reads a 14-period RSI on the M15 chart and only trades when RSI leaves the 30/70 zones, the current candle's colour matches the reversal direction, and the previous candle's colour shows exhaustion in the opposite direction. The point of that two-bar pattern is to avoid catching falling knives — a low RSI by itself is not a buy, because gold can stay oversold for hours during thin sessions. The reversal-candle-plus-prior-exhaustion-candle combo is the EA's reading of "selling pressure has run out, buyers are stepping in"; the short side mirrors it.
SL is the maximum of three quantities: ATR(14) × 1.5, the user's fixed StopLossPips (default 15) converted to price via GetPipSize(), and the broker's SYMBOL_TRADE_STOPS_LEVEL × 1.5. The "max" form is the key. On quiet gold days where ATR is small, the fixed-pip floor takes over and the SL is exactly 15 pips; on volatile sessions where ATR has blown out, the ATR term dominates and the SL widens automatically. The minimum-distance floor exists so the EA doesn't send stops so tight that the broker's stop-level check rejects them. With the defaults on XAUUSD this almost always lands at 15 pips in the backtest.
TP handling is the unusual bit. UseRSIExitOnly defaults to true, which means the order is sent with tpPrice = 0 — there is no fixed TP. Exits run from ManageOpenPositions(), which fires on every tick (not just on new bars). For a long, the moment currentRSI >= RSI_ExitLevel (default 50) the position is closed via TryClose_EX09014(). For a short, the mirror is <= 50. The 50-line is a momentum-neutral level — "RSI has unwound, take the profit". If the user turns RSI-exit off, TP is set to slDist × 1.5 (1.5:1 R:R).
Trailing-stop logic also runs every tick. Once profit exceeds TrailingStartPips × pipSize (default 10 pips), the stop moves to currentPrice − TrailingStartPips for longs (or + 10 pips for shorts). After that initial move, the stop only ratchets in increments of TrailingStepPips (default 5 pips) — SafePositionModify rejects any update where the new SL isn't at least 5 pips better than the current one. This is "step trailing" rather than "every-tick ratchet", and is meant to suppress broker modification spam on noisy M15 bars.
Filters are minimal but explicit. UseSpreadFilter defaults to true with MaxSpreadPips = 25.0. On a 2-decimal gold broker (e.g. 1850.00) that's 2.5 raw price units — a wide tolerance so the EA doesn't disable itself on retail brokers with mediocre raw spreads. UseTimeFilter defaults to false; when enabled, the user supplies a StartTime/EndTime string and the EA blocks new entries outside the window. Both filters run inside CheckFilters() before the no-trade gate.
The hardening layer is real here, not aspirational. IsSafeToTrade_EX09014() returns false on any of the following: equity >= InpCapAmount (cap-on mode), equity < InpCapFloor (default $50), equity < 95% of g_initialBalance, daily realized loss >= 3% of effective capital, weekly realized loss >= 6%, three consecutive losses with a 30-minute cooldown still active, g_tradesToday >= InpMaxTradesPerDay (50), market closed (Friday 21:00 GMT → Sunday 22:00 GMT), no active London or New York session, or news window hit. The session filter (InActiveSession_EX09014) treats London 07:00–16:00 GMT and New York 12:00–21:00 GMT as active, blocks Asia 00:00–07:00 GMT by default, and only counts the Asia block if London/NY is also inactive. IsNewsTime_EX09014 is a clock-arithmetic proxy, not a real news feed: it blocks entries within ±InpNewsFilterMinutes (15) of the London and NY session-open hours. The flag is off by default.
GMT detection runs once in OnInit via DetectGMTOffset_EX09014. The function scans H1 bars backwards looking for a gap > 2 hours between adjacent bars — that's the weekend close — and infers the server's GMT offset from the gap's hour. The user can override with InpServerGMTOffset.
Risk math is the standard 2% pattern. CalculatePositionSize(slPips) takes AccountInfoDouble(ACCOUNT_BALANCE) × 0.02, divides by slPips × pipValuePerLot, rounds down to the broker's SYMBOL_VOLUME_STEP, clamps to SYMBOL_VOLUME_MIN/MAX, and shrinks the lot further if margin required exceeds 90% of free margin. The fixed-lot fallback (FixedLotSize = 0.01) is used when UseMoneyManagement = false. The hard lot cap InpMaxLot = 5.0 is enforced at init. The magic number is 22209014 — the EX09### family uses 22209###.
Two correctness details worth knowing. First, the EA holds at most one position at a time — CountPositions() >= 1 blocks new entries in OnTick(). No pyramiding, no hedging against same magic. Second, the OnTester formula is (profit × profit_factor) / (1 + equity_dd_pct) with a 30-trade minimum — a quality-weighted score that penalizes drawdown hard, so a high-PnF strategy with a 50% DD scores lower than a moderate-PnF strategy with a 10% DD. This is what the optimizer hill-climbs toward during MT5 backtests.
TryClose_EX09014 and TryModify_EX09014 both retry three times on the standard MQL5 transient codes (REQUOTE, TIMEOUT, PRICE_OFF, PRICE_CHANGED), with 200ms and 100ms sleeps respectively. SafePositionModify is the pre-flight: it normalizes SL/TP to _Digits, ensures each is on the correct side of price, and shifts to broker minimum distance if the user's stop is too tight.
What to expect in backtest: RSI reversion is a mean-reversion pattern and does best in range-bound sessions with adequate volatility. XAUUSD M15 with the default 30/70 thresholds and 15-pip floor SL trades about once every few hours during London/NY. Win rate with UseRSIExitOnly=true tends to be high (often 70%+) but the R-multiple per win is small (RSI typically doesn't run far past 50), while losses are capped at the SL distance. The expected profile is "many small wins, occasional full-SL losses" — the equity curve is generally a slow grind up with periodic drawdowns clustered around 3% daily-loss trips. The RSI exit at 50 means most winners close at single-digit pips, so commission and swap matter more on this EA than on a trend follower.
Strategy Deep Dive
Each new M15 bar, GetReversionSignal() reads two RSI values, two candle colours, and a single ATR(14) and only returns a signal when the prior bar was exhausted (RSI < 30 or > 70) and the current bar shows a directional reversal candle that follows a candle of the opposite colour — that two-bar shape is the entry gate. OpenPosition() then builds the SL as max(ATR1.5, 15 pips, broker_min1.5), sizes the lot to 2% risk of balance at that SL distance via CalculatePositionSize(), and sends a market order with no TP when UseRSIExitOnly is on. Every tick, ManageOpenPositions() checks whether RSI has returned to 50 (exit), then applies a 10-pip-start / 5-pip-step trailing stop via SafePositionModify. The full safety stack — spread filter, session filter (London/NY only, Asia blocked by default), GMT detection, daily/weekly loss caps, equity floor, and 3-loss cooldown — runs in CheckFilters() and IsSafeToTrade_EX09014() before the signal is even considered.
EX09014 enters a long when the previous bar's RSI closed below 30 (the RSI_Oversold default) and the current bar's RSI is rising, provided the current bar is bullish (close > open) and the previous bar was bearish — that two-bar pattern is the EA's reading of selling exhaustion. The short entry is the strict mirror: previous-bar RSI above 70, current RSI falling, current bar bearish, previous bar bullish. Only one position is allowed at a time, evaluated on each new M15 bar.
With UseRSIExitOnly = true (the default), exits are handled by ManageOpenPositions() on every tick: a long closes the moment currentRSI >= RSI_ExitLevel (default 50), a short closes the moment currentRSI <= 50. If RSI-exit is disabled, the position uses a fixed TP at 1.5× the SL distance, and the trailing stop takes over — once profit exceeds 10 pips, the stop ratchets in 5-pip increments via SafePositionModify. There is no time stop; positions survive overnight by default.
SL is the maximum of three quantities: ATR(14) × 1.5, StopLossPips × pipSize (default 15 pips), and SYMBOL_TRADE_STOPS_LEVEL × 1.5 — whichever is largest wins. The trailing stop kicks in at 10 pips of profit and ratchets in 5-pip steps via SafePositionModify. The position is also force-closed by IsSafeToTrade_EX09014() if daily loss hits 3% of effective capital, weekly loss hits 6%, equity falls below 95% of initial balance, or three consecutive losses trip the 30-minute cooldown.
With UseRSIExitOnly = true (the default), the order is sent with tpPrice = 0 and exit is purely RSI-driven: a long closes at RSI >= 50, a short closes at RSI <= 50. If RSI-exit is off, TP is set to slDist × 1.5 (1.5:1 R:R). The OnTester optimizer uses (profit × profit_factor) / (1 + equity_dd_pct) with a 30-trade minimum.
Minimum recommended balance: $100, but the EA's 2% per-trade risk with a 15-pip floor SL and 5.0-lot cap is sized for a micro gold account. XAUUSD M15 only — the M15 bar period is hardcoded via iRSI(_Symbol, PERIOD_M15, ...) and iATR(_Symbol, PERIOD_M15, 14). Use a low-spread broker: the 25-pip spread cap is intentionally wide so the EA passes most retail brokers, but tighter spreads (≤5 pips) will improve RSI-exit fills. Active sessions: London 07:00–16:00 GMT and New York 12:00–21:00 GMT — Asia 00:00–07:00 GMT is blocked by default. Risk level: MEDIUM.
Strategy Logic
Pipsgrowth EX09014 MeanReversion — Strategy Logic Analysis (from .mq5 source)
Family: MeanReversion
Magic: 22209014
Version: 2.00
BRIEF:
Gold scalping RSI reversion EA. BUY when RSI exits oversold with bullish reversal candle; SELL when RSI exits overbought with bearish reversal candle. Exit on RSI return to 50 or TP. Includes ATR-based SL, trailing, spread/time filters, and the 12-layer stack: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
SafePositionModify()OnTradeTransaction()RefreshIndicators()GetReversionSignal()OpenPosition()CalculatePositionSize()ManageOpenPositions()IsNewBar()GetPipSize()CheckFilters()CountPositions()EffectiveCapital_EX09014()- ...and 9 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (22 total across 6 groups):
- [=== Risk Management ===]
UseMoneyManagement=true// Use Dynamic Risk % - [=== Risk Management ===]
RiskPercent=2.0// Risk Percent per Trade - [=== Risk Management ===]
FixedLotSize=0.01// Fixed LotSize(if MMfalse) - [===
RSISettings ===] RSI_Period = 14 //RSIPeriod - [===
RSISettings ===] RSI_Oversold = 30 //RSIOversold Level - [===
RSISettings ===] RSI_Overbought = 70 //RSIOverbought Level - [===
RSISettings ===] RSI_ExitLevel = 50 //RSIExit Level - [=== Trade Settings ===]
StopLossPips= 15 // StopLoss(pips) - [=== Trade Settings ===]
TakeProfitPips= 25 // TakeProfit(pips) - [=== Trade Settings ===] Slippage = 3 // Max
Slippage(points) - [=== Trade Settings ===]
InpMagicNumber=22209014// Magic Number - [=== Trade Settings ===]
InpTradeComment= "Psgrowth.com Expert_09014" // TradeComment - [=== Trailing Stop ===]
UseTrailingStop=true// Use Trailing Stop - [=== Trailing Stop ===]
TrailingStartPips= 10 // TrailingStart(pips) - [=== Trailing Stop ===]
TrailingStepPips= 5 // TrailingStep(pips) - [=== Filters ===]
UseSpreadFilter=true// Use Spread Filter - [=== Filters ===]
MaxSpreadPips=25.0// MaxSpread(pips) - [=== Filters ===]
UseTimeFilter=false// Use Time Filter - [=== Filters ===]
StartTime= "08:00" // StartTime(HH:MM) - [=== Filters ===]
EndTime= "17:00" // EndTime(HH:MM) - [=== Filters ===]
UseRSIExitOnly=true// Exit onRSIlevelonly - [=== Hardening:
GMTSessions ===]InpMaxConsecLosses= 3 // Global Variables
// Pipsgrowth EX09014 MeanReversion — Execution Flow (from source analysis)
// Family: MeanReversion
// Gold scalping RSI reversion EA. BUY when RSI exits oversold with bullish reversal candle; SELL when RSI exits overbought with bearish reversal candle. Exit on RSI return to 50 or TP. Includes ATR-based SL, trailing, spread/time filters, and the 12-layer stack: 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 |
|---|---|---|
| UseMoneyManagement | true | Use Dynamic Risk % |
| RiskPercent | 2.0 | Risk Percent per Trade |
| FixedLotSize | 0.01 | Fixed Lot Size (if MM false) |
| RSI_Period | 14 | RSI Period |
| RSI_Oversold | 30 | RSI Oversold Level |
| RSI_Overbought | 70 | RSI Overbought Level |
| RSI_ExitLevel | 50 | RSI Exit Level |
| StopLossPips | 15 | Stop Loss (pips) |
| TakeProfitPips | 25 | Take Profit (pips) |
| Slippage | 3 | Max Slippage (points) |
| InpMagicNumber | 22209014 | Magic Number |
| InpTradeComment | "Psgrowth.com Expert_09014" | Trade Comment |
| UseTrailingStop | true | Use Trailing Stop |
| TrailingStartPips | 10 | Trailing Start (pips) |
| TrailingStepPips | 5 | Trailing Step (pips) |
| UseSpreadFilter | true | Use Spread Filter |
| MaxSpreadPips | 25.0 | Max Spread (pips) |
| UseTimeFilter | false | Use Time Filter |
| StartTime | "08:00" | Start Time (HH:MM) |
| EndTime | "17:00" | End Time (HH:MM) |
| UseRSIExitOnly | true | Exit on RSI level only |
| InpMaxConsecLosses | 3 | Global Variables |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX09014 GoldScalper_RSIReversion — RSI extreme reversion for Gold, full 12-layer stack."
#include <Trade\Trade.mqh>
//+------------------------------------------------------------------+
//| Inputs |
//+------------------------------------------------------------------+
input group "=== Risk Management ==="
input bool UseMoneyManagement = true; // Use Dynamic Risk %
input double RiskPercent = 2.0; // Risk Percent per Trade
input double FixedLotSize = 0.01; // Fixed Lot Size (if MM false)
input group "=== RSI Settings ==="
input int RSI_Period = 14; // RSI Period
input int RSI_Oversold = 30; // RSI Oversold Level
input int RSI_Overbought = 70; // RSI Overbought Level
input int RSI_ExitLevel = 50; // RSI Exit Level
input group "=== Trade Settings ==="
input int StopLossPips = 15; // Stop Loss (pips)
input int TakeProfitPips = 25; // Take Profit (pips)
input int Slippage = 3; // Max Slippage (points)
input int InpMagicNumber = 22209014; // Magic Number
input string InpTradeComment = "Psgrowth.com Expert_09014"; // Trade Comment
input group "=== Trailing Stop ==="
input bool UseTrailingStop = true; // Use Trailing Stop
input int TrailingStartPips = 10; // Trailing Start (pips)
input int TrailingStepPips = 5; // Trailing Step (pips)
input group "=== Filters ==="
input bool UseSpreadFilter = true; // Use Spread Filter
input double MaxSpreadPips = 25.0; // Max Spread (pips)
input bool UseTimeFilter = false; // Use Time Filter
input string StartTime = "08:00"; // Start Time (HH:MM)
input string EndTime = "17:00"; // End Time (HH:MM)
input bool UseRSIExitOnly = true; // Exit on RSI level only
input group "=== Hardening: Risk Management ==="
input double InpDailyLossLimitPct = 3.0;
input double InpMaxLot = 5.0;
input group "=== Capital Allocation Cap ==="
// InpCapEnabled removed — use InpCapAmount=0 to disable
input double InpCapAmount = 0.0;
input double InpCapFloor = 50.0;
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;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.