P
PipsGrowth
Mean ReversionOpen Source – Free

Pipsgrowth EX13002 RSI_MA

MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1

Pipsgrowth.com EX13002 RSI MA EA — RSI extreme cross + SMA(21) bias pullback, full 12-layer stack.

Overview

Pipsgrowth EX13002 RSI_MA is a contrarian pullback engine that buys the first oversold reaction and shorts the first overbought reaction, but only when the higher-timeframe trend agrees and the market is showing a tradable pulse. It runs on M5 or H1 bars of any XAUUSD or FX-major chart and is, in the source author's words, broker-portable. The compiled logic in Pipsgrowth_com_EX13002.mq5 is a strict 12-layer pipeline — regime detection, signal generation, entry, confirmation, no-trade gating, capital cap, risk, sizing, manage, exit, scaling, OnTester — wired into 30 functions and 19 user inputs plus 15 internal defines. The handle set is tight: iRSI(21) on PRICE_OPEN, iMA(21, MODE_SMA, PRICE_OPEN) on the chart timeframe, iATR(14), iADX(14), iBands(20, 2.0, PRICE_CLOSE) for width context, and an iMA(50, MODE_EMA, PRICE_CLOSE) on H1 for the higher-timeframe trend filter.

The signal itself is a textbook momentum-pullback cross. ComputeSignal reads the closed-bar RSI(21): a long fires when the previous bar printed at or below 100 minus InpRSIThreshold (30 by default) and the current closed bar climbed back above that oversold line with the previous bar's close sitting above the SMA(21) bias line. A short is the mirror — previous bar ≥ InpRSIThreshold (70) crossing back below, with the prior close below SMA(21). When a signal fires the function also computes a confidence score from the RSI excursion past the trigger, capped at 100, which is logged but not currently used to gate entries. The bias-MA guard is what stops the EA from buying every RSI pop in a strong downtrend — both the cross direction and the close-vs-SMA side have to agree.

That signal then has to survive a four-hurdle confirmation stack in ConfirmEntry before any order is built. First, an H1 EMA(50) agreement: the H1 closed bar must be on the same side of the 50-EMA as the proposed trade. Second, a spread filter that not only enforces InpMaxSpreadPoints=30 but also blocks trades when the current spread is more than 2× the rolling 50-tick average stored in g_spread_rolling_sum / g_spread_rolling_count — this is the EA's defence against latency spikes and post-news spread blowouts. Third, a server-time session gate from SESSION_START_HOUR=07:00 to SESSION_END_HOUR=21:00, with Friday from 20:00 onward blocked (close-proximity guard). Fourth, a reward-to-risk check: with the ATR-driven stop distance set to 1.5 × ATR and the take-profit at FULL_TP_R=2.0 × the stop distance, the realised R/R must clear InpMinRR=1.2 — note that the final TP/RR pair is locked in even when the test is satisfied, so this acts as a sanity filter rather than a dynamic target.

Regime is computed once per closed bar in ComputeRegime, which sorts the last 100 ATR(14) values and last 100 Bollinger-Band-width samples to derive the 20th, 80th and 25th percentiles. The classifier reads the current ATR against those percentiles to flag COMPRESS (ATR ≤ 20th percentile AND BB-width ≤ 25th percentile) and EXPAND (ATR ≥ 80th percentile) states, then folds those with ADX thresholds to assign one of seven regimes: STRONG_TREND (ADX ≥ 25), WEAK_TREND (ADX ≥ 18), RANGE, BREAKOUT, COMPRESS, EXPAND, or CHOPPY (ADX < 12). The only regime the entry logic explicitly rejects is CHOPPY; STRONG_TREND, WEAK_TREND, RANGE and EXPAND are all considered tradable. On top of regime, OnTick also enforces InpMinADX=18 as a hard pre-signal gate so the EA does not waste a signal in a directionless market.

Risk and sizing are computed in ComputeLots from effective capital, not raw equity. ComputeEffectiveCapital takes the current equity, subtracts nothing, then optionally caps it to InpCapitalCapAmount if that input is set above zero — at default InpCapitalCapAmount=0 the cap is disabled and effective capital equals equity. The result is cached for 5 seconds (g_eff_capital_last_calc) to keep sizing consistent across a bar but responsive enough to track drawdown. Lots are then solved as (effective capital × InpRiskPercent=0.5%) divided by the loss-per-lot at the current ATR stop distance, finally clamped to the broker's lot step and bounds. ComputeSLTP applies the same 1.5 × ATR stop distance, with a safety pad of stopsLevel + 5 points so the broker never rejects the order as too close, and rounds the result to the symbol tick size via NormalizePrice.

