P
PipsGrowth
HedgingOpen Source – Free

Pipsgrowth EX05002 Hedge

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

Pipsgrowth.com EX05002 HedgeCover — EMA cross seed + loss-triggered protective hedge, full 12-layer stack.

Overview

EX05002 is a single-position, single-hedge cover EA. It does not run a basket of opposite legs or stack scaling orders into a trend — every entry is exactly one seed trade, and at most one opposing hedge is attached to that seed. The hedge fires only after the seed is already in a loss, only on losing positions the EA still owns, and only once per ticket. There is no grid logic, no martingale, and no per-layer lot scaling. The EA's only job is to enter on a confirmed momentum cross, manage that one trade through break-even, partial close and trailing, and then — if price keeps running against the seed — open a single protective cover that bounds the loss while the original thesis plays out.

The seed is generated by an EMA(8)/EMA(21) crossover on the closed bar. The cross alone is not enough: ComputeSignal() also computes a confidence number from the relative spread between the two EMAs (sep * 30 + 40, capped at 100), and HtfAgrees() confirms the direction against an H1 EMA(50) filter — longs only above EMA50, shorts only below it. The regime classifier (ClassifyRegime()) runs on every tick using ADX(14), ATR(14) percentile over a 200-bar lookback, and a Bollinger Band(20, 2.0) width proxy, and resolves the market into one of seven buckets: COMPRESS, RANGE, CHOPPY, WEAKTREND, STRONGTREND, EXPAND and BREAKOUT. The EA seeds only inside RANGE, COMPRESS or WEAKTREND — strong trends and breakouts are deliberately excluded so the protective hedge has room to do its job without fighting momentum on both sides at once. The CHOPPY bucket hard-blocks all new entries via NoTradeGated().

Risk and sizing are split into a per-trade percent and a portfolio cap. CalcLot() sizes the seed at 0.5% of effective capital by default (InpRiskPercent = 0.5), where effective capital is min(cap, equity) – realized_today. The SL distance is 2.0 × ATR(14) and the lot is derived from that distance and the symbol's tick value/size, then NormalizeVolume() clamps to the broker's volume step, min and max. OrderCalcMargin() pre-checks margin before the order is sent, and the CTrade request is retried up to three times on REQUOTE, PRICE_OFF, PRICE_CHANGED or TIMEOUT with a 150 ms sleep between attempts. Filling is selected automatically: FOK if the symbol allows it, then IOC, then RETURN.

Once a seed is open, the EA runs the full management stack in ManageExits() on every tick. At +1R, it ratchets the stop to break-even plus one point (one-shot, irreversible). At the same +1R threshold, it also closes 50% of the position as a partial TP — the partial close is skipped only if the remaining volume would fall below 2× the broker's minimum lot. After +1R, an ATR(14) × 2.5 trailing stop takes over and can only ratchet forward. The exit logic also watches for an opposite EMA cross with confidence >= 50, and closes the position if the regime flips into STRONGTREND against the trade. A time-stop fires at 240 bars in trade (about 20 hours on M5) to prevent capital from being tied up in dormant positions.

The protective hedge is a separate subsystem driven by ManageHedge(). For every main position still open under the EA's magic, it measures the current adverse excursion: (open_px - bid) for longs, (ask - open_px) for shorts. When that distance exceeds InpHedgeLossATRMult * ATR(14) (default 1.5 × ATR), and the position is not already in g_hedged_tickets, and the global hedge count is below min(InpMaxHedges, 3), the EA opens a single opposing market order with volume = position.Volume() * min(InpHedgeLotMultiplier, 1.5) — i.e. the same size as the seed by default, hard-capped at 1.5× by the HEDGE_LOT_MULT_MAX define. The hedge is tagged with the comment ..._H, the seed's ticket is added to g_hedged_tickets so it can never be re-hedged, and g_last_hedge_time is set so subsequent hedges have to wait InpHedgeCooldownMin minutes (default 5). Hedges inherit no SL/TP from the seed — they live until the manual close or the basket is flattened by the equity stop.

