P
PipsGrowth
Mean ReversionOpen Source – Free

Pipsgrowth EX13001 RSI_MA

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

Pipsgrowth.com EX13001 RSI MA V2 EA — RSI pullback + MA bias trend EA, full 12-layer stack.

Overview

EX13001 RSI_MA is a mean-reversion pullback EA that hunts for the moment RSI(21) snaps back through its extreme line while the slow moving average still confirms the prevailing trend direction. The setup is small in count — one oscillator, one bias filter, one higher-timeframe agreement, one regime classifier — but the gate that decides whether a signal becomes a trade is wider than the signal itself, stacking a 7-state market classifier, an ATR-anchored R/R check, a session filter, a daily loss circuit breaker, and a three-bar post-loss cooldown before the order is ever sent. The order it does send is then managed in three layers: a 50% partial close at +1R, a break-even-plus lock at +1R, an ATR trailing stop that ratchets behind price, a 200-bar time-based exit, and a hard opposite-signal exit when RSI walks back to the other extreme.

The signal core sits in ComputeSignal(). It pulls two RSI bars from the chart timeframe and one MA bar. The long trigger requires that the previous bar's RSI was at or below the oversold line (100 − InpRSIThreshold, i.e. 30 by default), the current bar's RSI is above that line, AND the previous bar's close finished above the slow MA(21) — proving the pullback is happening into an uptrend, not into a falling market. The short trigger is the mirror. When the cross fires, the function assigns a confidence value based on how far RSI has already overshot the threshold (50 + 2 × excursion, capped at 100) and tags the reason for the audit log.

Confirmation runs in ConfirmEntry() and adds four extra hurdles. First, the H1 EMA(50) must agree — for a long signal the H1 close must be above the H1 EMA, for a short signal it must be below. The H1 timeframe is hard-coded via the HTF_TREND_TF define and the EMA(50) handle is created on OnInit. Second, the current spread must be below InpMaxSpreadPoints (30 by default) AND not more than 2× the rolling 50-tick spread average that UpdateSpreadRolling() keeps in a running sum. Third, the broker-server hour must be inside the 07:00–21:00 window and the regime must not be CHOPPY. Fourth, the projected R/R must be at least InpMinRR (1.2) — using SL distance = 1.5 × ATR(14) and TP distance = 2 × SL.

The regime classifier in ComputeRegime() is the most distinctive piece of plumbing in the EA. It does not lean on a single trendiness metric. It pulls 102 bars of ATR, 102 bars of Bollinger Band width, and 3 bars of ADX, then computes two ATR percentiles (20th and 80th) and one BB-width percentile (25th) over the last 100 bars. From those it derives boolean flags: COMPRESS (ATR ≤ 20th-pctile AND BB-width ≤ 25th-pctile), EXPAND (ATR ≥ 80th-pctile), then folds them with ADX bands of 25 (strong) and 18 (weak). The output enum has seven states — STRONG_TREND, WEAK_TREND, RANGE, BREAKOUT, EXPAND, COMPRESS, CHOPPY — and the entry path explicitly rejects CHOPPY at two places (OnTick pre-signal and ConfirmEntry). The classifier runs every closed bar regardless of whether a signal exists, so the gate has fresh context by the time ComputeSignal() returns.

Risk and capital control run in two separate functions. ComputeEffectiveCapital() returns the account equity, capped at InpCapitalCapAmount when set; the cap can be set to zero to disable. If the cap is enabled and effective capital drops below InpCapitalCapFloor (50 by default), NoTradeGate() refuses to open new positions. ComputeLots() then sizes each trade off the projected SL distance: risk_money = effective_capital × 0.5%, loss_per_lot = (sl_distance / tickSize) × tickValue, lots = risk_money / loss_per_lot, then clamped to the broker's volume step/min/max. The same effective-capital number is reused to enforce a 3% daily loss circuit breaker (TodayLossRatio() walks deal history from midnight, sums profit + swap + commission for the day's exits tagged with InpMagic, and returns the loss as a percentage).

Position management lives in ManageOpenPositions(), which runs on every tick as long as the ATR handle returns a value. It walks PositionsTotal in reverse, filters by magic and symbol, and for each surviving position applies five steps in order. Step one is break-even: once price has moved InpBE_RMultiple × SL-distance (= 1.0R by default) in favor, the SL is set to open_price + 2 points (BE_OFFSET_POINTS = 2) — a true breakeven-plus lock, not a flat breakeven. Step two is ATR trailing: SL becomes bid − 2.5 × ATR for buys, ask + 2.5 × ATR for sells, but only if the new SL tightens (greater than current SL for buys, less for sells) and stays farther than the broker's stops-level. Step three is partial TP at PARTIAL_TP_R = 1R: 50% of the position is closed and the remainder is left to run to FULL_TP_R = 2R. Step four is a time exit at MAX_BARS_IN_TRADE = 200 bars on the current timeframe. Step five is the opposite-signal exit: if the position is a long and current RSI is now ≥ InpRSIThreshold, the position is closed; the mirror closes shorts. After every step the function calls ModifyPositionSL(), CloseThisPosition(), or ClosePartial(), each of which routes through TryClose/TryClosePartial/TryModify_EX13001 — three-attempt retry loops with 200ms back-off on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED for closes and only REQUOTE/TIMEOUT for modifies.