Layer 7 of the no-trade gate is the deal-event tracker TrackRecentDealEvents, which scans history from midnight to now for the EA's own InpMagic-tagged DEAL_ENTRY_OUT / DEAL_ENTRY_INOUT records, sums profit+swap+commission, and feeds two distinct state machines. The first is the daily-loss state machine: when g_today_realized_pnl (computed by ComputeTodayRealizedPnL on the same history scan) drops the account by ≥ InpDailyLossLimitPct=3% of effective capital, all new entries are blocked for the rest of the server day. The second is the consecutive-loss cooldown: every negative deal increments g_consecutive_losses, sets g_cooldown_until = now + 3 × PeriodSeconds (COOLDOWN_BARS_AFTER_LOSS=3), and only a positive deal resets the counter to zero. This is a real three-bar pause on the chart timeframe, not a fixed-seconds cooldown.

Position management runs on every tick in ManageOpenPositions and follows a fixed five-step order. Step 1 is break-even-plus-2 lock: once price has moved in favour by InpBE_RMultiple=1.0R, the stop is moved to entry plus BE_OFFSET_POINTS=2 ticks. Step 2 is an ATR trailing stop at InpTrailATRMult=2.5 × ATR that only ratchets in the favourable direction, only fires when the new stop is at least one tick beyond the current stop, and only modifies when the remaining distance to price exceeds the broker's stops level. Step 3 is a partial take-profit at PARTIAL_TP_R=1.0R closing PARTIAL_TP_RATIO=50% of the position — PartialAlreadyTaken is a no-op stub so this branch effectively re-fires every time ManageOpenPositions runs after TP1, which can over-close; in practice the partial-close path is only safe when volume still allows a non-zero remainder. Step 4 is a time exit at MAX_BARS_IN_TRADE=200 bars. Step 5 is the opposite-signal exit: a long is closed when RSI re-crosses up through OB, a short when RSI re-crosses down through OS.

Two more behaviours are worth highlighting. First, InpDryRun defaults to true — the EA is shipped in a logged-only mode where ComputeLots, ComputeSLTP and SendOrder all run normally but SendOrder short-circuits to PrintFormat('DRYRUN signal=...') and returns success. The only way to go live is to flip InpDryRun to false in the inputs dialog. Second, InpKillSwitch=true is a soft stop: when on, NoTradeGate returns true on the very first check, which blocks new entries but leaves the manage-open loop running so existing positions still get their break-even, trail, partial and time-exit treatment. SendOrder itself retries once on REQUOTE, PRICE_OFF or TIMEOUT before declaring failure. Close / close-partial / modify paths use the per-EA retry helpers TryClose_EX13002, TryClosePartial_EX13002 (both: 3 attempts, 200ms Sleep, retry on REQUOTE / TIMEOUT / PRICE_OFF / PRICE_CHANGED, break on any other retcode) and TryModify_EX13002 (3 attempts, 100ms Sleep, retry on REQUOTE / TIMEOUT only — PRICE_CHANGED and PRICE_OFF break the loop, a deliberate asymmetry with the close helpers).

OnTester returns 0 when the strategy traded fewer than 30 times — useful for filtering out under-sampled runs in the optimiser — and otherwise returns (net × profitFactor) / (1 + equity-drawdown-percent). When the drawdown comes back at zero or negative the formula falls back to the simpler net × pf. The OnTester formula is the only way the strategy self-evaluates during MT5's genetic pass; it explicitly rewards trades that produce profit per unit of drawdown, not raw net.

