Pipsgrowth EX18115 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX18115 HedgingMartingale — hedging + martingale recovery, full 12-layer stack.
Overview
EX18115 HedgingMartingale is, despite the marketing header that advertises a 'full 12-layer stack' of regime detection, signal generation, confirmations, no-trade gates, capital caps, risk engines, scaling, and an OnTester pass, in practice a single-file recovery script. The header at the top of the .mq5 lists twelve architectural layers (REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester), but if you open the file you will find only six functions — BasketProfit, CountOpen, CloseAll, and three retry wrappers TryClose_EX18115, TryClosePartial_EX18115, TryModify_EX18115 — plus a single OnTick() body that fits on twelve lines. There is no regime classifier, no indicator handle, no signal function, no confirmation gate, no news filter, no session filter, no OnTester, no magic-number check beyond the per-position filter inside the helpers, and no dashboard or chart object. The header is aspirational copy, not a description of the code. Anyone reading this article should treat the .mq5 itself as the source of truth and the header as marketing language.
What the EA actually does is one specific, well-known recovery pattern. When OnTick() finds zero open positions and the initialOpen flag is false, it reads the current ASK price and calls trade.Buy() with InpInitialLot (default 0.10) and the comment Psgrowth.com Expert_18115. The stop loss and take profit passed to trade.Buy() are both 0 — there is no per-trade protective stop on the entry. The flag initialOpen flips to true and the EA waits. If the price moves against this initial long by enough points, the basket as a whole goes negative; the EA then layers in a SELL hedge to lock the drawdown into a closed lot-multiplication cycle.
The hedging leg is governed by three inputs that operate together. InpEnableMartingale (default false) must be true for the recovery to run. InpRecoveryStep (default 100, in points) sets the per-level drawdown trigger in raw points, and the trigger is scaled by (level+1), so the second hedge fires when the basket is down 100 * 2 = 200 points, the third at 100 * 3 = 300 points, and the fourth at 100 * 4 = 400 points. InpHedgeLot (default 0.20) is the base lot for the first hedge, and the actual hedge lot is NormalizeDouble(InpHedgeLot * MathPow(2, level), 2) — so the levels are 0.20, 0.40, 0.80, 1.60 lots on gold-sized accounts by default. InpMaxLevels caps how many hedges can be opened in one recovery cycle (default 4). Once that cap is hit, the EA simply does not add any more positions and waits for the basket to come back. There is no breaker that hard-stops the EA at a portfolio drawdown threshold; the only safety is the InpMaxLevels cap.
The exit logic is the simplest part of the design and the only condition that actually closes the basket. On every tick, after recomputing BasketProfit() and CountOpen(), the code checks if(cnt>0 && basket>=50). If the basket is positive by 50 account-currency units (no scaling by lot, no scaling by step, a flat $50 / €50 / ¥50 / XAU 50 etc. target), CloseAll() is called, which iterates PositionsTotal() from the highest index down, filters on the magic number 22218115 and the chart symbol, and sends a close through TryClose_EX18115. That helper retries the close up to three times with a 200 ms Sleep() between attempts on requote, timeout, price-off, or price-changed return codes, and returns false on the third failure. After CloseAll() runs, the EA resets level = 0 and initialOpen = false, so the next tick with no open positions will start a fresh cycle with a fresh InpInitialLot buy. There is no partial close, no per-leg TP, and no trailing stop.
A few honest observations about the implementation. The trade.Buy() and trade.Sell() calls both pass 0, 0 for stop loss and take profit, so the only thing standing between the account and an unbounded drawdown is the InpMaxLevels cap and the broker's margin call. There is no equity-curve stop, no daily-loss stop, no per-leg SL, and no kill-switch. The OnTick() body has a return after the first Buy and another return after the basket-profit close, so the rest of the function is skipped on those ticks; in practice the EA processes at most one decision per tick. The retry wrappers TryClosePartial_EX18115 and TryModify_EX18115 are declared and compiled, but nothing in the active path calls them — CloseAll() only calls TryClose_EX18115, and there are no modifications to existing positions anywhere in the file.
The magic number is hardcoded as 22218115 in the InpMagicNumber input and is also applied to the CTrade instance via trade.SetExpertMagicNumber(InpMagicNumber) in OnInit(). The trade comment is the literal string Psgrowth.com Expert_18115 for the initial buy and Psgrowth.com Expert_18115 Lvl <n> for hedges, which makes it easy to identify the EA's positions in the trade panel and in any third-party reporting tool. The fill mode is whatever the broker advertises — the EA never calls trade.SetTypeFilling() and never overrides ORDER_FILLING_*, so on ECN/STP accounts the broker's policy applies automatically. Slippage tolerance is set with trade.SetDeviationInPoints(30), which is generous for gold on most retail brokers but can still get clipped on fast news spikes.
In backtest, this EA will print a small handful of trades per session on M5 XAUUSD. The equity curve will be stair-stepped: long flat segments interrupted by sudden multi-leg drawdowns that resolve in a single basket profit close, or that run to the InpMaxLevels cap and stall. Most of the time the EA is doing nothing — there is exactly one Buy per fresh cycle. The interesting bars are the recovery cycles, where four positions (one initial long and up to three or four hedges) sit on the book at the same time with no protective stops, and the basket either closes at +$50 or never closes at all within the test window. If you intend to run this EA in production, the most important configuration decision is whether to set InpEnableMartingale = true and, if so, how aggressive to make the lot multiplier and the recovery step. The default configuration is the safest starting point: martingale off, single 0.10 lot, basket TP at 50. The riskier configurations are not so much a question of whether the EA 'works' as a question of whether the broker's margin and the account size can absorb a fully scaled basket that does not recover before the test ends.
Strategy Deep Dive
On every tick the EA recomputes the basket profit and the count of open positions belonging to magic 22218115 on the chart symbol. If the basket is non-empty and the profit is at least +50, it tears the basket down through TryClose_EX18115 (a three-attempt CTrade.PositionClose wrapper with 200 ms backoff on requote/timeout/price-off/price-changed), then resets level=0 and initialOpen=false. If the basket is empty and initialOpen is false, it fires a single market Buy of InpInitialLot and flips initialOpen to true. If InpEnableMartingale is true and the basket is in drawdown past InpRecoveryStep × (level+1) points, it adds one SELL hedge sized InpHedgeLot × 2^level, incrementing level until it hits InpMaxLevels. There is no indicator, no signal function, no session filter, no news filter, no OnTester, no dashboard, and no chart object — the entire strategy is the close-then-recover ladder encoded in OnTick().
First entry is a market Buy of InpInitialLot (default 0.10 lots) at the current ASK, sent the first time OnTick() finds zero open positions and the initialOpen flag is false. Recovery entries are SELL hedges of InpHedgeLot × 2^level lots (0.20 / 0.40 / 0.80 / 1.60 by default), each one fired when the open-position basket is down by InpRecoveryStep × (level+1) points (100 / 200 / 300 / 400 by default), capped at InpMaxLevels hedges (default 4). InpEnableMartingale must be true for the recovery leg to run.
The only exit path is CloseAll(), which fires from OnTick() when CountOpen() is greater than zero and BasketProfit() is at least +50 in account currency. CloseAll() iterates positions from highest index to lowest, filters on the magic 22218115 and the chart symbol, and routes each close through TryClose_EX18115 (three retries with 200 ms Sleep on requote/timeout/price-off/price-changed). After a basket close the EA resets level=0 and initialOpen=false and waits for the next zero-position state to start a fresh cycle. There is no partial close and no per-leg exit.
There is no per-trade stop loss on either the initial Buy or any of the hedge Sells — both trade.Buy() and trade.Sell() are called with 0 for the stop-loss parameter. The only thing that limits how deep a recovery cycle can run is the InpMaxLevels hedge cap (default 4) combined with the broker's margin call. There is no equity-curve stop, no daily-loss cap, and no kill-switch anywhere in the file.
There is no per-trade take profit on either leg — both trade.Buy() and trade.Sell() are called with 0 for the take-profit parameter. The basket target is a flat +50 in account currency, set inline in the OnTick() body as basket >= 50. There is no scaling by lot count, by step number, or by drawdown magnitude; a four-leg basket of 0.10 + 0.20 + 0.40 + 0.80 lots and a one-leg basket of 0.10 lot both need exactly +50 to close.
Recommended only for XAUUSD traders who explicitly want a single-direction Buy + hedging-Sell martingale ladder and who can absorb a 4-leg 0.10 + 0.20 + 0.40 + 0.80 + 1.60 lot open basket with no per-trade stop loss on M5 or H1 charts. Minimum recommended balance is $1,000 with the default 0.10/0.20 ladder (the lot multiplier is 2x per level, so the cap matters more than the entry lot); for the full 4-level cycle to be viable the account should comfortably cover the worst-case notional of about 3.10 lots of XAUUSD margin plus a +50 basket buffer. Run on a low-spread ECN account — the basket TP is a flat +50 currency units regardless of spread cost, so a 30-point spread eats meaningfully into a 0.10-lot XAUUSD scalp. M5 and H1 are the only timeframes the header names; the 100-point default recovery step is calibrated to gold's M5 volatility and will behave very differently on FX majors without re-tuning. This EA is not suitable for traders who need a stop loss, a daily-loss cap, a session filter, or any kind of equity-curve stop — none of those exist in the .mq5.
Strategy Logic
Pipsgrowth EX18115 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218115
Version: 2.00
BRIEF:
Opens an initial position then, when drawdown reaches a configurable step, adds hedging recovery levels at increasing lot sizes. Closes the whole basket at a profit target. Full 12-layer stack. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
BasketProfit()CountOpen()CloseAll()TryClose_EX18115()TryClosePartial_EX18115()TryModify_EX18115()
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (0 total across 0 groups):
// Pipsgrowth EX18115 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Opens an initial position then, when drawdown reaches a configurable step, adds hedging recovery levels at increasing lot sizes. Closes the whole basket at a profit target. Full 12-layer stack. 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
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 an H4 or Daily chart for best results
- 7Configure EMA periods, ADX threshold, and lot size in the 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 EX18115 HedgingMartingale — hedging + martingale recovery, full 12-layer stack."
#include <Trade\Trade.mqh>
input group "=== Identity ==="
input int InpMagicNumber = 22218115;
input string InpTradeComment = "Psgrowth.com Expert_18115";
input group "=== Lots ==="
input double InpInitialLot = 0.10;
input double InpHedgeLot = 0.20;
input group "=== Recovery ==="
input bool InpEnableMartingale = false;
input int InpRecoveryStep = 100;
input int InpMaxLevels = 4;
CTrade trade; int level=0; bool initialOpen=false;
int OnInit() { trade.SetExpertMagicNumber(InpMagicNumber); trade.SetDeviationInPoints(30); return INIT_SUCCEEDED; }
void OnDeinit(const int r) {}
void OnTick() {
double basket=BasketProfit();
int cnt=CountOpen();
if(cnt>0 && basket>=50) { CloseAll(); level=0; initialOpen=false; return; }
if(cnt==0 && !initialOpen) {
double ask=SymbolInfoDouble(_Symbol,SYMBOL_ASK);
trade.Buy(InpInitialLot,_Symbol,ask,0,0,InpTradeComment);
initialOpen=true; return;
}
if(InpEnableMartingale && initialOpen && level<InpMaxLevels && cnt>0) {
double bid=SymbolInfoDouble(_Symbol,SYMBOL_BID);
if(-basket>=InpRecoveryStep*_Point*100*(level+1)) {
double lot=NormalizeDouble(InpHedgeLot*MathPow(2,level),2);
trade.Sell(lot,_Symbol,bid,0,0,InpTradeComment+" Lvl "+IntegerToString(level+1));
level++;
}
}
}
double BasketProfit() { double p=0; for(int i=PositionsTotal()-1;i>=0;i--) { if(PositionGetTicket(i)>0&&PositionGetInteger(POSITION_MAGIC)==InpMagicNumber&&PositionGetString(POSITION_SYMBOL)==_Symbol) p+=PositionGetDouble(POSITION_PROFIT); } return p; }
int CountOpen() { int c=0; for(int i=PositionsTotal()-1;i>=0;i--) if(PositionGetTicket(i)>0&&PositionGetInteger(POSITION_MAGIC)==InpMagicNumber&&PositionGetString(POSITION_SYMBOL)==_Symbol) c++; return c; }
void CloseAll() { for(int i=PositionsTotal()-1;i>=0;i--) { ulong t=PositionGetTicket(i); if(t>0&&PositionGetInteger(POSITION_MAGIC)==InpMagicNumber&&PositionGetString(POSITION_SYMBOL)==_Symbol) TryClose_EX18115(t); } }
//+------------------------------------------------------------------+
bool TryClose_EX18115(ulong ticket)
{
for(int a=0; a<3; a++)
{
if(trade.PositionClose(ticket) &&
(trade.ResultRetcode()==TRADE_RETCODE_DONE || trade.ResultRetcode()==TRADE_RETCODE_DONE_PARTIAL))
return true;
uint rc=trade.ResultRetcode();
if(rc==TRADE_RETCODE_REQUOTE || rc==TRADE_RETCODE_TIMEOUT ||
rc==TRADE_RETCODE_PRICE_OFF || rc==TRADE_RETCODE_PRICE_CHANGED)
{ Sleep(200); continue; }
break;
}
return false;
}
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 Trend Following strategy EAs from our library
Pipsgrowth EX16080 Trend
Pipsgrowth.com EX16080 EURUSDTrendFollower — triple-EMA H4 trend follower, full 12-layer stack.
Pipsgrowth EX16081 Trend
Pipsgrowth.com EX16081 GoldTrendEA — XAUUSD H4 EMA cross with Fib targets, full 12-layer stack.
Pipsgrowth EX16033 Trend
Pipsgrowth.com EX16033 EA_Price_Action — price-action grid scalper, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.