Pipsgrowth EX18013 TrendFollow
MT5 Expert Advisor (Open Source) · USDJPY · M15, M5, H1
Pipsgrowth.com EX18013 USDJPY_Aggressive_Pyramid — Donchian breakout + SuperTrend + protected-pyramid, full 12-layer stack.
Overview
Pipsgrowth EX18013 TrendFollow is built around a single mechanical question: did price just punch out of a 20-bar Donchian channel with the inlined SuperTrend trend filter confirming the same direction. The CoreSignal() function walks the previous 20 closed bars to find the highest high and lowest low, then checks whether the last closed bar's close sits above the upper rail (long) or below the lower rail (short). It does not act on that breakout alone. A second, in-house SuperTrend is computed bar-by-bar by SuperTrendDirClosed() using a 10-bar ATR with a 2.0 multiplier. The walk uses classic carry-forward logic — the upper band only ratchets down when close pierces it, the lower band only ratchets up when close dives through it — and returns +1 for bullish, -1 for bearish. The Donchian and SuperTrend must agree; the function returns 0 unless both are aligned, then a confidence score is produced from the breakout separation in ATR units plus the ADX surplus above the 22.0 threshold.
Before the EA fires a new order, ConfirmBuy() and ConfirmSell() reject signals that fight the higher timeframe. The filter is a 50-period EMA pulled from H1 (g_hHTFema). A buy needs bid > H1 EMA(50) and either the H1 EMA rising or the live bid above the current bar's H1 EMA value. A sell needs the mirror. RSI(14) then vetoes exhaustion entries: longs require RSI between 45 and 78, shorts between 22 and 55. The 0–100 confidence score is never used as a sizing input — it is logged for diagnostics. The NoTradeGates() block adds the operational filters: kill-switch, capital-cap floor breach, active cooldown timer, daily realised loss (3% of effective cap), weekly realised loss (6% of effective cap), spread wider than 30% of ATR, server hour outside 00:00–21:00, weekend, position cap of 5, and the regime classifier.
The regime classifier in UpdateRegime() is a 7-state machine using ADX(14), ATR-percentile rank over a 100-bar lookback, and Bollinger Band width percentile. ADX ≥ 30 lands in REG_STRONG_TREND; ADX between the user threshold (22) and 30 lands in REG_WEAK_TREND. Bollinger width below the 20th percentile is REG_COMPRESS. Width above the 80th percentile combined with ATR-percentile above 80% is REG_EXPAND. ATR-percentile above 80% on its own is REG_BREAKOUT. Width below the 35th percentile without compress markers is REG_RANGE. Everything else is REG_CHOPPY. RegimeAllowsEntry() only lets through StrongTrend, WeakTrend, Breakout, and Expand. Range, Compress, and Choppy are hard-blocks for new entries. This is the single gate that protects the strategy from a Donchian breakout that fires into a flat tape.
The pyramid layer is the defining feature of EX18013. The InpPyramidEnable input is off by default, and PYRAMID_MAX_LEVELS is hard-coded at 5. When pyramid is on, ManageEntries() calls AllBuysProtected() (or AllSellsProtected()) before any add. The protected-gate requires every open position on that side to have its stop moved to at least entry price + 0.05×ATR — a strict, low-buffer version of the original 1220 last-trade-risk-free rule. The spacing gate then checks that the live ask is at least 0.5×ATR beyond the most recent entry, so the EA is always adding into a trend with the previous tranche's risk eliminated. The new tranche is sized independently by CalcLots() and tagged PYRAMID#2 through PYRAMID#5 in the trade comment for trace-back. A per-bar guard (g_lastPyramidBar) prevents two adds in the same bar.
In-trade management runs every tick via ManageOpen(). Three hard exits check first. A volatility-spike exit fires when the current ATR exceeds 2.6× the 20-bar ATR average AND the position is in profit — this is a fast unwind before the move blows through stops. An opposite-SuperTrend exit fires when the inlined SuperTrend flips to the other side AND the position is in profit. A regime-change exit fires when the classifier returns Choppy, Range, or Compress AND the position is in profit. Each of these is gated by profitDist >= 0 so a position can sit through a noisy pullback without being closed at a loss by a premature flip. After the hard exits, the management logic moves stop to break-even once profit exceeds 1.0×ATR (the new stop sits at entry + 0.1×ATR buffer, one-shot). At 1.5×ATR profit, the ATR trail takes over, ratcheting the stop each tick to bid – 1.0×ATR for longs (ask + 1.0×ATR for shorts). Partial TP closes 50% of the position when price reaches 50% of the full TP distance and the residual volume stays above 1.5× the broker's minimum lot — the rest rides the trail.
Risk sits on top of the entries. InpRiskPercent (0.5% default) feeds a fixed-fractional lot calculation against the effective capital cap, which is min(InpCapAmount, equity). With InpCapAmount = 0 the cap is disabled and the EA uses full equity. InpCapFloor = 50 blocks new entries when the effective cap drops below $50. A 3-loss streak triggers a 6-hour cooldown. Daily and weekly realised PnL are recomputed from deal history at the start of every tick by UpdateRealized() and SumRealized(). OnTradeTransaction() watches each deal and increments g_consecLosses on losses, resetting to zero on a win. The kill-switch (InpKillSwitch) flattens every position this EA owns and skips all subsequent entry logic until toggled off. Friday 20:00 server triggers ShouldCloseForWeekend(), which walks every position and calls ClosePosition() to leave the book flat over the weekend gap.
Backtest hygiene is enforced in OnTester(). The custom criterion is (net * max(0.01, profitFactor)) / (1 + balance-DD%), gated by a minimum of 30 trades. Strategies that pass the gate but show a poor PF or a deep drawdown score poorly even with a positive net, so the optimiser naturally prefers smoother equity curves rather than one or two lucky outliers. The retry-and-filling logic uses FOK when supported, then IOC, then RETURN — with a 3-attempt loop on requote, price-off, price-changed, and timeout, sleeping 200ms between attempts for closes and partials and 100ms for modifies. Slippage is capped at 30 points. The combination means a runner strategy that depends on the pyramid and the trail can survive a thin-tape re-quote without throwing an order.
EX18013 is tuned for USDJPY on M15 with M5 and H1 as workable alternatives. The default is 0.5% risk per tranche, 0.5×ATR minimum profit between pyramid adds, 2.0×ATR stop and 3.0×ATR target (1.5:1 reward-to-risk on a clean setup, with a 1.2 minimum that rejects compressed breakouts that cannot offer the room). The H1 EMA(50) and the in-house SuperTrend both want a trending market, the regime classifier and the cooldown both want to skip chop, and the protected-gate ensures any pyramid add is funded by a position that no longer carries risk.
Strategy Deep Dive
Every tick, OnTick() refreshes five indicator handles (ATR14, ADX14, RSI14, BB20-2, HTF-EMA50-H1) and feeds the closed-bar arrays into UpdateRegime(), which classifies the market into 7 states. NoTradeGates() then runs the safety stack: kill-switch, capital-cap floor, cooldown timer, daily/weekly realised loss against the 3%/6% limits, spread > 30% of ATR, server hour outside 00:00–21:00, weekend, and the 5-position cap. On a new bar, CoreSignal() walks the previous 20 closes/highs/lows to compute the Donchian rails and calls SuperTrendDirClosed() to walk the same bars with the inlined 10/2.0 SuperTrend — both must agree on direction with ADX(14) ≥ 22 to produce a signal. ConfirmBuy()/ConfirmSell() then check H1 EMA(50) agreement and RSI(14) exhaustion bands, and ManageEntries() sizes the tranche via CalcLots() against the effective capital cap. When pyramid is on, the protected-gate (AllBuysProtected/AllSellsProtected) requires every open position on the same side to have its stop moved to at least entry + 0.05×ATR before any add, and the spacing gate requires price to be at least 0.5×ATR beyond the most recent entry. ManageOpen() runs every tick and stacks three profit-gated hard exits (vol-spike 2.6× ATR, opposite SuperTrend flip, regime change to Choppy/Range/Compress), then break-even at 1.0×ATR profit + 0.1 buffer, ATR trail at 1.5×ATR start / 1.0×ATR distance, and a 50% partial TP at 50% of the TP distance. OnTradeTransaction() watches each deal for the 3-loss / 6-hour cooldown; Friday 20:00 server triggers the weekend flat.
Long entry fires when the last closed bar's close prints above the 20-bar Donchian upper rail and the inlined SuperTrend (10-bar ATR, 2.0 multiplier) returns bullish — with ADX(14) ≥ 22, H1 EMA(50) agreeing on the long side, and RSI(14) inside 45–78. Sell entry is the mirror: close below the 20-bar Donchian lower rail, SuperTrend bearish, H1 EMA(50) on the sell side, RSI(14) between 22–55. The regime classifier must be in StrongTrend, WeakTrend, Breakout, or Expand — Choppy, Range, and Compress are hard-blocks.
Three hard exits close the position when in profit: a volatility-spike exit when the current ATR exceeds 2.6× the 20-bar average, an opposite-SuperTrend flip on the closed bar, and a regime change into Choppy, Range, or Compress. Soft exits include the 2.0×ATR target (3.0×ATR default TP) and the 50% partial TP at 50% of the full TP distance. The Friday 20:00 server weekend-flat block closes every open position this EA owns before the gap.
Initial stop is 2.0×ATR(14) below entry for longs, above entry for shorts. The stop moves to break-even (entry + 0.1×ATR buffer) on a one-shot basis once profit exceeds 1.0×ATR, then the ATR trail takes over at 1.5×ATR profit and ratchets the stop to bid/ask minus 1.0×ATR each tick. The RespectStopsBuySL and RespectStopsSellSL helpers enforce the broker's SYMBOL_TRADE_STOPS_LEVEL minimum distance.
Initial take-profit sits at 3.0×ATR(14) from entry (1.5:1 reward-to-risk on a clean setup). A pre-trade gate in ManageEntries() rejects any signal whose actual reward-to-risk falls below the InpMinRR of 1.2, so the effective TP is never narrower than 1.2× the stop distance. Partial TP closes 50% of the position when price reaches 50% of the full TP distance and the residual volume remains above 1.5× the broker's minimum lot.
USDJPY on the M15 timeframe (with M5 and H1 as workable alternatives) is the target. A $100 minimum deposit supports the 0.5% default risk per tranche, the protected-pyramid up to 5 levels, and the capital cap with the $50 floor. The strategy wants an ECN or RAW-spread broker with low spread — the spread filter rejects entries wider than 30% of ATR, so a 1-pip spread on USDJPY is comfortable and a 3-pip retail spread will block most sessions. The 00:00–21:00 server window covers Tokyo, London, and New York, with the 20:00 Friday weekend-flat suitable for accounts that do not want to hold USDJPY over the rollover. The MEDIUM risk label reflects the 0.5% base risk plus the 5-position pyramid ceiling and the 3%/6% daily/weekly loss limits, but the protected-gate and the regime block keep a single trending market from turning into a runaway exposure.
Strategy Logic
Pipsgrowth EX18013 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218013
Version: 2.00
BRIEF:
Aggressive Pyramid trend-follower. Core signal: Donchian N-bar channel breakout confirmed by inlined SuperTrend ATR trailing-stop flip. Pyramid hard-capped at 5 levels and gated by the last-position-risk-free rule; adds spaced by min ATR profit-distance. Entries gated by regime (ADX+ATR-pct+BB-width), HTF-EMA agreement, RSI not-extreme, min R/R, spread/session. Full in-trade management: BE, partial TP, ATR trail, regime exit. Capital cap, daily/weekly loss limits, cooldown. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
ATRADXRSIBB- HTFema
KEY FUNCTIONS:
NormPrice()ClampVolume()StopsLevelPrice()RespectStopsBuySL()RespectStopsSellSL()LogFail()CountPositions()SumRealized()UpdateRegime()RegimeAllowsEntry()NoTradeGates()CoreSignal()- ...and 21 more
INTERNAL CONSTANTS (25 total):
ADX_PERIOD= 14 //ADXperiodRSI_PERIOD= 14 //RSIperiodBB_PERIOD= 20 // Bollinger periodBB_DEVIATION=2.0// Bollinger deviationATR_PERIOD= 14 //ATRperiod (also used by inlinedSuperTrend)ATR_PCT_LOOKBACK= 100 //ATR-percentile lookbackHTF_TIMEFRAME=PERIOD_H1//HTFtimeframe forEMA-agreement filterHTF_EMA_PERIOD= 50 //HTFEMAperiodPYRAMID_MAX_LEVELS= 5 // Pyramid hard cap (per spec)PYRAMID_MIN_PROFIT_ATR=0.5// Min profit (xATR) before next addPYRAMID_ATR_SPACING=1.0// MinATRspacing between pyramid addsMAX_BARS_HOLD= 0 // Time-based exit (0 = disabled)BE_ATR_MULT=1.0// Break-even trigger (xATR)BE_BUFFER_ATR=0.1// Break-even buffer (xATR)TRAIL_ATR_MULT=1.5//ATRtrail start (xATRprofit)- ...and 10 more
INPUT PARAMETERS (21 total across 5 groups):
- [=== Identity ===]
InpMagicNum=22218013// Magic number - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_18013" // Trade comment - [=== Identity ===]
InpSlippagePts= 30 // Max slippage (points) - [=== Identity ===]
InpDryRun=true// Dry-run (no live sends) - [=== Risk & Sizing ===]
InpRiskPercent=0.5// Risk % per trade (of effective cap) - [=== Risk & Sizing ===]
InpDailyLossPct=3.0// Daily loss limit % - [=== Risk & Sizing ===]
InpWeeklyLossPct=6.0// Weekly loss limit % - [=== Risk & Sizing ===]
InpMaxPositions= 5 // Max concurrent positions (pyramid cap) - [=== Risk & Sizing ===]
InpCooldownLosses= 3 // Cooldown after N losses (count) - [=== Risk & Sizing ===]
InpKillSwitch=false// Kill switch (flatten+halt) - [=== Capital Allocation Cap ===]
InpCapAmount=0.0// Capital cap amount (USDequity) - [=== Capital Allocation Cap ===]
InpCapFloor=50.0// Capital floor (USD, block entries) - [===
Signal(Donchian +SuperTrend) ===]InpDirection=TRADE_BOTH// Trade direction - [===
Signal(Donchian +SuperTrend) ===]InpDonchianPeriod= 20 // Donchian breakout period (bars) - [===
Signal(Donchian +SuperTrend) ===]InpSTPeriod= 10 //SuperTrendATRperiod - [===
Signal(Donchian +SuperTrend) ===]InpSTMultiplier=2.0//SuperTrendATRmultiplier - [===
Signal(Donchian +SuperTrend) ===]InpAdxThreshold=22.0//ADXthreshold for trend strength - [=== Exit / Manage ===]
InpSLMultiplier=2.0// Stop loss (xATR) - [=== Exit / Manage ===]
InpTPMultiplier=3.0// Take profit (xATR) - [=== Exit / Manage ===]
InpMinRR=1.2// Minimum reward:risk ratio - [=== Exit / Manage ===]
InpPyramidEnable=false// Enable protected-pyramiding (defaultOFF, capped)
// Pipsgrowth EX18013 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Aggressive Pyramid trend-follower. Core signal: Donchian N-bar channel breakout confirmed by inlined SuperTrend ATR trailing-stop flip. Pyramid hard-capped at 5 levels and gated by the last-position-risk-free rule; adds spaced by min ATR profit-distance. Entries gated by regime (ADX+ATR-pct+BB-width), HTF-EMA agreement, RSI not-extreme, min R/R, spread/session. Full in-trade management: BE, partial TP, ATR trail, regime exit. Capital cap, daily/weekly loss limits, cooldown. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
ON_INIT:
Create indicator handles: ATR, ADX, RSI, BB, HTFema
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
EA Parameters
| Parameter | Default | Description |
|---|---|---|
| InpMagicNum | 22218013 | Magic number |
| InpTradeComment | "Psgrowth.com Expert_18013" | Trade comment |
| InpSlippagePts | 30 | Max slippage (points) |
| InpDryRun | true | Dry-run (no live sends) |
| InpRiskPercent | 0.5 | Risk % per trade (of effective cap) |
| InpDailyLossPct | 3.0 | Daily loss limit % |
| InpWeeklyLossPct | 6.0 | Weekly loss limit % |
| InpMaxPositions | 5 | Max concurrent positions (pyramid cap) |
| InpCooldownLosses | 3 | Cooldown after N losses (count) |
| InpKillSwitch | false | Kill switch (flatten+halt) |
| InpCapAmount | 0.0 | Capital cap amount (USD equity) |
| InpCapFloor | 50.0 | Capital floor (USD, block entries) |
| InpDirection | TRADE_BOTH | Trade direction |
| InpDonchianPeriod | 20 | Donchian breakout period (bars) |
| InpSTPeriod | 10 | SuperTrend ATR period |
| InpSTMultiplier | 2.0 | SuperTrend ATR multiplier |
| InpAdxThreshold | 22.0 | ADX threshold for trend strength |
| InpSLMultiplier | 2.0 | Stop loss (xATR) |
| InpTPMultiplier | 3.0 | Take profit (xATR) |
| InpMinRR | 1.2 | Minimum reward:risk ratio |
| InpPyramidEnable | false | Enable protected-pyramiding (default OFF, capped) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18013 USDJPY_Aggressive_Pyramid — Donchian breakout + SuperTrend + protected-pyramid, 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>
//========================== TUNABLE CONSTANTS ============================
// (kept out of the input surface to satisfy the 12-22 input cap)
#define ADX_PERIOD 14 // ADX period
#define RSI_PERIOD 14 // RSI period
#define BB_PERIOD 20 // Bollinger period
#define BB_DEVIATION 2.0 // Bollinger deviation
#define ATR_PERIOD 14 // ATR period (also used by inlined SuperTrend)
#define ATR_PCT_LOOKBACK 100 // ATR-percentile lookback
#define HTF_TIMEFRAME PERIOD_H1 // HTF timeframe for EMA-agreement filter
#define HTF_EMA_PERIOD 50 // HTF EMA period
#define PYRAMID_MAX_LEVELS 5 // Pyramid hard cap (per spec)
#define PYRAMID_MIN_PROFIT_ATR 0.5 // Min profit (xATR) before next add
#define PYRAMID_ATR_SPACING 1.0 // Min ATR spacing between pyramid adds
#define MAX_BARS_HOLD 0 // Time-based exit (0 = disabled)
#define BE_ATR_MULT 1.0 // Break-even trigger (xATR)
#define BE_BUFFER_ATR 0.1 // Break-even buffer (xATR)
#define TRAIL_ATR_MULT 1.5 // ATR trail start (xATR profit)
#define TRAIL_ATR_DIST 1.0 // ATR trail distance (xATR)
#define PARTIAL_TP_RATIO 0.50 // Partial TP fraction at TP1
#define SESSION_START_HOUR 0 // Session window start (broker server time)
#define SESSION_END_HOUR 21 // Session window end (broker server time)
#define MAX_SPREAD_PCT 0.30 // Max spread as fraction of ATR (30%)
#define VOL_SPIKE_MULT 2.6 // ATR-spike exit multiplier
#define WEEKEND_CLOSE_HOUR 20 // Friday close-all hour
#define VOL_EXIT_ENABLE true // Volatility-spike-exit toggle
#define PROT_SL_ATR_BUFFER 0.05 // Min SL-in-profit buffer (xATR) for protected gate
//+------------------------------------------------------------------+
//| ENUMERATIONS |
//+------------------------------------------------------------------+
enum ENUM_TRADE_DIRECTION
{
TRADE_BUY_ONLY = 0, // Buy Only
TRADE_SELL_ONLY = 1, // Sell Only
TRADE_BOTH = 2 // Both Directions
};
enum ENUM_REGIME
{
REG_STRONG_TREND = 0, // StrongTrend
REG_WEAK_TREND = 1, // WeakTrend
REG_RANGE = 2, // Range
REG_BREAKOUT = 3, // Breakout
REG_COMPRESS = 4, // Compress
REG_EXPAND = 5, // Expand
REG_CHOPPY = 6 // Choppy
};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.