The backtest profile of this EA on XAUUSD M5 is straightforward: expect a low-to-moderate trade frequency dominated by the post-pullback continuation trades, occasional re-entries on the same bar if the signal reverses quickly, and visible drawdown clusters during the COMPRESS / CHOPPY regimes that pass the spread and ADX gates but ultimately don't trend. The PYRAMID_ENABLED=false define is a hard wall — there is no martingale, no grid, no averaging. The MAX_SYMBOL_EXPOSURE=1 cap means you cannot run a hedge or grid of this EA on the same symbol from the same terminal; either run it on a separate magic on a different symbol, or accept the one-position cap. The EA is suitable for accounts from $100 upward, but a $500+ balance gives the daily-loss state machine enough headroom to actually engage on a losing streak. Run on an ECN/RAW-spread broker with sub-30-point typical gold spreads, server time aligned so that the 07:00–21:00 server window overlaps the London and New York sessions, and verify the broker's GMT offset matches your chart's session labels before going live.

Strategy Deep Dive

Each tick, the EA first calls TrackRecentDealEvents to scan today's history for its own magic-tagged DEAL_ENTRY_OUT/INOUT records, then runs ManageOpenPositions across every open position with a 1.5×ATR stop, the +1R break-even-plus-2 lock, the 2.5×ATR trail, the 1R partial, the 200-bar time exit, and the opposite-signal exit layered in that fixed order. Once a new bar opens, OnTick calls ComputeRegime to derive the 7-state regime from 100-bar ATR and Bollinger-width percentiles plus ADX, rejects CHOPPY outright and any bar where ADX<18, then ComputeSignal reads the closed-bar RSI(21) and SMA(21) to detect the cross-from-extreme-with-bias setup. ConfirmEntry then enforces the H1-EMA(50) agreement, the ≤30-point spread cap with the 2× rolling-50-tick-avg guard, the 07:00–21:00 server-time session window, and the 1.2 R/R minimum; only then does ComputeLots size the order at 0.5% of effective capital per trade and SendOrder either prints a DRYRUN log line or calls trade.PositionOpen with the ATR-derived SL and the 2R TP. InpDryRun defaults to true, so the EA is shipped in logged-only mode until the user flips it off.

Entry Signal

Long entry fires when the closed-bar RSI(21) climbs back above the oversold level (100 − InpRSIThreshold, default 30) from a value at or below that level on the previous bar, with the previous close sitting above the SMA(21) bias line. A short is the mirror: previous RSIInpRSIThreshold=70 crossing back below, with the prior close below SMA(21). The signal then has to pass a four-hurdle confirmation stack — H1 EMA(50) agreement, spread ≤ 30 points and not > 2× the rolling 50-tick average, server-time window 07:00–21:00 (Friday closed from 20:00), and a 1.2 R/R floor — before any order is sent.

Exit Signal

Five-step exit pipeline runs on every tick: (1) break-even-plus-2 lock at +1R, (2) ATR 2.5× trailing stop that only ratchets in the favourable direction, (3) 50% partial close at +1R, (4) time exit at 200 bars, and (5) opposite-signal exit — a long is closed when RSI re-crosses above OB, a short when RSI re-crosses below OS.

Stop Loss

Initial stop is 1.5 × ATR(14) from entry, rounded to the symbol tick size, with a broker-stops-level + 5-point safety pad to prevent order rejection. Once price has moved 1R in favour the stop moves to entry + 2 points (BE lock); thereafter a 2.5 × ATR trailing stop ratchets in the favourable direction only. There is no per-trade hard stop beyond the trail; the global safety nets are the 3% daily-loss cap on effective capital and a 3-bar cooldown after a losing deal.

Take Profit

Final take-profit is 2.0 × the initial stop distance (2R), with a partial 50% close at +1R. The 2R target is the realised R/R that the ConfirmEntry filter checks against InpMinRR=1.2 before any order is sent, so any trade that fires is guaranteed to clear that floor. The 1R partial and 2R final pair are hard-coded into the SL/TP order ticket — not a trailing TP.

Best For

Minimum recommended balance: $100, but $500+ gives the 3% daily-loss state machine real headroom on a losing streak. The EA is broker-portable across XAUUSD and the FX majors — the source header explicitly lists "FX Majors, Gold/Metals" — so choose an ECN/RAW-spread account with sub-30-point typical gold spread and sub-2-point FX spread, server time aligned so the 07:00–21:00 server window overlaps the London and New York sessions, and verify the broker's GMT offset matches the chart's session labels before going live. InpDryRun is true by default — flip it off only after a successful forward-test run on a demo account of the same balance.

