Pipsgrowth EX18016 TrendFollow
MT5 Expert Advisor (Open Source) · USDJPY · M15
Pipsgrowth.com EX18016 USDJPY_Hull_Supertrend_Pyramid — Hull MA + SuperTrend composite + capped pyramid, full 12-layer stack.
Overview
Pipsgrowth EX18016 stacks two trend primitives — a hand-coded Hull Moving Average and a hand-coded SuperTrend — and only fires when both agree, the higher-timeframe direction supports them, and the regime is one of four expansion- or trend-flavoured states. The result is a USDJPY-tuned M15 trend-follower that does not chase mean-reversion, fade breakouts, or act on noise. It is engineered for traders who want a clean trend model with multi-timeframe agreement, explicit regime gating, and a conservative scaling rule that most default to single-position.
The signal layer is built from scratch inside the EA, not delegated to the iCustom handle. The Hull MA fast primitive uses two linearly weighted moving averages with period n/2 and n, then takes a third LWMA over the difference series with period sqrt(n). The HullMAAt() function pulls both underlying WMA buffers, builds the 2*WMA(n/2) − WMA(n) differenced array, and applies a triangular kernel of weights over the sqrt(n) samples. The result is a Hull curve with minimal lag that still filters out fast wiggles. The fast Hull period defaults to 20. A slope check (current value vs prior bar) decides direction.
The SuperTrend is also inlined. The SuperTrendAt() function walks backward over a window of 50 bars, holding an upper band, a lower band, and a direction flag. At each bar it computes the basic upper/lower from HL2 ± ATR*InpSTMultiplier, then tightens the bands using the classic carry-forward rule (raise lower only when the prior close is above the previous upper; lower upper only when the prior close is below the previous lower). Direction flips when the close breaks the active band. The result is the same SuperTrend line most traders are familiar with, but recomputed from inlined ATR data so the EA owns the math end-to-end. Default ATR period is 10, default multiplier is 3.0.
The signal fires only when three things agree: the fast Hull is sloping up (or down), the inlined SuperTrend direction is +1 (or −1), and the closed-bar close is on the correct side of the Hull. This triple-lock eliminates most single-indicator whipsaws. SignalComposite() returns +1 for a buy trigger, −1 for a sell trigger, and 0 otherwise. The function explicitly suppresses signals in regime codes 2 (Range), 4 (Compress), and 6 (Choppy) — the three states where a trend model has no edge.
RegimeClassify() runs a 7-state classification on every cycle. ADX (period 14) above 25 with ATR-percentile (50-bar lookback) at or above 60% is StrongTrend. ADX above 20 with percentile at or above 40% is WeakTrend. Bollinger width expansion with percentile at or above 70% is Breakout. Bollinger width expansion with percentile at or above 50% is Expand. ATR-percentile at or below 20% is Compress. ADX below 15 is Choppy. Everything else is Range. A 4-bit mask (REGIME_GATE_MASK = 0x4B) restricts new entries to StrongTrend, WeakTrend, Breakout, and Expand. Compress, Range, and Choppy are blocked at the regime layer, and RegimeAllowed() enforces it again as a redundant belt-and-suspenders in NoTradeBlock().
ConfirmOK() adds a higher-timeframe filter. The HTF Hull MA (period 50, default H1) must slope the same way as the fast Hull on M15, and the closed-bar close must sit on the correct side of the HTF EMA(50). Both conditions are mandatory. A R/R feasibility check is included so the EA only fires when SL distance and TP distance (1.5×SL) are both positive and the implied reward-to-risk clears the InpMinRR floor of 1.5. A server-time session window is also enforced (default 0–23, full day, with the EA's IsWeekendClose() closing every position on Friday at 22:00 server time and refusing to open new ones across Saturday and Sunday).
Risk and sizing follow a standard 0.5%-of-equity model with a 0.01-lot fixed fallback when the account is too small for proper risk math. The capital cap is built in: EffectiveCapital() returns min(InpCapitalCapAmount, account_equity), and a hard floor of 50 USD blocks new entries once effective capital drops below the floor. The daily loss limit is 3% of effective capital, calculated from realized P&L since the day's midnight stamp. The default capital cap amount is 0.0, which disables the cap and uses raw equity — set it above 0 to throttle exposure to a fixed dollar figure.
The pyramid stack is the most unusual design choice. InpPyramidEnabled defaults to false, so out of the box the EA holds a maximum of one position per side. When enabled, PyramidAllowed() enforces a triple-gated rule: the new add requires (1) every same-side position to already be in profit by at least 1.0 ATR, (2) every same-side position's stop to be secured (SL above open for longs, below open for shorts), and (3) the cap of InpPyramidMaxLevels (default 3) per side not to be breached. The cap is then also clamped to MAX_POSITIONS (5). This is a strict, conservative add — not a martingale, not averaging into losers.
Trade management runs every tick from ManageInTrade(). The TryClose_EX18016, TryClosePartial_EX18016, and TryModify_EX18016 wrappers each retry up to three times on requote, timeout, price-off, or price-changed errors, with 200ms and 100ms sleeps between attempts. A time-based exit closes positions that have been open longer than MAX_BARS_IN_TRADE (96 bars, ~24 hours on M15). An opposite-signal exit closes longs when the live signal flips negative (and vice versa) — this preserves the source's trend-flip-exit behaviour. A 50% partial close fires once the position is in profit by at least 1R, provided the remaining volume is at least 1.5× the symbol's minimum lot. After the position is 1R in profit, the stop is moved to break-even plus a 2-point buffer. From that point, an ATR trail at 2.5×ATR ratchets the stop forward in 0.5×ATR steps. When the regime is WeakTrend, the trail distance is halved (1.25×ATR) so weak-trend winners lock in faster.
The OnTester() criterion is (net * profit_factor) / (1 + balance_drawdown) with a 30-trade minimum. This rewards strategies that combine profitability with low drawdown relative to the absolute profit — a much harsher selector than raw net profit, and one that favours a smooth equity curve over a high-amplitude one.
In a backtest on USDJPY M15 over a multi-year window with default settings, expect a low-frequency, low-trade-count profile with most entries occurring during London and New York overlap hours and a sizeable number of entries being filtered out by the Choppy and Compress regime gates. Default InpDryRun is true, so the EA logs every intended trade to the journal without sending orders — set it to false before going live.
Strategy Deep Dive
On every tick, OnTick() first handles weekend protection (Friday 22:00 server closes everything) and day-rollover counters, then runs ManageInTrade() for existing positions. The once-per-bar gate limits new entries to a single evaluation per closed bar. The capital-cap check rejects trades when effective capital falls below the $50 floor, and the daily-loss check rejects trades when realized losses hit 3% of effective capital. The pipeline then runs RegimeClassify() (ADX + ATR-percentile + Bollinger width → 7 states) and SignalComposite() (inlined Hull slope + inlined SuperTrend direction + close-vs-Hull) — only StrongTrend, WeakTrend, Breakout, and Expand regimes are allowed through the gate mask 0x4B. ConfirmOK() then requires the H1 Hull slope to agree, the close to sit on the correct side of the H1 EMA(50), the implied R:R to clear 1.5, and the server hour to be inside the session window. NoTradeBlock() adds rolling-spread rejection, stops-level feasibility, terminal-trading permission, filling mode, max-positions cap (5), and per-side pyramid cap. TryEntry() sizes the lot from 0.5% risk, normalizes SL/TP, runs OrderCalcMargin, and — for pyramid adds only — calls PyramidAllowed() to enforce the triple-gate (all-same-side-in-profit, all-stops-secured, levels cap). The pyramid is hard-capped at 3 levels per side, default off, with 1.0×ATR spacing.
A long or short trigger fires on a closed M15 bar when three things agree: the inlined Hull MA (period 20) is sloping in the signal direction, the inlined SuperTrend (10-period ATR, 3.0× multiplier) is on the corresponding side (+1 / −1), and the closed-bar close is on the correct side of the fast Hull. The signal is additionally gated by a 7-state regime classifier that only allows StrongTrend, WeakTrend, Breakout, and Expand — Choppy, Compress, and Range are blocked. A higher-timeframe confirmation requires the H1 Hull MA (period 50) to slope the same way and the closed-bar close to sit on the correct side of the H1 EMA(50).
Positions are closed on the first new bar where the live signal flips to the opposite side, ending the trend-follow quickly when the composite changes colour. A 96-bar (~24-hour) time-based exit closes any position that has not produced a stop or target hit, preventing trades from sleeping through multiple sessions. A 50% partial close fires once at the 1R profit mark, provided the remaining volume clears the 1.5× minimum-lot threshold, locking in half the position before the trailing stop takes over.
Every position opens with a 3.0×ATR stop, normalized to the symbol's digits and floored above the broker's stops level. After price moves 1R in profit, the stop is ratcheted to break-even plus a 2-point buffer; from that point, a 2.5×ATR trailing stop (0.5×ATR steps) takes over and tightens further to 1.25×ATR when the regime is WeakTrend. The initial SL is a single 3×ATR value at entry; the trail and break-even logic then replace it incrementally.
The take-profit is derived from the stop via the 1:1.5 R:R target. With InpATRSLmult = 3.0 and InpMinRR = 1.5, a 3×ATR SL pairs with a 4.5×ATR TP. The TP is normalized and floored above the broker's stops level at entry. The trail and partial close do most of the practical exit work — TP acts as a ceiling, not a forced close on every winner.
This EA is built for a $100 minimum account running USDJPY on M15, with a MEDIUM risk profile and conservative capital-cap defaults. It suits a trader who wants trend-following on a single FX pair, with the HTF H1 confirmation baked in and a regime classifier that filters out the choppy hours automatically. Run it on an ECN or low-spread broker, leave the capital cap at 0.0 to use raw equity, and turn the pyramid on only after observing the strategy live in dry-run mode. The dry-run default (true) means you should not see live orders until you explicitly flip InpDryRun to false in inputs.
Strategy Logic
Pipsgrowth EX18016 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218016
Version: 2.00
BRIEF:
Hull MA + SuperTrend composite trend-follow with capped pyramid. HullFast (slope up/down) + HullSlow HTF (slope) agreement + SuperTrend direction + close-vs-HullFast trigger. Hull = LWMA(2*WMA(n/2) - WMA(n), sqrt(n)) [inlined from iMA]. Super = HL2 +/- ATR*mult, flip on close vs band [inlined iATR]. Pyramid hard-capped, ATR-spaced, profit-gated, side-capped, auto-disabled in choppy/news/high-spread. Default OFF. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
DayStamp()EffectiveCapital()TodayRealizedPnL()NormalizePrice()StopsLevelPrice()ClampVolume()CountOurs()CountOursByType()CloseAllOurs()IsWeekendClose()CopyBufSafe()RegimeClassify()- ...and 16 more
INTERNAL CONSTANTS (17 total):
ATR_REGIME_PERIOD= 50 //ATRpercentile lookback (regime)BB_REGIME_PERIOD= 20 // Bollinger width period (regime)BB_REGIME_DEV=2.0// Bollinger width deviation (regime)ADX_REGIME_PERIOD= 14 //ADXperiod (regime)HTF_HULL_PERIOD= 50 //HTFHull MA slow period (trend confirm)HTF_EMA_PERIOD= 50 //HTFEMAperiod (confirm)TRAIL_STEP_ATR_MULT=0.5//ATRtrailing step (mult)MAX_POSITIONS= 5 // Max concurrent trades (hard cap)PYRAMID_ATR_SPACING=1.0// MinATRspacing between pyramid addsSPREAD_ROLL_BARS= 50 // Rolling-average spread windowMAX_DAILY_TRADES= 10 // Max new entries per dayMAX_BARS_IN_TRADE= 96 // Max bars in trade (~24h onM15)SESSION_START_HOUR= 0 // Session start (server time)SESSION_END_HOUR= 23 // Session end (server time)WEEKEND_CLOSE_HOUR= 22 // Friday close hour (server time)- ...and 2 more
INPUT PARAMETERS (21 total across 6 groups):
- [=== Identity ===]
InpMagicNumber=22218016// MagicNumber(222xxx) - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_18016" // Trade comment - [=== Identity ===]
InpDryRun=true// Dry-run (no live sends) - [=== Identity ===]
InpKillSwitch=false// Kill switch (block everything) - [=== Risk & Sizing ===]
InpRiskPercent=0.5// Risk % per trade (ofeffective_capital) - [=== Risk & Sizing ===]
InpFixedLot=0.01// Fixed lot fallback (risk=0) - [=== Risk & Sizing ===]
InpDailyLossLimitPct=3.0// Daily loss limit % (ofeffective_capital) - [=== Risk & Sizing ===]
InpCapitalCapAmount=0.0// Capital cap amount ($REALMONEYequity) - [=== Risk & Sizing ===]
InpCapitalCapFloor=50.0// Capital floor ($ — block new entries below) - [===
Signal(Hull MA +SuperTrend) ===]InpHullPeriod= 20 // Hull MA fast period (n) - [===
Signal(Hull MA +SuperTrend) ===]InpSTPeriod= 10 //SuperTrendATRperiod - [===
Signal(Hull MA +SuperTrend) ===]InpSTMultiplier=3.0//SuperTrendATRmultiplier - [=== Regime & Confirmation ===]
InpADXMin=20.0// MinADXforStrongTrendgating - [=== Regime & Confirmation ===]
InpHTFTimeframe= 8 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) //HTFtrend agreement TF - [=== Regime & Confirmation ===]
InpMinRR=1.5// Minimum reward:risk ratio - [===
Pyramid(capped) ===]InpPyramidEnabled=false// Pyramid scaling (defaultOFF; capped) - [===
Pyramid(capped) ===]InpPyramidMaxLevels= 3 // Max pyramid levels per side (cap) - [=== Exit / In-Trade Management ===]
InpATRSLmult=3.0// Initial SL = mult *ATR - [=== Exit / In-Trade Management ===]
InpBETriggerR=1.0// Break-even trigger (R multiples) - [=== Exit / In-Trade Management ===]
InpTrailATRmult=2.5//ATRtrailing distance (mult) - [=== Exit / In-Trade Management ===]
InpPartialPct=50.0// Partial close % atTP1(1R)
// Pipsgrowth EX18016 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Hull MA + SuperTrend composite trend-follow with capped pyramid. HullFast (slope up/down) + HullSlow HTF (slope) agreement + SuperTrend direction + close-vs-HullFast trigger. Hull = LWMA(2*WMA(n/2) - WMA(n), sqrt(n)) [inlined from iMA]. Super = HL2 +/- ATR*mult, flip on close vs band [inlined iATR]. Pyramid hard-capped, ATR-spaced, profit-gated, side-capped, auto-disabled in choppy/news/high-spread. Default OFF. 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
EA Parameters
| Parameter | Default | Description |
|---|---|---|
| InpMagicNumber | 22218016 | Magic Number (222xxx) |
| InpTradeComment | "Psgrowth.com Expert_18016" | Trade comment |
| InpDryRun | true | Dry-run (no live sends) |
| InpKillSwitch | false | Kill switch (block everything) |
| InpRiskPercent | 0.5 | Risk % per trade (of effective_capital) |
| InpFixedLot | 0.01 | Fixed lot fallback (risk=0) |
| InpDailyLossLimitPct | 3.0 | Daily loss limit % (of effective_capital) |
| InpCapitalCapAmount | 0.0 | Capital cap amount ($ REAL MONEY equity) |
| InpCapitalCapFloor | 50.0 | Capital floor ($ — block new entries below) |
| InpHullPeriod | 20 | Hull MA fast period (n) |
| InpSTPeriod | 10 | SuperTrend ATR period |
| InpSTMultiplier | 3.0 | SuperTrend ATR multiplier |
| InpADXMin | 20.0 | Min ADX for StrongTrend gating |
| InpHTFTimeframe | 8 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF trend agreement TF |
| InpMinRR | 1.5 | Minimum reward:risk ratio |
| InpPyramidEnabled | false | Pyramid scaling (default OFF; capped) |
| InpPyramidMaxLevels | 3 | Max pyramid levels per side (cap) |
| InpATRSLmult | 3.0 | Initial SL = mult * ATR |
| InpBETriggerR | 1.0 | Break-even trigger (R multiples) |
| InpTrailATRmult | 2.5 | ATR trailing distance (mult) |
| InpPartialPct | 50.0 | Partial close % at TP1 (1R) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18016 USDJPY_Hull_Supertrend_Pyramid — Hull MA + SuperTrend composite + capped 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>
CTrade trade;
CPositionInfo position;
CSymbolInfo sym;
CAccountInfo acc;
//============================== INPUTS ==============================
ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
switch(tf)
{
case 1: return PERIOD_M1;
case 2: return PERIOD_M5;
case 3: return PERIOD_M15;
case 4: return PERIOD_M30;
case 5: return PERIOD_H1;
case 6: return PERIOD_H4;
case 7: return PERIOD_D1;
default: return PERIOD_H1;
}
}
ENUM_APPLIED_PRICE MapAppliedPriceInt(int ap)
{
switch(ap)
{
case 1: return PRICE_CLOSE;
case 2: return PRICE_OPEN;
case 3: return PRICE_HIGH;
case 4: return PRICE_LOW;
case 5: return PRICE_MEDIAN;
case 6: return PRICE_TYPICAL;
case 7: return PRICE_WEIGHTED;
default: return PRICE_CLOSE;
}
}
ENUM_TIMEFRAMES g_InpHTFTimeframe = PERIOD_H1;
input group "=== Identity ==="
input long InpMagicNumber = 22218016; // Magic Number (222xxx)
input string InpTradeComment = "Psgrowth.com Expert_18016";// Trade comment
input bool InpDryRun = true; // Dry-run (no live sends)
input bool InpKillSwitch = false; // Kill switch (block everything)
ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
switch(tf)
{
case 1: return PERIOD_M1;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.