The hardening stack is layered on top. IsMarketOpen() blocks Saturday and Friday after 21:00 server time, plus Sunday before 22:00. InActiveSession() translates server time to GMT using the auto-detected g_gmtOffset (or a manual InpServerGMTOffset), then admits bars only inside London (7–16 GMT) or New York (12–21 GMT), and explicitly rejects the Asian window (0–7 GMT) when InpAvoidAsia is true. IsNewsTime() blocks entries within ±15 minutes of the London or NY session open when InpNewsFilter is on. NoTradeGated() runs ten separate checks (choppy regime, spread > 250 points, session, news, daily trade cap, HTF disagreement, capital floor, daily loss, weekly loss, consec-loss cooldown, max concurrent) and writes a reason string to the log if any one of them fails.

The capital caps are enforced twice. On entry, EffectiveCapital() floors at the smaller of InpCapitalCapAmount (set to 0 means use full equity) and the current account equity, then subtracts today's realized P&L. The lot is sized off that effective figure, so after a losing day the EA automatically trades smaller. Daily loss at 3% of effective capital and weekly loss at 6% block all new entries; the realized figures are read straight from the deal history filtered by magic and symbol. A separate emergency check in OnTick() closes everything if equity drops below balance – (effective_capital × daily_loss_pct) — the equity stop.

The OnTester custom criterion is (net_profit * profit_factor) / (1 + |balance_dd|), gated on a minimum of 30 trades and a positive profit factor. That formula rewards both profitability per unit of drawdown and consistency across many trades — the kind of curve a single-strategy hedge-cover system can actually produce. A backtest that wins big on 12 trades and then gives it back will score poorly even if the absolute profit is high.

The minDeposit label in the catalog is $100, and the risk tier is HIGH — both correct. The EA needs enough headroom to cover one full seed plus one full hedge at the broker's lot step, and the protective cover is only useful if the account can hold both legs through a full ATR move against the seed. The 0.5% per-trade risk default assumes the operator is willing to take the seed to stop AND the hedge to stop on the same day, which is the worst realistic case for the design. Anyone running this should size for that, not for the seed alone.

Strategy Deep Dive

On every tick the EA refreshes the ATR(14), ADX(14), Bollinger(20, 2.0), EMA(8), EMA(21) and H1 EMA(50) handles and recomputes the regime from ADX, ATR-percentile and band-width. The seven-state classifier lets new seeds through only in RANGE / COMPRESS / WEAKTREND; CHOPPY is hard-blocked. NoTradeGated() then runs ten pre-trade checks (spread, session, news, daily trade cap, HTF agreement, capital floor, daily loss, weekly loss, consec-loss cooldown, max concurrent) and refuses the entry with a logged reason if any one fails. A new seed is opened only on a new bar and only when the account is flat of this EA's magic. The protective hedge is a strictly separate subsystem: ManageHedge() scans open main positions each tick, and when a position is in loss by more than 1.5 × ATR(14) and is not already in g_hedged_tickets and the hedge count is below 3, it opens a single opposing market order at the same lot size (capped at 1.5× by the HEDGE_LOT_MULT_MAX define) and marks the ticket so it can never be hedged twice. Hedges are spaced at least 5 minutes apart by g_last_hedge_time and inherit no SL/TP — they live until the equity stop or manual close.

Entry Signal

A seed position is opened on a closed-bar EMA(8) crossing EMA(21), with the additional requirement that the H1 EMA(50) agrees with the direction (price above for longs, below for shorts) and that the regime classifier resolves the market to RANGE, COMPRESS or WEAKTREND. The signal confidence is derived from the EMA spread, and no entry is taken in CHOPPY, STRONGTREND, EXPAND or BREAKOUT regimes.

Exit Signal

Exits run on every tick: break-even (open ± 1 point) is locked in one shot at +1R, 50% of the position is closed as a partial TP at the same +1R threshold, and an ATR(14) × 2.5 trailing stop takes over and can only ratchet forward. A position is also closed on an opposite EMA cross with confidence ≥ 50, on a regime flip into STRONGTREND against the trade, or after 240 bars in trade.

Stop Loss

Per-trade initial stop is 2.0 × ATR(14) on the closed bar, clamped to the broker's SYMBOL_TRADE_STOPS_LEVEL. The stop is then ratcheted to break-even + 1 point at +1R (one-shot) and handed off to an ATR(14) × 2.5 trailing stop after that. There is no portfolio-level SL beyond the daily-loss (3%) and weekly-loss (6%) caps and the emergency equity stop.

Take Profit

