Pipsgrowth EX03022 Grid
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX03022 HedgingGridEA — hedging + grid recovery, full 12-layer stack.
Overview
EX03022 HedgingGridEA is a one-leg buy with a single counter-hedge recovery — not a multi-tier grid despite the family label. The code opens exactly one Buy at the start of each cycle, waits for price to drop a configurable distance below that entry, and then opens one Sell at double the lot to form a closed hedge. No indicators drive that decision; the trigger is purely the distance between the current Bid and the open price of the initial position, measured in points. The EA's only inputs are lot size, hedge distance, basket take-profit, and the standard GMT session and capital-protection gates — there is nothing else to configure. The header documents a 12-layer stack (REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester), but the runtime path inside OnTick is much narrower than that list suggests: it checks the safety gate, sums basket profit, counts open positions, and either closes everything on basket TP or fires the counter-hedge. Everything else in the source is scaffolding.
The lifecycle starts when CountOpen() returns zero and no initial ticket is recorded. The first tick of a fresh session calls TryBuy_EX03022 at the current Ask with lot 0.10 (InpLotSize default), no SL, no TP, and the comment 'Psgrowth.com Expert_03022'. The trade object is a CTrade configured with magic 22203022 and 20-point slippage. TryBuy_EX03022 normalises the lot to the symbol's volume step, clamps it to the symbol's min and max, and pre-checks free margin via OrderCalcMargin. If the margin check fails the function prints a message and returns false without sending. Otherwise it refreshes the Ask, calls trade.Buy, and accepts the result only if the return code is TRADE_RETCODE_DONE or TRADE_RETCODE_DONE_PARTIAL. Retcode-classified transient errors (REQUOTE, TIMEOUT, PRICE_OFF, PRICE_CHANGED) trigger a 200 ms Sleep and a retry, up to three attempts. On success the daily trade counter g_dailyTrades increments, and the ticket is stored in initialTicket.
On every subsequent tick the EA recomputes two things: the basket profit across all positions filtered by magic and symbol, and the count of open positions on the same filter. If the basket profit reaches or exceeds InpTakeProfit * _Point * 100, the EA calls CloseAll() which iterates the position list and uses TryClose_EX03022 to flatten each ticket (three retries, 200 ms, transient-error classification identical to the entry helpers). After the basket closes, the hedged flag is set back to false and initialTicket is reset to zero, so the next cycle starts cleanly.
If the count is still one and the position is unhedged, the EA reads the open price from POSITION_PRICE_OPEN and the current Bid, and computes openPrice - bid. Once that difference reaches InpHedgeDistance points (100 by default), TrySell_EX03022 is called with InpLotSize * 2 lots (0.20 by default) at the current Bid, again with no per-trade SL or TP. TrySell_EX03022 has the same three-retry loop and the same margin guard as TryBuy_EX03022, and on success the hedged flag is set to true. From that point on, the EA will not add another position — it only watches basket profit. There is no third leg, no martingale escalation, and no spacing logic driven by InpGridStep. The 50-point InpGridStep input is declared in the source but is not referenced in OnTick, the entry helpers, or any function called by OnTick; it is effectively dead code and has no effect on live behaviour.
The exit is a basket-only target. InpTakeProfit defaults to 100 points; the EA multiplies that by _Point and by 100 to derive a money target. For XAUUSD with _Point = 0.01, the basket target is therefore $100. For 5-digit FX majors the same expression collapses to a much smaller number, which is why the file header notes the EA is portable to FX majors and gold but in practice the default target only makes sense on instruments where _Point is 0.01 or larger. There is no per-trade stop loss on either leg; the implicit stop is the broker's margin call or the account-level InpEquityFloor, InpDailyLossLimit, InpWeeklyLossLimit, and InpCapitalCap inputs (each defaulting to 0 = disabled). The capital cap is enforced as a balance ceiling: if AccountInfoDouble(ACCOUNT_BALANCE) is already at or above InpCapitalCap the EA refuses to open new positions — useful for testing the EA on a small sub-account.
Session control is a pure GMT gate. InpUseGMTSessions defaults to true. DetectGMTOffset_EX03022 walks every candidate offset from -12 to +12, applies it to the server time, and scores the resulting MqlDateTime: weekday in 1..5 scores 10, hour in 7..21 scores 5. The offset with the highest combined score is taken as the broker's GMT offset and stored in g_gmtOffset. InActiveSession_EX03022 then converts server time to GMT, blocks Saturday and Sunday outright, and admits the tick if the GMT hour falls in [InpLondonStartGMT, InpLondonEndGMT) = [7, 16) or in [InpNewYorkStartGMT, InpNewYorkEndGMT) = [12, 21). The two windows overlap between 12:00 and 16:00 GMT, so the EA is effectively active across the London open and the New York open and close.
The cooldown behaviour has a hardcoded trigger that overrides the visible InpMaxConsecLosses input. OnTradeTransaction filters deals by magic and symbol, and on every DEAL_ENTRY_OUT or DEAL_ENTRY_INOUT it accumulates the realised P/L (profit + swap + commission) into g_realizedToday and g_realizedWeek. A negative total increments g_consecLossesHD; a non-negative total resets it to zero. The cooldown activates at g_consecLossesHD >= 3 — not at InpMaxConsecLosses — and uses InpCooldownMinutes (30 by default) to set g_cooldownUntil. IsSafeToTrade_EX03022 refuses to trade while g_cooldownUntil is in the future. So the user-facing InpMaxConsecLosses input is effectively cosmetic; the live behaviour keys off the constant 3.
The OnTester formula is a flat profit-to-drawdown ratio weighted by profit factor, gated by trades >= 10 and maxDD > 0. It returns (profit / maxDD) * (pf > 1 ? pf : 0), which is a combined return / smoothness / consistency score suitable for strategy-optimizer ranking. Strategies that take fewer than ten trades in the test window get a zero regardless of profitability.
For deployment: minimum recommended balance is $100, but the effective risk depends almost entirely on InpLotSize and the broker's contract size. With InpLotSize = 0.10 on XAUUSD the initial buy is 0.10 lot and the hedge leg is 0.20 lot, so the account must clear OrderCalcMargin for 0.30 lot of gold exposure. Set InpEquityFloor, InpDailyLossLimit, and InpCapitalCap explicitly before going live — the defaults of 0 disable all three guards. The EA is sensitive to spread: a 50-point round-trip spread on a 100-point basket target consumes 50% of the gross profit, and the lot-doubled Sell leg amplifies the swap and commission cost of the recovery path. Run it on a low-spread, low-swap broker, and start the backtest on a session window where London and New York overlap to match the production session gate.
Strategy Deep Dive
OnTick first calls UpdateDailyCounters_EX03022 to rotate g_realizedToday, g_realizedWeek, g_dayStartTime, and g_weekStartTime when the day or week boundary crosses. It then runs IsSafeToTrade_EX03022, which checks the GMT session window, the cooldown timer, the equity floor, the daily and weekly loss limits, the balance cap, the daily trade counter, and the consec-loss counter. Only if every guard passes does the EA compute basket profit and the position count, decide whether to close on basket TP, fire the initial Buy, or open the doubled-lot hedge Sell. TryBuy_EX03022 and TrySell_EX03022 both pre-check free margin via OrderCalcMargin and retry up to three times on REQUOTE, TIMEOUT, PRICE_OFF, or PRICE_CHANGED errors with a 200 ms Sleep. TryClose_EX03022 uses the same retry pattern for the basket close. OnTradeTransaction filters deals by magic and symbol, accumulates realised P/L into the daily and weekly buckets, increments g_consecLossesHD on losses, and triggers the 30-minute cooldown at the third consecutive loss. DetectGMTOffset_EX03022 scores candidate offsets from -12 to +12 against weekday and hour heuristics, picks the best, and stores it in g_gmtOffset for the session filter. The OnTester formula is (profit / maxDD) * (pf > 1 ? pf : 0) gated by trades >= 10 and maxDD > 0.
Opens a single Buy at the current Ask with InpLotSize lots (0.10 default), no SL and no TP. After the position is live, the EA watches the distance between the open price and the current Bid; once Bid drops by InpHedgeDistance points (100 by default) it opens a counter-hedge Sell at twice the lot (0.20) at the current Bid. No indicators are involved — the trigger is purely the price-distance threshold from the initial ticket. There is no multi-level grid: only one hedge leg ever fires per cycle.
Exit is basket-only. The EA sums unrealised P/L across every position with magic 22203022 on the current symbol, and once basket >= InpTakeProfit * _Point * 100 it calls CloseAll() and resets initialTicket plus the hedged flag. With the default InpTakeProfit = 100 on XAUUSD (where _Point = 0.01) the basket target is $100. There is no per-trade stop; the only hard stops are the account-level capital caps and the cooldown after three consecutive losing deals.
There is no per-trade stop loss on either leg of the basket. The only hard stops are the account-level guards in IsSafeToTrade_EX03022 — InpEquityFloor (default 0 = disabled), InpDailyLossLimit (0 = disabled), InpWeeklyLossLimit (0 = disabled) — plus the InpCapitalCap balance ceiling. OnTradeTransaction also imposes a 30-minute cooldown after three consecutive losing realised deals (g_consecLossesHD >= 3), which is hardcoded and ignores the InpMaxConsecLosses input.
Basket take-profit is the only target. The basket closes when unrealised P/L across all magic-22203022 positions on _Symbol reaches InpTakeProfit * _Point * 100. With the default InpTakeProfit = 100 and on XAUUSD (_Point = 0.01) that is a $100 basket target. There is no per-trade TP on the Buy or the hedge Sell; both legs are closed together when the basket hits.
Use EX03022 on XAUUSD M5 with InpLotSize = 0.10 and InpHedgeDistance = 100 (the defaults). The minimum recommended balance is $100, but the account must clear OrderCalcMargin for 0.30 lot of gold (the initial 0.10 + the 0.20 hedge), which on most brokers translates to roughly $600-$1,500 of free margin at 1:100 leverage. Run it on a low-spread, low-swap broker — a 50-point round-trip spread on a 100-point basket target eats 50% of the gross profit. The session gate is GMT London 7-16 union New York 12-21 with weekend blocking, so it needs a broker whose server time is within +/- 12 hours of actual GMT (DetectGMTOffset_EX03022 picks the best candidate offset at init). Set InpEquityFloor, InpDailyLossLimit, and InpCapitalCap explicitly before going live; the defaults of 0 disable all three. Do not expect the InpMaxConsecLosses input to gate anything — the live cooldown fires at the third consecutive losing deal regardless.
Strategy Logic
Pipsgrowth EX03022 Grid — Strategy Logic Analysis (from .mq5 source)
Family: Grid
Magic: 22203022
Version: 2.00
BRIEF:
Hedging + grid recovery EA that opens opposing positions at configurable distance. Uses a hedge-and-recover approach with grid step spacing and basket take-profit close
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
BasketProfit()CountOpen()CloseAll()DetectGMTOffset_EX03022()ServerToGMT_EX03022()InActiveSession_EX03022()UpdateDailyCounters_EX03022()IsSafeToTrade_EX03022()TryBuy_EX03022()TrySell_EX03022()TryClose_EX03022()OnTradeTransaction()
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (0 total across 0 groups):
// Pipsgrowth EX03022 Grid — Execution Flow (from source analysis)
// Family: Grid
// Hedging + grid recovery EA that opens opposing positions at configurable distance. Uses a hedge-and-recover approach with grid step spacing and basket take-profit close
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 a chart — H1 or H4 is recommended for grid EAs
- 7Set grid step (pips), maximum orders, and lot size in the EA dialog
- 8Enable Allow Algo Trading and click OK
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX03022 HedgingGridEA — hedging + grid recovery, full 12-layer stack."
#include <Trade\Trade.mqh>
input group "=== Identity ==="
input int InpMagicNumber = 22203022;
input string InpTradeComment = "Psgrowth.com Expert_03022";
input group "=== Trading ==="
input double InpLotSize = 0.10;
input int InpHedgeDistance = 100;
input int InpGridStep = 50;
input int InpTakeProfit = 100;
input group "=== Hardening GMT Sessions ==="
input bool InpUseGMTSessions = true;
input int InpLondonStartGMT = 7;
input int InpLondonEndGMT = 16;
input int InpNewYorkStartGMT = 12;
input int InpNewYorkEndGMT = 21;
input group "=== Hardening Capital Protection ==="
input double InpEquityFloor = 0.0;
input double InpDailyLossLimit = 0.0;
input double InpWeeklyLossLimit = 0.0;
input double InpCapitalCap = 0.0;
input group "=== Hardening Trade Safety ==="
input int InpMaxTradesPerDay = 50;
input int InpCooldownMinutes = 30;
input int InpMaxConsecLosses = 0;
CTrade trade;
bool hedged=false; ulong initialTicket=0;
//--- Hardening Globals
double g_realizedToday = 0;
double g_realizedWeek = 0;
datetime g_dayStartTime = 0;
datetime g_weekStartTime = 0;
int g_gmtOffset = 3;
int g_dailyTrades = 0;
int g_consecLossesHD = 0;
datetime g_cooldownUntil = 0;
int OnInit() { trade.SetExpertMagicNumber(InpMagicNumber); trade.SetDeviationInPoints(20); g_gmtOffset = DetectGMTOffset_EX03022(); g_dayStartTime = TimeCurrent(); g_weekStartTime = TimeCurrent(); PrintFormat("GMT offset auto-detected: %d", g_gmtOffset); return INIT_SUCCEEDED; }
void OnDeinit(const int r) {}
void OnTick() {
UpdateDailyCounters_EX03022();
if(!IsSafeToTrade_EX03022()) return;
double basket=BasketProfit();
int cnt=CountOpen();
if(cnt>0 && basket>=InpTakeProfit*_Point*100) { CloseAll(); hedged=false; initialTicket=0; return; }
if(cnt==0 && initialTicket==0) {
double ask=SymbolInfoDouble(_Symbol,SYMBOL_ASK);
if(TryBuy_EX03022(InpLotSize,ask,0,0,InpTradeComment))
initialTicket=trade.ResultOrder();
return;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 Grid strategy EAs from our library
Pipsgrowth EX03026 Grid
Pipsgrowth.com EX03026 USDJPY_Aggressive_Pyramid — MTF Hull MA pyramid with regime detection, full 12-layer stack.
Pipsgrowth EX03001 Grid
Pipsgrowth.com EX03001 Thanos Grid Adaptive — bidirectional ATR-spaced stop-order grid, full 12-layer stack.
Pipsgrowth EX03020 Grid
Pipsgrowth.com EX03020 GridScalperMA — dynamic grid with MA trend filter, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.