Pipsgrowth EX09012 MeanReversion
MT5 Expert Advisor (Open Source) · XAUUSD, XAGUSD, EURUSD, USDJPY · M5, M15
Pipsgrowth.com EX09012 RSI_V1_EA — RSI reversal from extreme zones, full 12-layer stack.
Overview
Pipsgrowth EX09012 is a one-indicator reversal system. Where the rest of the MeanReversion family in this catalogue layers candlestick geometry, volume-trap detection, CCI confirmation, or composite scoring, EX09012 stays narrow: a single Relative Strength Index on the closed bar, and a binary crossover against the 30/70 oversold and overbought levels. The strategy buys when the most recent fully-closed RSI(14) crosses up from below 30 — i.e. a bar that closed oversold followed by a bar that closes back inside neutral — and sells on the mirror: a bar that closed above 70 followed by a bar that closes back below 70. The thresholds and the lookback period are user-configurable via InpRSI_Period, InpRSI_Oversold and InpRSI_Overbought, but the default 14/30/70 combination is the canonical RSI reversal setup.
The signal is detected on a new-bar gate inside CheckSignal(). The function reads two RSI values from the last closed bar — bufRSI[0] is the most recent closed value, bufRSI[1] is the one before that — and only fires once per bar via the static g_lastBarTime compare. That gate is what keeps the EA from re-entering the same signal on every tick of a flat bar. Once the direction is decided, OpenPosition() pulls the live ask or bid, computes SL and TP as fixed-point distances, runs an OrderCalcMargin pre-check against free margin, and then attempts the order through a 3-retry loop on TRADE_RETCODE_REQUOTE, _PRICE_CHANGED, _PRICE_OFF and _TIMEOUT, with 100ms sleeps and a RefreshRates() between attempts. The fill mode is resolved once in OnInit by SetProperFillingMode(), which probes the symbol's SYMBOL_FILLING_MODE and picks FOK, IOC or RETURN in that priority order.
Stops are fixed points, not ATR multiples. The default configuration is 500 points for the stop-loss and 1000 points for the take-profit, both computed as price ± points * mysymbol.Point() and rounded to the symbol's digits. At 2:1 reward-to-risk the math is simple — a winning trade captures twice the loss of a losing one — but the distance is constant regardless of how quiet or volatile the market is. A 200-bar quiet session in XAUUSD will get the same 500/1000 point treatment as a 200-bar breakout session, which is by design: this is a point-based EA, not a volatility-aware one. The 5-lot cap (InpMaxLotSize) is what keeps a mis-set InpRiskPercent from over-sizing on a thin account.
What EX09012 does have that simpler RSI bots do not is a two-stage trade-management stack running on every tick in ManageOpenPositions(). Stage one is the break-even: when the position is InpBEStart=250 points in profit, the SL is moved to entry + InpBEOffset=30 points for a long, mirrored for a short. Stage two is the trailing stop: once the position is InpTrailStart=350 points in profit, the SL ratchets to price - InpTrailDistance=150 points behind the current bid (or ask for shorts), and only ever moves forward. The two stages are designed to stack — a 500-point move first locks in break-even-plus-30, then the trailing stop takes over and follows price at a 150-point leash. There is no partial close at 1R like the other MeanReversion EAs use; the position either runs to the 1000-point TP, gets stopped at break-even-or-trail, or hits the 500-point SL on the way out. Both stages call TryModify_EX09012, which re-attempts the SL change 3 times on REQUOTE and TIMEOUT only with 100ms sleeps between.
The risk layer is more thorough than the entry logic. CheckDrawdownLimits() runs on every tick and tracks two numbers: a daily start balance and a running peak equity. If realized daily loss reaches 3% of the start-of-day balance, or if current equity falls 10% from the running peak, g_ddLimitHit is set to true, the EA optionally closes all positions via CloseAllPositions() and no new entries are taken until CheckNewDay() resets the flag at the next midnight server time. The peak-equity logic matters because it catches flash drawdowns that the daily-loss check would miss — a 9% mid-day dip counts as peak - 9%, not as dailyStart - 9%, and the 10% threshold means a single bad session closes the EA before it can dig deeper. InpCloseOnDDLimit=true (the default) means the EA force-closes open positions when the limit fires, not just refuses new entries.
Beneath the basic time filter (InpUseTimeFilter=false by default, 8–20 server hours, Friday close at 20) sits a second-layer hardening module that most MeanReversion EAs in this catalogue do not expose as input. DetectGMTOffset_EX09012() walks back through hourly bars looking for a daylight-saving gap to derive the server's GMT offset; if InpServerGMTOffset is set non-zero the user override is used instead and detection is skipped. InActiveSession_EX09012() then converts server time to GMT and checks whether the current minute is inside the London (InpLondonStartHour=7 to InpLondonEndHour=16) or New York (InpNYStartHour=12 to InpNYEndHour=21) windows, with an InpAvoidAsia block on the 0–7 GMT band. The session gate is what actually decides entry eligibility — the older 8–20 server-hour filter only matters if you set InpUseTimeFilter=true, but the GMT-aware session is always on. IsNewsTime_EX09012() is a generic time-based proxy that flags the ±InpNewsFilterMinutes=15 window around the London and NY session opens. None of this is a real news feed — it is a coarse time fence, off by default, useful only as a sanity filter against the first 15 minutes of a major release.
A capital-allocation cap and floor round out the safety stack. Set InpCapAmount=0 to disable, or set it to your dollar risk budget and IsSafeToTrade_EX09012() will treat MathMin(cap, equity) as effective capital for both lot sizing and the daily-loss check. InpCapFloor=50 blocks entries below $50 equity. InpMinEquityPercent=95 blocks entries when equity has fallen more than 5% from the g_initialBalance captured in OnInit. InpMaxTradesPerDay=50 caps the daily trade count, and InpMaxConsecLosses=3 plus InpCooldownMinutes=30 enforces a 30-minute cool-off after a third consecutive loss — the consecutive-loss counter is incremented inside OnTradeTransaction on every losing DEAL_ENTRY_OUT. None of these are entry filters on signal quality; they are the EA's only defense against a long losing streak.
Pyramiding is wired in but disabled by default. Flip InpEnablePyramid=true and IsGridSafe() will allow a second or third position in the same direction, capped at InpMaxPositions=3, but only if the existing same-direction position is already at least InpMinProfitPoints=200 points in profit. That is the gate: a layered position can only be added when the first layer is green, which prevents the classic grid-martingale pattern of averaging into losers. The function counts same-direction positions in CountPositions() and refuses the pyramid entry if any existing position is in the red. There is no lot multiplier on the pyramid leg, no hedge-against-opposite, and InpEnablePyramid=false keeps the EA flat in one position at a time.
What the EA does not have is worth listing. There is no regime classifier — unlike the EX09004 volume-trap and EX09006 candle-pattern EAs in the same family, EX09012 will fire an RSI cross on a strong trend and let the fixed SL handle the loss. There is no HTF (higher-timeframe) confirmation, no candle-pattern gate, no volume gate, and no volatility gate on the signal bar. There is no partial close and no trailing TP — TP is hit once at the 1000-point level, the SL/TP ratio is the entire edge. The OnTester custom criterion is (net * profitFactor) / (1 + relativeEquityDDPercent) with a 30-trade minimum before the score is returned. That formula penalizes high-drawdown optimizations, which means an MT5 strategy-test pass that has higher net profit but deeper DD will score worse than a smoother alternative with lower net. The optimizer will tend to favor parameter combinations that do not blow up, not the ones that make the most.
For backtesting expectations: on XAUUSD M5 with the default 500/1000 points, expect somewhere between 200 and 600 trades per year depending on the test window's RSI-cross frequency, a hit rate typically in the 40–55% range (RSI crosses are not a high-probability signal alone), and a profit factor in the 1.0 to 1.4 zone. The 2:1 fixed R:R is the only edge the strategy has against randomness; the break-even and trailing stack exist to keep that edge from leaking back. Trades that hit TP will land exactly at 1000 points. Trades that hit the 500-point SL will lose the full distance. Trades that get trailed will close somewhere in between, and the break-even floor means the worst-case after the position is +250 points in profit is a small win, not a loss. The DD protection and the 3% daily-loss cap are what keep an unlucky streak from compounding into a margin call — on a $100 account a 10% peak-to-trough equity drop is $10, which is two losing trades at minimum lot, and the EA will halt before it can chain a third.
Strategy Deep Dive
Each tick OnTradeTransaction updates the realized P&L, daily trade count and consecutive-loss counter, then OnTick refreshes prices, checks the 250-point spread cap, runs CheckTimeFilter, and gates CheckDrawdownLimits. On each new closed bar CheckSignal() reads the last two RSI(14) values: a BUY fires when rsiPrev < 30 && rsiCurrent >= 30, SELL mirror. IsSafeToTrade_EX09012() then layers 10+ checks — capital cap, equity floor, daily loss, 30-minute cooldown after 3 losses, market open, GMT-aware London/NY session, optional ±15-minute news window — before OpenPosition() sizes at 0.5% of effective capital with a 5-lot cap, then sends the order through a 3-retry REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED loop. ManageOpenPositions() runs every tick and applies the two-stage exit (250pt break-even to entry+30, then 350pt trail at 150pt distance); the OnTester returns (net * pf) / (1 + DD) with a 30-trade minimum.
RSI(14) reversal on the most recent closed bar. BUY when the last closed RSI crosses UP from below 30 (oversold exit); SELL when the last closed RSI crosses DOWN from above 70 (overbought exit). The threshold, period, and the one-signal-per-bar gate (g_lastBarTime) are the only signal-side inputs. No regime classifier, no HTF confirmation, no volume or candle-pattern gate — a pure oscillator cross.
Exits run on every tick via ManageOpenPositions(). A one-shot break-even pushes SL to entry + InpBEOffset=30 points after InpBEStart=250 points of profit, and a forward-only trailing stop at InpTrailDistance=150 points behind price activates after InpTrailStart=350 points of profit. The fixed 1000-point TP is the primary profit-taker; the optional Friday close and the DD-limit close via CloseAllPositions() are the safety exits. There is no opposite-signal exit and no partial close — only the SL, TP, break-even and trail decide when the position ends.
Stop-loss is a fixed 500 points from entry (not ATR-derived), set in OpenPosition() as price ± 500 * mysymbol.Point() and rounded to the symbol's digits. The break-even function then ratchets SL to entry + 30 points after +250 points of profit, and a forward-only trailing stop kicks in at +350 points of profit with a 150-point distance behind price. The DD protection layer (3% daily / 10% equity-peak) is the global risk brake that closes everything if the per-trade SL math isn't enough.
Take-profit is a fixed 1000 points from entry, set symmetrically in OpenPosition() as price ± 1000 * mysymbol.Point(). With a 500-point SL this gives a 2:1 reward-to-risk, the entire edge of the strategy. There is no partial close and no trailing TP — TP is hit once at 1000 points, the position is closed at the original 1000-point TP target, and the break-even/trailing stack only ever intervenes on the SL side.
Best on XAUUSD M5 with a $100 minimum balance, broker server time GMT+2 or GMT+3 (so the DetectGMTOffset-derived London/NY session window lines up with real liquidity). Use a low-spread ECN or raw-spread account — the 250-point XAUUSD spread cap is permissive but the strategy has no spread-cost buffer, so a wide-spread retail feed eats directly into the 2:1 R:R. The natural habitat is the London and New York sessions, exactly when the GMT-aware InActiveSession_EX09012() check allows entries. Keep InpUseDDProtection=true (the default) and let the 3% daily / 10% equity-peak limits ride — they are the EA's only real risk brake on an unlucky streak.
Strategy Logic
Pipsgrowth EX09012 MeanReversion — Strategy Logic Analysis (from .mq5 source)
Family: MeanReversion
Magic: 22209012
Version: 2.00
BRIEF:
RSI-based reversal EA. BUY when RSI crosses up from below oversold (30); SELL when RSI crosses down from above overbought (70). Includes breakeven, trailing, drawdown protection, 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:
SetProperFillingMode()OnTradeTransaction()CheckTimeFilter()CheckDrawdownLimits()CheckNewDay()CheckSignal()OpenPosition()IsGridSafe()ManageOpenPositions()CalculateLotSize()NormalizeLot()CountPositions()- ...and 14 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (35 total across 9 groups):
- [=== Identity ===]
InpMagicNumber=22209012// Magic Number - [=== Identity ===]
InpSlippage= 30 // MaxSlippage(points) - [=== Identity ===]
InpMaxSpread= 250 // MaxSpread(points, 0=disabled) - [=== Identity ===]
InpMaxRetries= 3 // Order Retry Attempts - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_09012" // TradeComment - [=== Money Management ===]
InpRiskPercent=0.5// Risk % per Trade - [=== Money Management ===]
InpFixedLot=0.01// FixedLot(if Risk=0) - [=== Money Management ===]
InpMaxLotSize=5.0// Maximum Lot Size Cap - [=== Money Management ===]
InpStopLoss= 500 // StopLoss(points) - [=== Money Management ===]
InpTakeProfit= 1000 // TakeProfit(points) - [=== Strategy Settings ===]
InpRSI_Period= 14 //RSIPeriod - [=== Strategy Settings ===]
InpRSI_Oversold=30.0//RSIOversoldLevel(BUYzone) - [=== Strategy Settings ===]
InpRSI_Overbought=70.0//RSIOverboughtLevel(SELLzone) - [=== Time Filter ===]
InpUseTimeFilter=false// Enable Time Filter - [=== Time Filter ===]
InpStartHour= 8 // StartHour(Server Time) - [=== Time Filter ===]
InpEndHour= 20 // EndHour(Server Time) - [=== Time Filter ===]
InpTradeFriday=true// Trade on Friday - [=== Time Filter ===]
InpFridayCloseHour= 20 // Close All Friday After - [=== Trade Management ===]
InpUseBreakeven=true// Enable Breakeven - [=== Trade Management ===]
InpBEStart= 250 // BEStart(points profit) - [=== Trade Management ===]
InpBEOffset= 30 // BEOffset(points above entry) - [=== Trade Management ===]
InpEnableTrail=true// Enable Trailing Stop - [=== Trade Management ===]
InpTrailStart= 350 // Trail StartDistance(points) - [=== Trade Management ===]
InpTrailDistance= 150 // Trail Distance behind price (points) - [=== Pyramid Settings ===]
InpEnablePyramid=false// Enable Safe Pyramiding - [=== Pyramid Settings ===]
InpMaxPositions= 3 // Max Open Positions - [=== Pyramid Settings ===]
InpMinProfitPoints= 200 // MinProfit(points) for Next Entry - [=== Drawdown Protection ===]
InpUseDDProtection=true// Enable Drawdown Protection - [=== Drawdown Protection ===]
InpMaxDailyLoss=3.0// Max Daily Loss % (0=disabled) - [=== Drawdown Protection ===]
InpMaxEquityLoss=10.0// Max Equity Loss % fromPeak(0=disabled) - [=== Drawdown Protection ===]
InpCloseOnDDLimit=true// Close All When DD Limit Hit - [=== Display ===]
InpShowPanel=true// Show Info Panel - [=== Display ===]
InpPanelX= 10 // Panel X Position - [=== Display ===]
InpPanelY= 30 // Panel Y Position - [=== Capital Allocation Cap ===]
InpCapFloor=50.0// +------------------------------------------------------------------+
// Pipsgrowth EX09012 MeanReversion — Execution Flow (from source analysis)
// Family: MeanReversion
// RSI-based reversal EA. BUY when RSI crosses up from below oversold (30); SELL when RSI crosses down from above overbought (70). Includes breakeven, trailing, drawdown protection, 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 |
|---|---|---|
| InpMagicNumber | 22209012 | Magic Number |
| InpSlippage | 30 | Max Slippage (points) |
| InpMaxSpread | 250 | Max Spread (points, 0=disabled) |
| InpMaxRetries | 3 | Order Retry Attempts |
| InpTradeComment | "Psgrowth.com Expert_09012" | Trade Comment |
| InpRiskPercent | 0.5 | Risk % per Trade |
| InpFixedLot | 0.01 | Fixed Lot (if Risk=0) |
| InpMaxLotSize | 5.0 | Maximum Lot Size Cap |
| InpStopLoss | 500 | Stop Loss (points) |
| InpTakeProfit | 1000 | Take Profit (points) |
| InpRSI_Period | 14 | RSI Period |
| InpRSI_Oversold | 30.0 | RSI Oversold Level (BUY zone) |
| InpRSI_Overbought | 70.0 | RSI Overbought Level (SELL zone) |
| InpUseTimeFilter | false | Enable Time Filter |
| InpStartHour | 8 | Start Hour (Server Time) |
| InpEndHour | 20 | End Hour (Server Time) |
| InpTradeFriday | true | Trade on Friday |
| InpFridayCloseHour | 20 | Close All Friday After |
| InpUseBreakeven | true | Enable Breakeven |
| InpBEStart | 250 | BE Start (points profit) |
| InpBEOffset | 30 | BE Offset (points above entry) |
| InpEnableTrail | true | Enable Trailing Stop |
| InpTrailStart | 350 | Trail Start Distance (points) |
| InpTrailDistance | 150 | Trail Distance behind price (points) |
| InpEnablePyramid | false | Enable Safe Pyramiding |
| InpMaxPositions | 3 | Max Open Positions |
| InpMinProfitPoints | 200 | Min Profit (points) for Next Entry |
| InpUseDDProtection | true | Enable Drawdown Protection |
| InpMaxDailyLoss | 3.0 | Max Daily Loss % (0=disabled) |
| InpMaxEquityLoss | 10.0 | Max Equity Loss % from Peak (0=disabled) |
| InpCloseOnDDLimit | true | Close All When DD Limit Hit |
| InpShowPanel | true | Show Info Panel |
| InpPanelX | 10 | Panel X Position |
| InpPanelY | 30 | Panel Y Position |
| InpCapFloor | 50.0 | +------------------------------------------------------------------+ |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX09012 RSI_V1_EA — RSI reversal from extreme zones, full 12-layer stack."
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
//+------------------------------------------------------------------+
//| INPUT GROUP: Identity |
//+------------------------------------------------------------------+
input group "=== Identity ==="
input int InpMagicNumber = 22209012; // Magic Number
input int InpSlippage = 30; // Max Slippage (points)
input int InpMaxSpread = 250; // Max Spread (points, 0=disabled)
input int InpMaxRetries = 3; // Order Retry Attempts
input string InpTradeComment = "Psgrowth.com Expert_09012"; // Trade Comment
//+------------------------------------------------------------------+
//| INPUT GROUP: Money Management |
//+------------------------------------------------------------------+
input group "=== Money Management ==="
input double InpRiskPercent = 0.5; // Risk % per Trade
input double InpFixedLot = 0.01; // Fixed Lot (if Risk=0)
input double InpMaxLotSize = 5.0; // Maximum Lot Size Cap
input int InpStopLoss = 500; // Stop Loss (points)
input int InpTakeProfit = 1000; // Take Profit (points)
//+------------------------------------------------------------------+
//| INPUT GROUP: Strategy Settings |
//+------------------------------------------------------------------+
input group "=== Strategy Settings ==="
input int InpRSI_Period = 14; // RSI Period
input double InpRSI_Oversold = 30.0; // RSI Oversold Level (BUY zone)
input double InpRSI_Overbought = 70.0; // RSI Overbought Level (SELL zone)
//+------------------------------------------------------------------+
//| INPUT GROUP: Time Filter |
//+------------------------------------------------------------------+
input group "=== Time Filter ==="
input bool InpUseTimeFilter = false; // Enable Time Filter
input int InpStartHour = 8; // Start Hour (Server Time)
input int InpEndHour = 20; // End Hour (Server Time)
input bool InpTradeFriday = true; // Trade on Friday
input int InpFridayCloseHour= 20; // Close All Friday After
//+------------------------------------------------------------------+
//| INPUT GROUP: Trade Management |
//+------------------------------------------------------------------+
input group "=== Trade Management ==="
input bool InpUseBreakeven = true; // Enable Breakeven
input int InpBEStart = 250; // BE Start (points profit)
input int InpBEOffset = 30; // BE Offset (points above entry)
input bool InpEnableTrail = true; // Enable Trailing Stop
input int InpTrailStart = 350; // Trail Start Distance (points)
input int InpTrailDistance = 150; // Trail Distance behind price (points)
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.