P
PipsGrowth
HedgingOpen Source – Free

Pipsgrowth EX05001 Hedge

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

Pipsgrowth.com EX05001 HedgedGrid XAUUSD 5M — RSI reversion + hedged grid (default OFF), full 12-layer stack.

Overview

Pipsgrowth EX05001 is a confirmation-heavy mean-reversion EA built around a single question: when RSI(14) on the most recent closed M5 bar pushes to an extreme, is the broader tape quiet enough to expect a snap-back? Every layer of the strategy is engineered to answer that question with multiple yes/no votes before any order is staged. The closed-bar trigger is computed in ComputeSignal: an RSI reading at or below InpRSIBuyLevel (default 30) arms a long, a reading at or above InpRSISellLevel (default 70) arms a short, and the function returns a confidence score that scales linearly with how far RSI has pushed past the threshold — at the threshold itself the score is 30, and it climbs toward 100 as RSI extends deeper into extreme territory. That confidence is carried into the rest of the code: it is logged on every seed order and is the gate the flip-exit logic consults before closing a position on a contrary RSI print.

The first filter the signal has to pass is a higher-timeframe agreement check inside HtfAgrees. The function reads a 50-period EMA on H1 (HTF_TF=PERIOD_H1) and demands that the current Ask sit above the EMA for a long or below it for a short. Counter-trend RSI extremes — a 28 reading against a falling H1 EMA, for example — are discarded here without ever reaching the rest of the gating stack. The second filter is a 7-state regime classifier in ClassifyRegime. It pulls ADX(14), ATR(14), and a 20-period Bollinger Band width proxy (BB_PERIOD=20, BB_DEVIATION=2.0), then buckets the market into REGIME_RANGE, REGIME_COMPRESS, REGIME_WEAKTREND, REGIME_STRONGTREND, REGIME_EXPAND, REGIME_BREAKOUT, or REGIME_CHOPPY. EX05001 is a mean-reversion system, so it only seeds new positions when the regime is RANGE, COMPRESS, or WEAKTREND — the three conditions where RSI extremes are most likely to revert cleanly. Strong trends, breakouts, expansion, and choppy tape all stop the seed path. The ATR-percentile input fed to the classifier comes from a 200-bar rolling history maintained in OnTick every time a new M5 bar opens.

