Pipsgrowth EX13008 RSI_MA
MT5 Expert Advisor (Open Source) · XAUUSD · M1, H1
Pipsgrowth.com EX13008 RSI_RECOVERY_SOURCE_CODE — RSI zone recovery with basket profit close, full 12-layer stack.
Overview
Pipsgrowth EX13008 is a basket-closure mean-reversion bot whose only working signal is a single RSI cross above a configurable oversold threshold, with the entire position-management logic delegated to a single CloseAllBuySell() call when aggregate basket profit reaches a target. The indicator stack is the leanest in the EX13 family: one iRSI handle created in OnInit() with the period and applied price coming from the RsiPeriod=14 input and RsiAppliedPrice=1 (=PRICE_CLOSE) input, and a synthetic timeframe map produced by MapTimeframeInt() that translates the integer 1..7 in RsiTimeframe into PERIOD_M1..PERIOD_D1. OnTick() copies the last two completed-bar RSI values into the Rsi[] buffer, then checks the cross: a buy fires when the prior bar was strictly below the buyzone input (default 35) and the just-closed bar is above it; a sell fires when the prior bar was strictly above the sellzone input (default 100) and the just-closed bar is below it. Because RSI is mathematically bounded to [0, 100], the sell branch is effectively inert at the default sellzone=100 unless the operator actively lowers the threshold, and the EA runs as a long-only reversion system out of the box.
The trade-management design is the most distinctive feature of EX13008. TryBuy_EX13008() and TrySell_EX13008() submit the MqlTradeRequest with sl=0, tp=0, and a market order price — there is no protective stop and no profit target on the order ticket itself. Instead, drawZoneLevel() paints four horizontal lines on the chart the moment a position is filled: ZONE_H and ZONE_L in cyan mark the entry price and entry-minus-2000-points, while ZONE_T_H and ZONE_T_L in blue mark entry-plus-4000-points and entry-minus-2000-points-minus-4000-points. The names suggest a recovery-zone system, but the in-code variable is a visualization aid only — there is no averaging, no martingale progression, no grid, and no per-trade partial close. GetPositionProfit() walks PositionsTotal() on every tick, sums POSITION_PROFIT for every open ticket on the symbol and magic, and CloseAllBuySell() is invoked the moment that basket sum reaches CloseWhenInProfit (default $20). The basket-close loop calls TryClose_EX13008() up to ten times per ticket before giving up, and TryClose_EX13008() itself does three CTrade.PositionClose attempts with a 200ms Sleep between REQUOTE, TIMEOUT, PRICE_OFF, and PRICE_CHANGED responses before breaking on any other retcode.
Lot sizing is fixed at LotSize=0.01. TryBuy_EX13008() and TrySell_EX13008() clamp the requested volume to the broker's SYMBOL_VOLUME_MIN, SYMBOL_VOLUME_MAX, and SYMBOL_VOLUME_STEP before submitting, and refuse the trade if OrderCalcMargin() reports a required margin greater than ACCOUNT_MARGIN_FREE. The 3-attempt outer loop in OnTick() — wrapping both the margin pre-check and the CTrade submission — adds a 500ms Sleep between retries, so the effective retry cadence is more forgiving than the inner 200ms used in TryClose_EX13008(). The whole EA was clearly assembled with a copy-paste shortcut: MapTimeframeInt() and MapAppliedPriceInt() appear four times each in the source (lines 40-67, 74-101, 110-137, 145-172, 179-206, 213-240) and the body of each copy is identical. The duplication is harmless because the function bodies are byte-for-byte the same, but it is a code-hygiene tell that this is a small, hand-built utility rather than a templated multi-strategy composite.
The safety layer is the standard EX13-family ten-gate IsSafeToTrade_EX13008() chain evaluated on every tick: an InpCapAmount cap stop (returns false once equity reaches the configured ceiling, disabled by default at 0.0), an InpCapFloor=50 equity minimum, a 95%-of-initial-balance kill switch anchored to g_initialBalance captured at OnInit, a 3% daily loss limit, a 6% weekly loss limit computed as 2x the daily cap on EffectiveCapital_EX13008(), a 3-consecutive-losses trigger that arms a 30-minute g_cooldownUntil wall-clock gate, a 50-trades-per-day ceiling on g_tradesToday, an IsMarketOpen_EX13008() weekend gate (closed Saturday, Sunday before 22 GMT, Friday from 21 GMT), an InActiveSession_EX13008() filter that allows London 7-16 GMT and New York 12-21 GMT while InpAvoidAsia=true suppresses the Asian 0-7 GMT window, and an optional InpNewsFilter that pauses trading within InpNewsFilterMinutes=15 of the London or New York open. OnTradeTransaction() filters incoming DEAL_TRANSACTION_DEAL_ADD events by the magic 22213008 and the DEAL_ENTRY_OUT direction, accumulates profit+swap+commission into g_realizedToday and g_realizedWeek, and increments g_consecLosses on every negative-pnl close. UpdateDailyCounters_EX13008() resets the daily counters and the loss streak at the first tick of a new server date.
The DetectGMTOffset_EX13008() helper implements the same DST-gap scan used by the rest of the family: if the operator has set InpServerGMTOffset to a non-zero value, that integer is returned as-is; otherwise the function walks 100 H1 bars looking for a >2-hour gap, then back-computes the GMT offset from the gap bar's hour field. ServerToGMT_EX13008() subtracts g_gmtOffset*3600 seconds from TimeCurrent() so that the session, news, and market-open checks all operate in real GMT regardless of the broker's server timezone. OnTester() returns the canonical (net * profit_factor) / (1 + relative_drawdown_percent) score when the test produced at least 30 trades and both pf and dd are positive, and 0 otherwise — a formula that rewards net profit and consistency while penalising deep drawdowns. The OnInit() guards are: RSI handle must succeed, magic must be non-zero, LotSize must be > 0, InpCapAmount==0 OR InpCapFloor<InpCapAmount, InpMaxTradesPerDay must be > 0, and InpMaxLot must be > 0.
The most operationally important quirk is the sellzone=100 default. RSI cannot exceed 100, so the condition Rsi[1] > sellzone && Rsi[0] < sellzone is unreachable out of the box and the bot only ever buys. Traders who want symmetry need to drop sellzone to a value like 65 or 70 so that the upper-threshold cross becomes physically possible. The second quirk is the four chart lines: on a fresh bar the ZONE_H/ZONE_L/ZONE_T_H/ZONE_T_L objects are overwritten by ObjectCreate(0,...,OBJ_HLINE,...) every time a new position opens, so the prior trade's zone markers are not preserved. Operators who want a clean post-trade chart need to call ObjectDelete(0, ZONE_L) etc. on the basket close, which the current code does not do. The third quirk is that the trade request passes no SL and no TP, so the only thing standing between an open position and a margin call is the basket profit target and the safety gates — a sustained adverse move will eat equity until the daily loss limit or the equity-floor kill switch fires.
Strategy Deep Dive
OnTick() runs UpdateDailyCounters_EX13008() to reset the daily P&L counter and the loss streak at the date rollover, then evaluates the ten-gate IsSafeToTrade_EX13008() permission chain (cap stop, equity floor, 95% initial-balance kill, 3% daily loss, 6% weekly loss, 3-consec-loss 30-min cooldown, 50-trade daily cap, weekend hours, London/NY session filter with Asia avoidance, optional news filter). On the first tick of a new bar, the iRSI(14, RsiAppliedPrice) handle is sampled into Rsi[] via CopyBuffer() and a cross check fires TryBuy_EX13008() or TrySell_EX13008() with sl=0, tp=0, and a market price — both wrappers clamp the lot to the broker volume step, refuse on insufficient margin, and retry three times on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED with a 500ms Sleep. A successful fill triggers drawZoneLevel() to paint ZONE_H/ZONE_L (cyan) and ZONE_T_H/ZONE_T_L (blue) horizontal lines on the chart. GetPositionProfit() is evaluated every tick and CloseAllBuySell() is invoked the moment the basket sum reaches CloseWhenInProfit. OnTradeTransaction() updates the daily/weekly realized PnL and the consec-loss counter used by the safety gates; OnTester() returns the standard (net * pf) / (1 + dd) score.
EX13008 fires a long entry the moment a single RSI(14, PRICE_CLOSE) — evaluated on the user-selected RsiTimeframe — crosses upward through the buyzone input (default 35), i.e. previous bar below 35 and current bar above 35. The mirrored short signal requires Rsi[1] > sellzone and Rsi[0] < sellzone, but because sellzone defaults to 100 and RSI is mathematically bounded to [0, 100], that branch is unreachable out of the box and the EA only opens longs unless the operator lowers sellzone to a realistic level (e.g. 65-70). Each new bar triggers a fresh evaluation; entries occur at most once per bar, on the first tick of that bar.
There are no per-trade stop-loss or take-profit tickets. EX13008 exits exclusively by closing the entire basket of same-magic positions on the symbol the moment GetPositionProfit() — which sums POSITION_PROFIT across all open tickets — reaches or exceeds CloseWhenInProfit (default $20). CloseAllBuySell() walks PositionsTotal() in reverse, filters by symbol and magic, and calls TryClose_EX13008() up to ten times per ticket; TryClose_EX13008() itself does three CTrade.PositionClose attempts with 200ms Sleep between REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED and breaks on any other retcode. The four chart-zone horizontal lines (ZONE_H/ZONE_L/ZONE_T_H/ZONE_T_L) are not exits — they are visual markers and do not get deleted on close.
EX13008 ships with no broker-side stop-loss. The protective ceiling is the basket profit target — if the basket sum never reaches CloseWhenInProfit, the position is held indefinitely until one of the safety gates fires: the 3% daily loss limit, the 6% weekly loss limit, the 95% initial-balance kill switch, the equity floor, or the 30-minute cooldown after 3 consecutive losses. The four cyan/blue chart lines drawn at entry are visual aids only and are not protective orders.
There is no per-trade take-profit. The TP is the basket-wide profit target CloseWhenInProfit (default $20 USD) measured on PositionProfit across every open same-magic ticket on the symbol. When the sum reaches that dollar threshold, CloseAllBuySell() fires and unwinds the entire basket. There is no fractional close, no scaling-out, and no per-position TP — one number, one exit decision, all tickets at once.
Recommended balance: $100 minimum, $500-$2,000 practical. Best on XAUUSD M1 (the default RsiTimeframe=1 maps to PERIOD_M1) or H1, on a 5-digit broker with sub-30-point spread and FOK or IOC fill support, ideally ECN/RAW. Keep the London 7-16 GMT and New York 12-21 GMT session filter on, leave InpAvoidAsia=true on (RSI reversion signals on XAUUSD are noisy in Asia), and never override the 95% equity-floor kill or the 3% daily / 6% weekly loss caps. Default the EA is long-only because sellzone=100 is unreachable — drop sellzone to 65-70 if you want symmetry. Tune buyzone (default 35) lower for fewer, more selective buys; raise CloseWhenInProfit to widen the basket target and reduce churn. This is a low-frequency visual teaching tool, not a high-frequency scalper — pair it with manual H1 context, not with automated basket-management scripts.
Strategy Logic
Pipsgrowth EX13008 RSI_MA — Strategy Logic Analysis (from .mq5 source)
Family: RSI_MA
Magic: 22213008
Version: 2.00
BRIEF:
RSI Recovery zone EA. Opens a trade when RSI crosses the buy/sell zone threshold, then draws a recovery zone around the entry and closes all positions once the basket reaches a set profit target. Fixed lot sizing (no martingale progression). Full 12-layer stack: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
drawZoneLevel()CloseAllBuySell()GetPositionProfit()OnTradeTransaction()EffectiveCapital_EX13008()DetectGMTOffset_EX13008()ServerToGMT_EX13008()IsMarketOpen_EX13008()InActiveSession_EX13008()IsNewsTime_EX13008()IsSafeToTrade_EX13008()UpdateDailyCounters_EX13008()- ...and 3 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (21 total across 5 groups):
- [=== Identity ===]
InpMagicNumber=22213008// Magic Number - [=== Strategy Parameters ===]
LotSize=0.01// Lot Size - [=== Strategy Parameters ===]
CloseWhenInProfit= 20 // Close all trades when in profit of x $ - [===
RSIParameters ===]RsiTimeframe= 1 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) - [===
RSIParameters ===]RsiAppliedPrice= 1 // Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted) - [=== Hardening: Risk Management ===]
InpDailyLossLimitPct=3.0// Daily loss limit (% of effective capital) - [=== Hardening: Risk Management ===]
InpMaxLot=5.0// Hard lot cap per trade - [=== Hardening:
GMTSessions ===]InpServerGMTOffset= 0 // ServerGMToffset hours (0=auto-detect) - [=== Hardening:
GMTSessions ===]InpLondonStartHour= 7 // London session start (GMT) - [=== Hardening:
GMTSessions ===]InpLondonEndHour= 16 // London session end (GMT) - [=== Hardening:
GMTSessions ===]InpNYStartHour= 12 // New York session start (GMT) - [=== Hardening:
GMTSessions ===]InpNYEndHour= 21 // New York session end (GMT) - [=== Hardening:
GMTSessions ===]InpAvoidAsia=true// Avoid Asian session - [=== Hardening:
GMTSessions ===]InpAsiaStartHour= 0 // Asian session start (GMT) - [=== Hardening:
GMTSessions ===]InpAsiaEndHour= 7 // Asian session end (GMT) - [=== Hardening:
GMTSessions ===]InpNewsFilter=false// Avoid trading near news session opens - [=== Hardening:
GMTSessions ===]InpNewsFilterMinutes= 15 // Minutes to avoid around news - [=== Hardening:
GMTSessions ===]InpMaxTradesPerDay= 50 // Maximum trades per day - [=== Hardening:
GMTSessions ===]InpMinEquityPercent=95.0// Stop trading if equity < this % of initial balance - [=== Hardening:
GMTSessions ===]InpCooldownMinutes= 30 // Cooldown minutes after consec losses - [=== Hardening:
GMTSessions ===]InpMaxConsecLosses= 3 // Max consecutive losses before cooldown
// Pipsgrowth EX13008 RSI_MA — Execution Flow (from source analysis)
// Family: RSI_MA
// RSI Recovery zone EA. Opens a trade when RSI crosses the buy/sell zone threshold, then draws a recovery zone around the entry and closes all positions once the basket reaches a set profit target. Fixed lot sizing (no martingale progression). Full 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 | 22213008 | Magic Number |
| LotSize | 0.01 | Lot Size |
| CloseWhenInProfit | 20 | Close all trades when in profit of x $ |
| RsiTimeframe | 1 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) |
| RsiAppliedPrice | 1 | Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted) |
| InpDailyLossLimitPct | 3.0 | Daily loss limit (% of effective capital) |
| InpMaxLot | 5.0 | Hard lot cap per trade |
| InpServerGMTOffset | 0 | Server GMT offset hours (0=auto-detect) |
| InpLondonStartHour | 7 | London session start (GMT) |
| InpLondonEndHour | 16 | London session end (GMT) |
| InpNYStartHour | 12 | New York session start (GMT) |
| InpNYEndHour | 21 | New York session end (GMT) |
| InpAvoidAsia | true | Avoid Asian session |
| InpAsiaStartHour | 0 | Asian session start (GMT) |
| InpAsiaEndHour | 7 | Asian session end (GMT) |
| InpNewsFilter | false | Avoid trading near news session opens |
| InpNewsFilterMinutes | 15 | Minutes to avoid around news |
| InpMaxTradesPerDay | 50 | Maximum trades per day |
| InpMinEquityPercent | 95.0 | Stop trading if equity < this % of initial balance |
| InpCooldownMinutes | 30 | Cooldown minutes after consec losses |
| InpMaxConsecLosses | 3 | Max consecutive losses before cooldown |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX13008 RSI_RECOVERY_SOURCE_CODE — RSI zone recovery with basket profit close, full 12-layer stack."
#include <Trade\Trade.mqh>
#include <Trade/Trade.mqh>
CTrade obj_Trade;
string ZONE_L = "ZL";
string ZONE_H ="ZH";
string ZONE_T_H = "ZTH";
string ZONE_T_L ="ZTL";
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_APPLIED_PRICE MapAppliedPriceInt(int ap)
{
switch(ap)
{
case 1: return PRICE_CLOSE;
case 2: return PRICE_OPEN;
case 3: return PRICE_HIGH;
case 4: return PRICE_LOW;
case 5: return PRICE_MEDIAN;
case 6: return PRICE_TYPICAL;
case 7: return PRICE_WEIGHTED;
default: return PRICE_CLOSE;
}
}
ENUM_TIMEFRAMES g_RsiTimeframe = PERIOD_H1;
ENUM_APPLIED_PRICE g_RsiAppliedPrice = PRICE_CLOSE;
input group "=== Identity ==="
input int InpMagicNumber = 22213008; // Magic Number
input string InpTradeComment = "Psgrowth.com Expert_13008";
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;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.