Strategy Logic

Pipsgrowth EX13002 RSI_MA — Strategy Logic Analysis (from .mq5 source)

Family: RSI_MA Magic: 22213002 Version: 2.00

BRIEF: RSI crosses back from extreme (OS for buys, OB for shorts) while price is on the correct side of an SMA(21) => momentum- pullback entry; mirror for shorts. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • CopyBufSafe()
  • CopyCloseSafe()
  • CopyCloseSafeTF()
  • GetStopsLevelPrice()
  • NormalizePrice()
  • ClampVolume()
  • CheckMargin()
  • CurrentSpreadPoints()
  • ComputeEffectiveCapital()
  • ComputeTodayRealizedPnL()
  • TodayLossRatio()
  • ComputeRegime()
  • ...and 18 more

INTERNAL CONSTANTS (15 total):

  • MA_TF = PERIOD_CURRENT // Signal MA timeframe (chart TF)
  • MA_METHOD = MODE_SMA // Slow trend-bias MA method
  • MA_APPLIED_PRICE = PRICE_OPEN // Match source
  • RSI_APPLIED_PRICE = PRICE_OPEN // Match source
  • HTF_TREND_TF = PERIOD_H1 // Higher-timeframe trend agreement
  • HTF_EMA_PERIOD = 50 // HTF EMA period
  • PARTIAL_TP_RATIO = 0.50 // Close 50% at TP1
  • PARTIAL_TP_R = 1.0 // TP1 = 1R
  • FULL_TP_R = 2.0 // Final TP = 2R
  • BE_TRIGGER_R = 1.0 // Move to BE at +1R
  • BE_OFFSET_POINTS = 2 // Lock +2 pts beyond entry
  • MAX_SYMBOL_EXPOSURE = 1 // Max positions per symbol
  • PYRAMID_MAX_LEVELS = 3 // hard-capped
  • SESSION_START_HOUR = 7 // Broker server time
  • NEWS_BLACKOUT_MINUTES = 0 // Manual news window minutes (0 = off)

INPUT PARAMETERS (19 total across 6 groups):

  • [=== Identity ===] InpMagic = 22213002 // Magic number (unique per EA)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_13002" // Trade comment
  • [=== Identity ===] InpDryRun = true // Dry-run mode (no live orders) (—)
  • [=== Identity ===] InpKillSwitch = false // Kill switch (true=close-only) (—)
  • [=== Capital Allocation Cap ===] InpCapitalCapAmount = 0.0 // Cap amount in account currency ($)
  • [=== Capital Allocation Cap ===] InpCapitalCapFloor = 50.0 // Floor below which new trades blocked ($)
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (% of effective capital)
  • [=== Risk & Sizing ===] InpDailyLossLimitPct = 3.0 // Daily loss limit (% of effective capital)
  • [=== Risk & Sizing ===] InpMaxConcurrent = 1 // Max concurrent positions (—)
  • [=== Risk & Sizing ===] InpMinRR = 1.2 // Minimum reward:risk to take entry (—)
  • [=== Signal (RSI + MA) ===] InpRSIPeriod = 21 // RSI period (bars)
  • [=== Signal (RSI + MA) ===] InpRSIThreshold = 70 // RSI extreme threshold (e.g. 70 => OB, 30 OS)
  • [=== Signal (RSI + MA) ===] InpMAPeriod = 21 // Slow MA period (bars)
  • [=== Regime / Confirm / Exec ===] InpMinADX = 18.0 // Minimum ADX for entry (—)
  • [=== Regime / Confirm / Exec ===] InpMaxSpreadPoints = 30 // Max allowed spread (points)
  • [=== Regime / Confirm / Exec ===] InpSlippagePoints = 10 // Order slippage/deviation (points)
  • [=== Exit / Manage ===] InpATR_SLMult = 1.5 // ATR multiplier for initial SL (xATR)
  • [=== Exit / Manage ===] InpBE_RMultiple = 1.0 // Break-even trigger (x R-multiple)
  • [=== Exit / Manage ===] InpTrailATRMult = 2.5 // ATR trailing-stop multiplier (xATR)