The third gate is NoTradeGated, a function that bundles every other safety check into one sequential pass. It refuses to seed when the spread is above InpMaxSpreadPts (default 250 points — sized for gold's typical spread band), when the GMT hour falls outside the union of London 7–16 and New York 12–21, when InpNewsFilter is on and the bar is within InpNewsFilterMinutes (default 15) of a session open, when g_tradesToday has hit InpMaxTradesPerDay (default 50), when the H1 EMA disagrees with the signal direction, when EffectiveCapital has fallen below InpCapitalCapFloor (default $50), when daily or weekly realized losses have crossed their respective 3% / 6% thresholds of effective capital, when g_consec_losses has reached InpCooldownAfterLoss, or when CountMyPositions has hit InpMaxConcurrent (default 4). OnTick also re-evaluates the emergency equity stop on every tick: if live equity drops below the starting balance minus one daily-loss limit worth of capital, CloseAll is invoked with the reason EQUITY_STOP and the EA flattens everything.

Risk and sizing are driven by effective capital, not the raw account balance. EffectiveCapital returns the lesser of InpCapitalCapAmount (default 0, which falls back to live equity) and current equity, minus realized P&L since the start of the trading day. CalcLot applies the InpRiskPercent (default 0.5%) to that figure and converts it into a lot size using the symbol's tick value, tick size, and the SL distance in price. The SL is set at SL_ATR_MULT × ATR(14) (default 2.0×) and the TP at TP_ATR_MULT × ATR(14) (default 3.0×), giving a 1:1.5 reward-to-risk ratio. OpenSeed refuses to send the order if the resulting TP would sit inside 1.2× the SL distance — a sanity check that prevents degenerate trades in low-volatility conditions. OrderCalcMargin pre-checks margin availability, and the TryBuy/TrySell wrappers retry up to three times on REQUOTE, TIMEOUT, PRICE_OFF, or PRICE_CHANGED with a 200ms backoff and a fresh Ask/Bid refresh.

Management runs every tick inside ManageExits. At +1R the SL is ratcheted to break-even plus one point (the extra point is there to absorb spread) and 50% of the position is closed into the partial-TP bucket, provided the remaining volume is still larger than twice the symbol's minimum lot size. After +1R the trailing block takes over: it computes a 2.5× ATR distance from the current price, clamps the level to the broker's SYMBOL_TRADE_STOPS_LEVEL minimum, and only modifies the SL when the new level strictly improves on the existing one. A flip exit closes the position when the closed-bar RSI swings to the opposite extreme with confidence at or above 50, or when the regime classifier flips into REGIME_STRONGTREND regardless of confidence. Any position still alive after MAX_BARS_IN_TRADE (default 240) is force-closed — a hard time stop that prevents mean-reversion trades from degrading into swing holds.

The hedged grid is the EA's optional scaling mode and ships disabled (InpGridEnabled=false). With it on, ManageGrid inspects open positions on every tick, and when the current price has moved GRID_ATR_MULT × ATR(14) (default 1.5×) past the most recent position in a direction, it adds another leg in that same direction. The lot size for each grid leg is the previous leg's lot multiplied by InpGridLotMultiplier, but the multiplier is hard-capped at GRID_LOT_MULT_MAX (1.3) inside ManageGrid — even if the input is set higher, the EA clamps it. Grid is also disabled in REGIME_CHOPPY and when the spread breaches InpMaxSpreadPts, and the per-direction leg count is hard-capped at GRID_MAX_LEVELS_CAP (5). At default settings the grid is effectively dormant; flipping it on with the multiplier left at 1.0 turns EX05001 into a fixed-lot, capped DCA rather than a true martingale, and the per-leg cap of 5 means the maximum basket exposure is bounded even on a runaway move.

The hardening stack adds session logic on top of the regime filter. DetectGMTOffset infers the broker's server-to-GMT offset from a one-hour gap in H1 candles — when InpServerGMTOffset is 0 the EA scans the last 100 H1 bars for the weekend gap, computes the difference between the post-gap bar's hour and 22, normalizes the offset into the –12 to +12 range, and stores it in g_gmtOffset. InActiveSession then checks the GMT hour against London 7–16 and New York 12–21. When InpAvoidAsia is true (the default) the function subtracts the Asia 0–7 window, so EX05001 effectively trades only during the London / New York overlap and the early-NY afternoon. The IsMarketOpen helper blocks weekend trading. The OnTradeTransaction handler updates g_realizedToday, g_realizedWeek, and g_tradesToday on every DEAL_ADD, and on the second consecutive loss (InpCooldownAfterLoss=2) it sets g_cooldownUntil to TimeCurrent() + 30 minutes — IsSafeToTrade checks this timer on every tick.

The EA runs on standard MT5 indicators. OnInit creates hRSI (RSI(14) on PRICE_CLOSE), hATR (ATR(14)), hADX (ADX(14)), hBB (Bollinger Bands with period 20 and deviation 2.0), and hEmaH (EMA(50) on H1 PRICE_CLOSE). The order-filling mode is auto-selected: FOK wins if the symbol supports it, otherwise IOC, otherwise RETURN. The trade object uses InpSlippagePts (default 30 points) and runs the three-retry, 200ms backoff logic for every modify, close, buy, and sell call. There are 30 inputs in seven groups (Identity, Risk & Sizing, Capital Allocation Cap, Signal, Hedged Grid, Exec/Manage, Hardening: GMT Sessions) and 29 functions covering the full 12-layer stack: regime classification, signal generation, entry, confirmation, no-trade gating, capital cap, risk, sizing, management, exit, scaling, and OnTester.

For a trader evaluating EX05001, the practical takeaways are these. The EA is a confirmation-heavy mean-reversion baseline that requires a quiet regime to fire — it will skip counter-trend RSI extremes in a strong trend, it will skip the signal in expansion and breakout states, and it will pause after two consecutive losses. Backtests should be expected to look smooth in RANGE and COMPRESS regimes and choppy in trends; the regime filter is the variable that drives most of the strategy's behavior, and the OnTester custom criterion (net × profit factor) / (1 + |balance drawdown|) requires at least 30 trades to return non-zero, so optimization runs that starve the EA of signals will score zero. XAUUSD on M5 is the default symbol, but the indicator stack and risk math are symbol-agnostic and the EA will run on FX majors without code changes — the 250-point spread cap and 30-point slippage default are sized for gold's typical spread band, so plan broker selection accordingly. With InpGridEnabled left off the EA behaves as a flat, single-position mean-reversion system; flipping the grid on converts it into a capped, fixed-lot DCA without ever crossing into true martingale territory.

Strategy Deep Dive

On every tick, OnTick refreshes the symbol, rotates the daily counters, and runs IsSafeToTrade — the hard gate that bundles session window, consecutive-loss cooldown, equity floor, daily/weekly loss limits, capital cap, market-open check, and trade count. If a new M5 bar has opened, the closed-bar RSI(14) is read by ComputeSignal and the 7-state regime is classified from ADX(14), ATR(14), and a 20-period Bollinger Band width proxy via ClassifyRegime, then HtfAgrees consults the H1 EMA(50). The seed path only fires when the EA is flat, the regime is RANGE / COMPRESS / WEAKTREND, the HTF agrees, and every NoTradeGated check passes; ManageExits then walks the open positions for break-even, partial TP, ATR trailing, RSI-flip exit, regime-flip exit, and the 240-bar time stop, while ManageGrid inspects for opt-in grid additions. The OnTester custom criterion scores (net × profit factor) / (1 + |balance drawdown|) and requires at least 30 trades to return non-zero.

Entry Signal

Long entry triggers when the closed M5 bar prints RSI(14) at or below InpRSIBuyLevel (default 30), the H1 EMA(50) sits below the current Ask, and the 7-state regime classifier (ADX14 + ATR14 + Bollinger width) lands in REGIME_RANGE, REGIME_COMPRESS, or REGIME_WEAKTREND. Short entry mirrors: RSI(14) at or above InpRSISellLevel (default 70), the H1 EMA confirms the short side, and the same regime window applies. The seed path only fires when the EA is flat — the grid layer is the only mechanism that can stack legs.

Exit Signal

At +1R the position is moved to break-even plus one point and 50% is closed into the partial-TP bucket; afterwards the stop ratchets at a 2.5× ATR(14) distance from current price, only ever moving in the profitable direction. A flip exit closes the position when the closed-bar RSI swings to the opposite extreme with confidence at or above 50, when the regime classifier flips into REGIME_STRONGTREND regardless of confidence, or after 240 bars in trade — a hard time stop that prevents mean-reversion entries from degrading into swing holds.

Stop Loss

Initial stop is placed at 2× ATR(14) from entry and auto-ratcheted to break-even plus one point at +1R, then trailed at 2.5× ATR(14) thereafter (only ever moving in the profitable direction, gated by the broker's SYMBOL_TRADE_STOPS_LEVEL minimum inside ClampStops). An emergency equity stop inside OnTick force-closes the entire basket if live equity drops below the starting balance minus one daily-loss limit worth of capital.

Take Profit

Take profit is set at 3× ATR(14) from entry, giving a 1.5R target, and OpenSeed refuses to send the order if the resulting TP would sit inside 1.2× the SL distance. In practice the first realized profit usually comes through the partial-TP block at +1R (50% of the position) rather than the limit, with the trailing block handling the remainder.

Best For

Minimum recommended balance: $100 (HIGH risk tag). Best paired with XAUUSD on M5 with a low-spread broker — the 250-point spread cap and 30-point slippage defaults are sized for gold's typical spread band, so ECN-style spreads on FX majors will also work. The two-consecutive-losses → 30-minute cooldown and the 3% daily loss limit will both trip on a choppy session, so expect the EA to flatten itself quickly in poor conditions rather than ride them out. Best fit: traders who want a confirmation-heavy mean-reversion baseline they can convert into a capped DCA by flipping the hedged grid on (InpGridEnabled=true, lot multiplier held at 1.0).

Strategy Logic

Pipsgrowth EX05001 Hedge — Strategy Logic Analysis (from .mq5 source)

Family: Hedge Magic: 22205001 Version: 2.00

BRIEF: RSI-extreme reversion signal on closed bar; hedged grid default OFF, ATR-spaced, lot-capped (mult <=1.3, max 5 levels). 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • AtrPercentile()
  • EffectiveCapital()
  • RealizedToday()
  • RealizedThisWeek()
  • ComputeSignal()
  • HtfAgrees()
  • InSession()
  • SpreadOk()
  • NoTradeGated()
  • NormalizeVolume()
  • CalcLot()
  • StopsLevelPts()
  • ...and 19 more

INTERNAL CONSTANTS (1 total):

  • GRID_ATR_MULT = 1.5 // grid spacing in ATR units (when grid enabled)

INPUT PARAMETERS (30 total across 7 groups):

  • [=== Identity ===] InpMagic = 22205001 // Magic number (unique per EA)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_05001" // Trade comment
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (%) of effective capital
  • [=== Risk & Sizing ===] InpDailyLossLimitPct = 3.0 // Daily loss limit (%) of effective capital
  • [=== Risk & Sizing ===] InpWeeklyLossLimitPct = 6.0 // Weekly loss limit (%) of effective capital
  • [=== Risk & Sizing ===] InpMaxConcurrent = 4 // Max concurrent positions (this EA)
  • [=== Risk & Sizing ===] InpCooldownAfterLoss = 2 // Cooldown consecutive losses before re-arm
  • [=== Capital Allocation Cap ===] InpCapitalCapAmount = 0.0 // Capital cap allocated ($ REAL money)
  • [=== Capital Allocation Cap ===] InpCapitalCapFloor = 50.0 // Floor below which entries are blocked ($)
  • [=== Signal (RSI reversion) ===] InpRSIBuyLevel = 30.0 // RSI buy threshold (closed bar)
  • [=== Signal (RSI reversion) ===] InpRSISellLevel = 70.0 // RSI sell threshold (closed bar)
  • [=== Hedged Grid (default OFF) ===] InpGridEnabled = false // Enable hedged grid expansion
  • [=== Hedged Grid (default OFF) ===] InpGridMaxLevels = 5 // Max grid levels per direction (<=5)
  • [=== Hedged Grid (default OFF) ===] InpGridLotMultiplier = 1.0 // Lot multiplier (1.0=fixed, max 1.3)
  • [=== Exec / Manage ===] InpMaxSpreadPts = 250 // Max spread (points)
  • [=== Exec / Manage ===] InpSlippagePts = 30 // Slippage (points)
  • [=== Exec / Manage ===] InpUseTrailing = true // Use ATR trailing stop
  • [=== Exec / Manage ===] InpUsePartialTP = true // Use partial TP at +1R
  • [=== Hardening: GMT Sessions ===] InpServerGMTOffset = 0 // Server GMT offset hours (0=auto-detect)
  • [=== Hardening: GMT Sessions ===] InpLondonStartHour = 7 // London session start (GMT)
  • [=== Hardening: GMT Sessions ===] InpLondonEndHour = 16 // London session end (GMT)
  • [=== Hardening: GMT Sessions ===] InpNYStartHour = 12 // New York session start (GMT)
  • [=== Hardening: GMT Sessions ===] InpNYEndHour = 21 // New York session end (GMT)
  • [=== Hardening: GMT Sessions ===] InpAvoidAsia = true // Avoid Asian session
  • [=== Hardening: GMT Sessions ===] InpAsiaStartHour = 0 // Asian session start (GMT)
  • [=== Hardening: GMT Sessions ===] InpAsiaEndHour = 7 // Asian session end (GMT)
  • [=== Hardening: GMT Sessions ===] InpNewsFilter = false // Avoid trading near news session opens
  • [=== Hardening: GMT Sessions ===] InpNewsFilterMinutes = 15 // Minutes to avoid around news
  • [=== Hardening: GMT Sessions ===] InpMaxTradesPerDay = 50 // Maximum trades per day
  • [=== Hardening: GMT Sessions ===] InpMinEquityPercent = 95.0 // Stop trading if equity < this % of initial balance
Pseudocode
// Pipsgrowth EX05001 Hedge — Execution Flow (from source analysis)
// Family: Hedge
// RSI-extreme reversion signal on closed bar; hedged grid default OFF, ATR-spaced, lot-capped (mult <=1.3, max 5 levels). 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. 2Confirm your broker allows hedging (holding opposing positions simultaneously)
  3. 3Open MetaTrader 5 on your computer
  4. 4Click File → Open Data Folder in the top menu
  5. 5Navigate to MQL5 → Experts and paste the .mq5 file there
  6. 6In MT5, right-click Expert Advisors in the Navigator panel → Refresh
  7. 7Drag the EA onto a chart and configure hedge trigger level and max exposure
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
InpMagic22205001Magic number (unique per EA)
InpTradeComment"Psgrowth.com Expert_05001"Trade comment
InpRiskPercent0.5Risk per trade (%) of effective capital
InpDailyLossLimitPct3.0Daily loss limit (%) of effective capital
InpWeeklyLossLimitPct6.0Weekly loss limit (%) of effective capital
InpMaxConcurrent4Max concurrent positions (this EA)
InpCooldownAfterLoss2Cooldown consecutive losses before re-arm
InpCapitalCapAmount0.0Capital cap allocated ($ REAL money)
InpCapitalCapFloor50.0Floor below which entries are blocked ($)
InpRSIBuyLevel30.0RSI buy threshold (closed bar)
InpRSISellLevel70.0RSI sell threshold (closed bar)
InpGridEnabledfalseEnable hedged grid expansion
InpGridMaxLevels5Max grid levels per direction (<=5)
InpGridLotMultiplier1.0Lot multiplier (1.0=fixed, max 1.3)
InpMaxSpreadPts250Max spread (points)
InpSlippagePts30Slippage (points)
InpUseTrailingtrueUse ATR trailing stop
InpUsePartialTPtrueUse partial TP at +1R
InpServerGMTOffset0Server GMT offset hours (0=auto-detect)
InpLondonStartHour7London session start (GMT)
InpLondonEndHour16London session end (GMT)
InpNYStartHour12New York session start (GMT)
InpNYEndHour21New York session end (GMT)
InpAvoidAsiatrueAvoid Asian session
InpAsiaStartHour0Asian session start (GMT)
InpAsiaEndHour7Asian session end (GMT)
InpNewsFilterfalseAvoid trading near news session opens
InpNewsFilterMinutes15Minutes to avoid around news
InpMaxTradesPerDay50Maximum trades per day
InpMinEquityPercent95.0Stop trading if equity < this % of initial balance
Source Code (.mq5)Open Source
Pipsgrowth_com_EX05001.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX05001 HedgedGrid XAUUSD 5M — RSI reversion + hedged grid (default OFF), 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>

//--- Tunables promoted to #define (kept OUT of input surface to respect 12-22 cap)
#define ATR_PERIOD          14
#define ATR_PCTILE_LOOKBACK 200
#define ADX_PERIOD          14
#define BB_PERIOD           20
#define BB_DEVIATION        2.0
#define RSI_PERIOD          14
#define HTF_EMA_PERIOD      50
#define HTF_TF              PERIOD_H1
#define REGIME_ADX_STRONG   25.0
#define REGIME_ADX_WEAK     18.0
#define ATR_PCTILE_RANGE_HI 70.0
#define ATR_PCTILE_RANGE_LO 30.0
#define BBW_COMPRESS_PCT    20.0
#define GRID_ATR_MULT       1.5      // grid spacing in ATR units (when grid enabled)
#define GRID_MAX_LEVELS_CAP 5
#define GRID_LOT_MULT_MAX   1.3
#define MAX_CONCURRENT_CAP  10
#define MAX_SYMBOL_EXP_CAP  5
#define SL_ATR_MULT         2.0
#define TP_ATR_MULT         3.0
#define BE_R_MULT           1.0
#define PARTIAL_TP_FRAC     0.5
#define PARTIAL_TP_R        1.0
#define TRAIL_ATR_MULT      2.5
#define TRAIL_START_R       1.0
#define MAX_BARS_IN_TRADE   240
#define MAX_SPREAD_MULT     3.0
#define SESSION_START_HOUR  7
#define SESSION_END_HOUR    21
#define NEWS_WINDOW_MIN     30
#define COOLDOWN_BARS       3

CTrade         trade;
CPositionInfo  position;
CSymbolInfo    mysymbol;
CAccountInfo   account;

//================== INPUTS (12-22 hard cap) ========================
input group "=== Identity ==="
input long     InpMagic              = 22205001;          // Magic number (unique per EA)
input string   InpTradeComment       = "Psgrowth.com Expert_05001"; // Trade comment

input group "=== Risk & Sizing ==="
input double   InpRiskPercent        = 0.5;              // Risk per trade (%) of effective capital
input double   InpDailyLossLimitPct  = 3.0;              // Daily loss limit (%) of effective capital
input double   InpWeeklyLossLimitPct = 6.0;              // Weekly loss limit (%) of effective capital

Full source code available on download

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

Tags:ex05001hedgepipsgrowthfreemt5xauusd

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_EX05001.mq5
File Size35.9 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyHedging
Risk LevelHigh Risk
Timeframes
M5H1
Currency Pairs
XAUUSD
Min. Deposit$100