Per-trade take profit is 3.0 × ATR(14), which sets a 1.5:1 reward-to-risk ratio against the 2.0 × ATR(14) stop. In practice, 50% of the position is usually closed at +1R as a partial TP well before the full TP is reached, and the trailing stop tends to capture the remainder.

Best For

Best for a $100+ account on a low-spread, ECN/RAW broker offering XAUUSD or the major FX pairs, on M5 or H1 charts. The EA needs enough headroom to absorb one full seed plus one full-size hedge (default 1.0× the seed) through a 1.5 × ATR adverse move, and a broker that can handle the position sizing and stops level on a metals contract. The risk profile is HIGH because both legs can be live at the same time and the hedge itself has no stop until manual close or the equity stop fires.

Strategy Logic

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

Family: Hedge Magic: 22205002 Version: 2.00

BRIEF: EMA(fast/slow) cross seed entry; protective loss-triggered hedge opens ONE opposing cover when a position loses > N*ATR, lot multiplier capped (<=1.5x), max 3 hedges, per-position single-hedge, cooldown gated. 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()
  • CountMyPositions()
  • CountHedgePositions()
  • NoTradeGated()
  • NormalizeVolume()
  • ...and 20 more

INTERNAL CONSTANTS (2 total):

  • HEDGE_LOT_MULT_MAX = 1.5 // hard cap on hedge lot multiplier
  • HEDGE_MAX_CAP = 3 // hard cap on simultaneous hedges

INPUT PARAMETERS (31 total across 7 groups):

  • [=== Identity ===] InpMagic = 22205002 // EA main magic number
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_05002" // 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 main 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 (EMA cross for seed) ===] InpEMAFast = 8 // Fast EMA period
  • [=== Signal (EMA cross for seed) ===] InpEMASlow = 21 // Slow EMA period
  • [=== Protective Hedge ===] InpHedgeLossATRMult = 1.5 // Loss trigger (ATR multiples, >=1.0)
  • [=== Protective Hedge ===] InpHedgeLotMultiplier = 1.0 // Hedge lot multiplier (1.0=fixed, max 1.5)
  • [=== Protective Hedge ===] InpMaxHedges = 3 // Max simultaneous hedges (0..3)
  • [=== Protective Hedge ===] InpHedgeCooldownMin = 5 // Cooldown between hedge trades (minutes)
  • [=== 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 EX05002 Hedge — Execution Flow (from source analysis)
// Family: Hedge
// EMA(fast/slow) cross seed entry; protective loss-triggered hedge opens ONE opposing cover when a position loses > N*ATR, lot multiplier capped (<=1.5x), max 3 hedges, per-position single-hedge, cooldown gated. 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
InpMagic22205002EA main magic number
InpTradeComment"Psgrowth.com Expert_05002"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 main positions (this EA)
InpCooldownAfterLoss2Cooldown consecutive losses before re-arm
InpCapitalCapAmount0.0Capital cap allocated ($ REAL money)
InpCapitalCapFloor50.0Floor below which entries are blocked ($)
InpEMAFast8Fast EMA period
InpEMASlow21Slow EMA period
InpHedgeLossATRMult1.5Loss trigger (ATR multiples, >=1.0)
InpHedgeLotMultiplier1.0Hedge lot multiplier (1.0=fixed, max 1.5)
InpMaxHedges3Max simultaneous hedges (0..3)
InpHedgeCooldownMin5Cooldown between hedge trades (minutes)
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_EX05002.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX05002 HedgeCover — EMA cross seed + loss-triggered protective hedge, 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 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 HEDGE_LOT_MULT_MAX  1.5      // hard cap on hedge lot multiplier
#define HEDGE_MAX_CAP       3        // hard cap on simultaneous hedges
#define MAX_CONCURRENT_CAP  10
#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

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

//================== INPUTS (12-22 hard cap) ========================
input group "=== Identity ==="
input long     InpMagic              = 22205002;             // EA main magic number
input string   InpTradeComment       = "Psgrowth.com Expert_05002"; // 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
input int      InpMaxConcurrent      = 4;                   // Max concurrent main positions (this EA)
input int      InpCooldownAfterLoss  = 2;                   // Cooldown consecutive losses before re-arm

input group "=== Capital Allocation Cap ==="

Full source code available on download

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

Tags:ex05002hedgepipsgrowthfreemt5xauusd

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