The 19 input parameters are organized in six groups: identity (magic 22213001, comment, dry-run flag defaulting to TRUE, kill switch), capital cap (cap amount, floor), risk & sizing (risk percent 0.5%, daily loss 3%, max concurrent 1, min R/R 1.2), signal (RSI period 21, RSI threshold 70, MA period 21), regime/confirm/exec (min ADX 18, max spread 30, slippage 10), and exit/manage (ATR-SL mult 1.5, BE R-multiple 1.0, trail ATR mult 2.5). The dry-run flag defaulting to TRUE is deliberate — it forces the EA to print every intended order to the log without sending it, so a user can observe entries, exits, and modifications on a live chart before flipping the switch. The kill switch forces a close-only mode without needing to remove the EA from the chart. The session filter is server-time 07:00 to 21:00 with a 1-hour Friday wind-down (Friday from 20:00 onward is blocked), not a London/NY overlap, so the EA's behavior depends on the broker's server clock. The OnTester custom criterion returns (net_profit × profit_factor) / (1 + equity_dd_percent) when total trades ≥ 30, rewarding strategies that pair positive expectancy with low drawdown. There is no martingale, no grid, no basket, and no news blackout module — the NEWS_BLACKOUT_MINUTES define is wired but the CalendarValueHistory call is left as a placeholder.

Strategy Deep Dive

OnInit creates six indicator handles — RSI(21) and MA(21) on the chart timeframe, ATR(14) and ADX(14) and Bollinger Bands(20, 2.0) for the regime classifier, plus an EMA(50) on H1 for higher-timeframe agreement — and configures the CTrade wrapper with the magic 22213001 and 10-point slippage. OnTick refreshes symbol rates, scans the deal history for fresh exits to update the consecutive-loss counter (which sets a 3-bar cooldown on any losing close), and then runs ManageOpenPositions() unconditionally with the current ATR value. On a new bar, it walks NoTradeGate() (kill switch, spread cap, server-time 07:00–21:00 with Friday wind-down from 20:00, capital floor, 3% daily loss circuit breaker, max-concurrent cap, symbol-exposure cap, loss-cooldown), then ComputeRegime() to classify the bar into one of seven states, then ADX-and-regime pre-filters, then ComputeSignal() for the RSI cross with MA-bias, then ConfirmEntry() for the HTF-EMA check, the spread cap, the session check, the regime sanity, and the 1.2 minimum R/R. If everything passes, ComputeLots() sizes the order off the projected SL × 0.5% of effective capital, ComputeSLTP() normalizes the SL and TP to tick size and pushes the SL outward of the broker's stops level, and SendOrder() opens the position with a single retry on REQUOTE/PRICE_OFF/TIMEOUT. The dry-run flag defaults to TRUE so the EA logs intended orders to the Experts tab without sending them until the user flips it off.

Entry Signal

Long entry fires when the previous bar's RSI(21) closes at or below 30 (100 − InpRSIThreshold=70) and the current bar's RSI closes above 30, with the previous bar's close also above the MA(21) bias line. The short entry is the exact mirror. A signal is rejected unless ADX(14) is at least 18, the regime classifier returns anything other than CHOPPY, the H1 EMA(50) confirms direction, the spread is below 30 points and not more than 2× the rolling 50-tick average, the broker-server hour is inside 07:00–21:00, and the projected R/R (TP at 2R against SL at 1.5×ATR) is at least 1.2.

Exit Signal

A position exits in one of five ways: a 50% partial close fires at +1R, the final TP sits at +2R, a hard opposite-signal exit closes the trade the moment RSI walks back to the other extreme (≥70 for longs, ≤30 for shorts), an ATR(14) trailing stop at 2.5×ATR ratchets the SL behind price once break-even-plus-2 lock has fired, and a 200-bar time-based exit closes any position that has not resolved on its own.

Stop Loss

Initial stop is 1.5×ATR(14) below the entry for longs (above for shorts), never closer than the broker's stops level plus a 5-point safety pad. Once price reaches +1R, the stop ratchets to entry + 2 points (a true breakeven-plus lock) and from there the ATR(14)×2.5 trailing ratchet takes over and only tightens.

Take Profit

TP1 sits at +1R (taking 50% off via the partial close) and the runner's TP2 sits at +2R. The order's broker-side TP is set to the 2R level on open; the 1R partial is then layered on top through ClosePartial(). The minimum R/R gate rejects any signal whose projected TP cannot reach at least 1.2R.

Best For

Best on XAUUSD M5 or H1 with a low-spread ECN or RAW account (sub-30-point spreads on gold, sub-2-point spreads on FX majors) and a $100 minimum deposit, with $300–$500 recommended to absorb the 1.5×ATR(14) initial stop on gold. The server-time 07:00–21:00 session window covers London and the New York open in most broker server clocks but the EA honors whatever the broker's server is set to, so verify your broker's GMT offset before running. Avoid running it on brokers with weekend quotes, during FOMC/ECB/NFP release windows (the news-blackout module is unwired), and on sub-$100 accounts where the 0.5% risk sizing would round below the broker's minimum lot step.

Strategy Logic

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

Family: RSI_MA Magic: 22213001 Version: 2.00

BRIEF: RSI emerges from oversold while price is above D1-SMA => bullish pullback entry; mirror for shorts. RSI-cross-with-MA- bias core gated by full 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 = 22213001 // Magic number (unique per EA)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_13001" // 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 EX13001 RSI_MA — Execution Flow (from source analysis)
// Family: RSI_MA
// RSI emerges from oversold while price is above D1-SMA => bullish pullback entry; mirror for shorts. RSI-cross-with-MA- bias core gated by full 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
InpMagic22213001Magic number (unique per EA)
InpTradeComment"Psgrowth.com Expert_13001"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_EX13001.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX13001 RSI MA V2 EA — RSI pullback + MA bias trend EA, 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:ex13001rsi_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_EX13001.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