Pseudocode
// Pipsgrowth EX13002 RSI_MA — Execution Flow (from source analysis)
// Family: RSI_MA
// RSI crosses back from extreme (OS for buys, OB for shorts) while price is on the correct side of an SMA(21) => momentum- pullback entry; mirror for shorts. 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:
M5H1

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
InpMagic22213002Magic number (unique per EA)
InpTradeComment"Psgrowth.com Expert_13002"Trade comment
InpDryRuntrueDry-run mode (no live orders) (—)
InpKillSwitchfalseKill switch (true=close-only) (—)
InpCapitalCapAmount0.0Cap amount in account currency ($)
InpCapitalCapFloor50.0Floor below which new trades blocked ($)
InpRiskPercent0.5Risk per trade (% of effective capital)
InpDailyLossLimitPct3.0Daily loss limit (% of effective capital)
InpMaxConcurrent1Max concurrent positions (—)
InpMinRR1.2Minimum reward:risk to take entry (—)
InpRSIPeriod21RSI period (bars)
InpRSIThreshold70RSI extreme threshold (e.g. 70 => OB, 30 OS)
InpMAPeriod21Slow MA period (bars)
InpMinADX18.0Minimum ADX for entry (—)
InpMaxSpreadPoints30Max allowed spread (points)
InpSlippagePoints10Order slippage/deviation (points)
InpATR_SLMult1.5ATR multiplier for initial SL (xATR)
InpBE_RMultiple1.0Break-even trigger (x R-multiple)
InpTrailATRMult2.5ATR trailing-stop multiplier (xATR)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX13002.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX13002 RSI MA EA — RSI extreme cross + SMA(21) bias pullback, full 12-layer stack."

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

//================== NON-INPUT TUNABLES (defines) ===================
#define MA_TF                   PERIOD_CURRENT  // Signal MA timeframe (chart TF)
#define MA_METHOD               MODE_SMA        // Slow trend-bias MA method
#define MA_APPLIED_PRICE        PRICE_OPEN      // Match source
#define RSI_APPLIED_PRICE       PRICE_OPEN      // Match source
#define HTF_TREND_TF            PERIOD_H1       // Higher-timeframe trend agreement
#define HTF_EMA_PERIOD          50              // HTF EMA period
#define ATR_PERIOD              14
#define ADX_PERIOD              14
#define BB_PERIOD               20
#define BB_DEVIATION            2.0
#define ATR_PCTILE_LOOKBACK     100
#define BB_PCTILE_LOOKBACK      100
#define REGIME_COMPRESS_PCTILE  20.0
#define REGIME_EXPAND_PCTILE    80.0
#define REGIME_STRONG_ADX       25.0
#define REGIME_WEAK_ADX         18.0
#define REGIME_BB_NARROW_PCT    25.0
#define PARTIAL_TP_RATIO        0.50            // Close 50% at TP1
#define PARTIAL_TP_R            1.0             // TP1 = 1R
#define FULL_TP_R               2.0             // Final TP = 2R
#define BE_TRIGGER_R            1.0             // Move to BE at +1R
#define BE_OFFSET_POINTS        2               // Lock +2 pts beyond entry
#define MAX_BARS_IN_TRADE       200
#define MAX_SYMBOL_EXPOSURE     1               // Max positions per symbol
#define COOLDOWN_BARS_AFTER_LOSS 3
#define MAX_DAILY_DRAWDOWN_CACHE_MS 60000
#define PYRAMID_ENABLED         false
#define PYRAMID_MAX_LEVELS      3               // hard-capped
#define PYRAMID_MIN_ATR_SPACING 1.0
#define SESSION_START_HOUR      7               // Broker server time
#define SESSION_END_HOUR        21
#define NEWS_BLACKOUT_MINUTES   0               // Manual news window minutes (0 = off)
#define SPREAD_ROLLING_LOOKBACK 50

enum ENUM_REGIME
  {
   REGIME_STRONG_TREND = 0,
   REGIME_WEAK_TREND   = 1,
   REGIME_RANGE        = 2,
   REGIME_BREAKOUT     = 3,
   REGIME_COMPRESS     = 4,
   REGIME_EXPAND       = 5,
   REGIME_CHOPPY       = 6
  };

//================== INPUTS (20 total) ==============================

Full source code available on download

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

Tags:ex13002rsi_mapipsgrowthfreemt5xauusd

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