Pipsgrowth EX18008 TrendFollow
MT5 Expert Advisor (Open Source) · USDJPY · M15, M5, H1
Pipsgrowth.com EX18008 TrendRider_PyramidTrend_USDJPY — Triple-EMA-stack + Hull-MA + protected-pyramid, full 12-layer stack.
Overview
Pipsgrowth EX18008 is a USDJPY-tuned trend rider that pairs an hourly triple-EMA stack with a fifteen-minute Hull-MA trigger, then layers in a seven-state market regime, capital-allocation cap, and a distinctive protected-pyramid gate before it ever sends a single order. The EA's brief in the source header is explicit: H1 directional bias from a 21/50/200 EMA stack, M15 inline Hull-MA slope cross on the closed bar, and ADX must clear 22 for the signal to even exist. The full architecture is split across twelve named layers — REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester — and every layer is wired through explicit, named functions rather than being collapsed into a single OnTick body.
The H1 stack does the heavy lifting on direction. Three EMAs run on the hourly chart (periods 21, 50, 200 by default) and the EMAStackDir() function returns a tri-state label — STACK_BULL when fast > medium > slow on the closed bar and the current bar is not retracing through either, STACK_BEAR when the inverse holds, otherwise STACK_FLAT. There is no fractional or weighted read; the stack either is bullish or it isn't, which removes a large class of mid-cross whipsaw trades. To trigger a real signal, the M15 Hull-MA must confirm: HullDir() computes an inline Hull-MA from a raw close copy (Hull = 2*WMA(n/2) − WMA(n)) over the user-defined period (default 34) and asks whether the last three values are monotonically rising, monotonically falling, or flat. A long signal only fires when the H1 stack is bullish AND the M15 Hull slope is rising on the closed bar; a short signal only fires when both flip bearish. The ATR(14) on the working timeframe then feeds a confidence score — 50 baseline plus up to 50 from price-to-Hull distance scaled by ATR and from ADX above its 22 threshold — capped at 100.
That signal still has to pass a confirm layer before it becomes an order. ConfirmBuy() and ConfirmSell() demand that bid agree with the H1 50-EMA: long needs bid above the 50-EMA and either the 50-EMA still rising or bid above its current value; short needs the inverse. The confirm step also requires RSI(14) to sit in a trend band (45–78 for longs, 22–55 for shorts), so RSI outright overbought blocks new longs and outright oversold blocks new shorts. A minimum reward-to-risk filter of 1.2 (set by InpMinRR) is enforced right after the SL/TP distances are computed from ATR. With the default SL multiplier of 2.0 and TP multiplier of 3.0, the planned R:R is 1.5, comfortably above the 1.2 floor.
Regime classification is the safety net under the signal stack. UpdateRegime() runs every tick from a 100-bar ATR history plus the live ADX(14) and Bollinger(20, 2.0) width, and emits one of seven states: STRONG_TREND (ADX ≥ 30), WEAK_TREND (ADX ≥ 22), BREAKOUT (ATR percentile > 80%), EXPAND (BB width percentile > 80% AND ATR percentile > 80%), RANGE (BB width percentile < 35%), COMPRESS (BB width percentile < 20%), and CHOPPY (everything else). RegimeAllowsEntry() returns false for RANGE, COMPRESS, and CHOPPY — three out of seven — which is roughly 43% of bars in a typical FX session. When the regime hard-blooms into CHOPPY, RANGE, or COMPRESS while a position is open and in profit, ManageOpen() closes the trade on the next tick.
Risk is fixed-fractional. CalcLots() reads the effective capital cap (the minimum of InpCapAmount and current equity, so 0.0 disables the cap and lets equity drive sizing) and computes lots = cap × 0.5% / (slTicks × tickValue), then ClampVolume() snaps to the broker's volume step and clamps to the symbol's volMin/volMax. A capital floor of 50 USD blocks all entries when the cap dips below it. Daily and weekly loss limits are evaluated against the cap (3% / 6% defaults), realised PnL is summed by SumRealized() from the deal history, and a 3-loss-in-a-row trigger sets a six-hour cooldown via g_cooldownUntil. NoTradeGates() also enforces the 0–21 server-hour session, max spread of 30% of ATR(14), the regime allow-list, the max-positions cap of 5, and the broker trade-mode check. The kill-switch input flattens and halts if flipped on.
The protected-pyramid gate is the standout design choice. With InpPyramidEnable off by default, EX18008 trades a single position per side; with it on, the EA can scale up to five adds per side, but the AllBuysProtected() / AllSellsProtected() functions refuse the new add unless every existing position on that side already has its stop moved to entry-plus-buffer in profit (the buffer is 0.05 × ATR by default). The new add must also be at least 0.5 × ATR beyond the previous entry price and the lot has to clear the 0.5% risk cap. This is meaningfully stricter than a plain pyramid — it refuses to add a fresh position into a portfolio of unprotected, underwater entries.
Position management runs on every tick. ManageOpen() reads the live Hull direction and closes the position (in profit only) if the M15 Hull has flipped to the opposite slope. A stochastic %K cross from overbought 80 closes longs; a cross from oversold 20 closes shorts. A volatility-spike detector sums the last 20 ATR values and force-closes any in-profit position the moment live ATR exceeds 2.6 × that average. For trades that survive those hard exits, ManageOpen() ratchets the stop: at +1.0 × ATR it pulls to entry + 0.1 × ATR (a one-shot break-even with a small buffer), and at +1.5 × ATR it starts an ATR trail at a distance of 1.0 × ATR. At 50% of the planned TP distance, the EA partial-closes half the position via PositionClosePartial; the remainder runs to TP or the trailing stop. The opposite-signal flag inverts on the close-bar Hull flip, and on a Friday 20:00 server-time check the EA flattens every position to avoid weekend gap risk. Slippage is capped at 30 points and every send goes through a three-attempt retry loop with 200 ms (close) or 100 ms (modify) sleeps to handle requotes and price-off returns.
For the optimizer, OnTester() returns (netProfit × max(0.01, profitFactor)) / (1 + balanceDrawdownPercent) when there are at least 30 trades; this rewards raw profit and profit factor while still penalising the depth of the drawdown. The default file ships with InpDryRun = true, which is a useful self-test mode — every buy and sell logs its would-be ticket, price, SL, and TP without actually sending, so you can confirm signal flow on a demo chart before flipping the live switch.
EX18008 was tuned on USDJPY but the implementation is broker-portable. The header explicitly notes it works on FX majors and metals and is portable across M5, M15, and H1. For a forward test, expect a relatively low trade count per week (the regime block plus the ADX threshold plus the H1+Hull agreement makes this a selective strategy, not a frequent-fire one). On a typical Tokyo and London overlap you should see the most setups, with USDJPY offering the cleanest H1-stack swings. Risk the EA at 0.5% per trade on a small account to confirm drawdown tolerance, then consider raising the risk percent only after a meaningful forward sample size of 100+ trades.
Strategy Deep Dive
EX18008 reads nine indicator handles on the working timeframe — ATR(14), ADX(14), RSI(14), Bollinger(20, 2.0), Stochastic(14, 3, 3), H1 50-EMA, and a triple H1 EMA stack of 21/50/200 — plus an inline Hull-MA(34) computed in place from a CopyClose buffer. The new-bar entry gate in OnTick() calls CoreSignal() to combine the H1 stack direction and the M15 Hull slope into a tri-state signal with a confidence score, then passes it through ConfirmBuy()/ConfirmSell(), the regime allow-list (STRONG_TREND, WEAK_TREND, BREAKOUT, EXPAND), the 1.2 R:R floor, and the full NoTradeGates() stack (kill-switch, capital-floor, cooldown, daily/weekly loss, max-spread 30% of ATR, session 0–21 server, max positions, regime, broker trade mode). Sizing is fixed-fractional off the effective cap; the protected-pyramid gate refuses any pyramid add unless every prior position on that side has its stop moved into profit. ManageOpen() runs every tick to apply BE, trail, partial TP, and the four hard exits (Hull flip, stochastic, volatility-spike, regime change) on each open position.
Long entries require a triple-stack bullish alignment on H1 (EMA21 > EMA50 > EMA200 with non-retracing current bar) confirmed by a rising M15 Hull-MA(34) slope on the closed bar and ADX(14) above 22 on the working timeframe. The signal then passes a confirm layer (bid above H1 50-EMA, RSI(14) between 45 and 78) and a minimum 1.2 reward-to-risk gate before any order is sent. Shorts are the mirror image with stack bearish, Hull falling, bid below H1 50-EMA, and RSI between 22 and 55.
Positions are closed on the next tick in profit only when the M15 Hull-MA slope flips against the position direction, when stochastic %K crosses back from overbought (80) or oversold (20), when live ATR exceeds 2.6× the 20-bar ATR average (volatility-spike exit), or when the regime falls to CHOPPY, RANGE, or COMPRESS. Surviving positions ratchet the stop: break-even at +1.0×ATR (to entry +0.1×ATR), ATR trail starting at +1.5×ATR with 1.0×ATR distance, and a 50% partial close at 50% of the planned TP distance. On Friday 20:00 server time every position is flattened for the weekend.
Stop loss is computed per trade as InpSLMultiplier × ATR(14) on the working timeframe — the default 2.0 multiplier gives a 2×ATR stop measured from entry. The EA also enforces a risk cap of 0.5% of the effective capital per trade and a per-side maximum of 5 positions, plus a one-shot break-even ratchet that pulls the stop to entry + 0.1×ATR once price reaches +1.0×ATR in profit.
Take profit is computed as InpTPMultiplier × ATR(14) from entry, with a 3.0 default giving 3×ATR — a 1.5:1 reward-to-risk ratio against the 2×ATR stop, well above the 1.2 InpMinRR floor. At 50% of the planned TP distance, the EA partial-closes half the position volume; the remainder runs to either the full TP or the trailing stop.
Best deployed on USDJPY at M15 with a $100 minimum balance — the EA was tuned on this pair, and the H1 stack + M15 Hull logic is calibrated for USDJPY's directional range behaviour. The 0.5% per-trade risk and 3%/6% daily/weekly loss limits suit a $100–$1,000 retail account, and the capital-allocation cap (InpCapAmount) is the right way to scale it up for prop or larger retail books. The default session window is 0–21 server time, which on most brokers covers Tokyo through New York — set the EA on a chart that aligns to your broker's GMT offset and consider disabling around Friday 20:00 server time is already handled by the in-built weekend-flat rule. Use a broker with low spreads on USDJPY (the 30%-of-ATR spread cap is generous but tight JPY spreads improve the entry frequency) and standard ECN or RAW execution; the auto FOK/IOC/RETURN fill-mode detection in OnInit works with virtually any modern broker.
Strategy Logic
Pipsgrowth EX18008 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218008
Version: 2.00
BRIEF:
Triple-EMA-Stack + Hull-MA Trigger Protected-Pyramid Rider — H1 triple EMA stack (fast/medium/slow) directional bias + M15 inline Hull-MA slope cross trigger on CLOSED bar. ADX must be above threshold. Pyramid OFF by default with unique all-positions-protected gate. Full regime layer (ADX+ATR-pctile +BB-width) gates entries and sizing. Capital-allocation-cap, ATR-trail, break-even, partial TP, opposite-Hull exit, regime- change exit, volatility-spike exit, stochastic exit, daily/ weekly loss limits, no-trade gates, broker-portable fills. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
ATRADXRSIBB- HTFema
- Stoch
EmaFastEmaMedEmaSlow
KEY FUNCTIONS:
NormPrice()ClampVolume()StopsLevelPrice()RespectStopsBuySL()RespectStopsSellSL()LogFail()CountPositions()SumRealized()WMA()HullMAFromArr()UpdateRegime()RegimeAllowsEntry()- ...and 23 more
INTERNAL CONSTANTS (31 total):
ADX_PERIOD= 14 //ADXperiodRSI_PERIOD= 14 //RSIperiodBB_PERIOD= 20 // Bollinger periodBB_DEVIATION=2.0// Bollinger deviationATR_PERIOD= 14 //ATRperiodATR_PCT_LOOKBACK= 100 //ATR-percentile lookbackHTF_TIMEFRAME=PERIOD_H1//HTFtimeframe forEMA-stack +EMA-confirmHTF_EMA_PERIOD= 50 //HTFEMAperiodPYRAMID_MAX_LEVELS= 5 // Pyramid hard capPYRAMID_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 16 more
INPUT PARAMETERS (23 total across 6 groups):
- [=== Identity ===]
InpMagicNum=22218008// Magic number - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_18008" // 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(H1EMAstack) ===]InpDirection=TRADE_BOTH// Trade direction - [===
Signal(H1EMAstack) ===]InpEmaFast= 21 //H1EMAFast period - [===
Signal(H1EMAstack) ===]InpEmaMedium= 50 //H1EMAMedium period - [===
Signal(H1EMAstack) ===]InpEmaSlow= 200 //H1EMASlow period - [=== Regime / Confirm ===]
InpHullPeriod= 34 //M15Hull MA period - [=== Regime / Confirm ===]
InpAdxThreshold=22.0//ADXthreshold for trend strength - [=== Regime / Confirm ===]
InpADXStrong=30.0//ADXforStrongTrendregime - [=== 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 (OFFdefault)
// Pipsgrowth EX18008 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Triple-EMA-Stack + Hull-MA Trigger Protected-Pyramid Rider — H1 triple EMA stack (fast/medium/slow) directional bias + M15 inline Hull-MA slope cross trigger on CLOSED bar. ADX must be above threshold. Pyramid OFF by default with unique all-positions-protected gate. Full regime layer (ADX+ATR-pctile +BB-width) gates entries and sizing. Capital-allocation-cap, ATR-trail, break-even, partial TP, opposite-Hull exit, regime- change exit, volatility-spike exit, stochastic exit, daily/ weekly loss limits, no-trade gates, broker-portable fills. 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, Stoch, EmaFast, EmaMed, EmaSlow
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 | 22218008 | Magic number |
| InpTradeComment | "Psgrowth.com Expert_18008" | 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 |
| InpEmaFast | 21 | H1 EMA Fast period |
| InpEmaMedium | 50 | H1 EMA Medium period |
| InpEmaSlow | 200 | H1 EMA Slow period |
| InpHullPeriod | 34 | M15 Hull MA period |
| InpAdxThreshold | 22.0 | ADX threshold for trend strength |
| InpADXStrong | 30.0 | ADX for StrongTrend regime |
| InpSLMultiplier | 2.0 | Stop loss (xATR) |
| InpTPMultiplier | 3.0 | Take profit (xATR) |
| InpMinRR | 1.2 | Minimum reward:risk ratio |
| InpPyramidEnable | false | Enable protected-pyramiding (OFF default) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18008 TrendRider_PyramidTrend_USDJPY — Triple-EMA-stack + Hull-MA + 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
#define ATR_PCT_LOOKBACK 100 // ATR-percentile lookback
#define HTF_TIMEFRAME PERIOD_H1 // HTF timeframe for EMA-stack + EMA-confirm
#define HTF_EMA_PERIOD 50 // HTF EMA period
#define PYRAMID_MAX_LEVELS 5 // Pyramid hard cap
#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 STOCH_K 14 // Stochastic %K
#define STOCH_D 3 // Stochastic %D
#define STOCH_SLOWING 3 // Stochastic slowing
#define STOCH_OVERBOUGHT 80.0 // Stochastic overbought
#define STOCH_OVERSOLD 20.0 // Stochastic oversold
#define VOL_SPIKE_MULT 2.6 // ATR-spike exit multiplier
#define WEEKEND_CLOSE_HOUR 20 // Friday close-all hour
#define STOCH_EXIT_ENABLE true // Stochastic-exit toggle
#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, // WeakTrendFull 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.