Pipsgrowth EX18053 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX18053 Hull2EA — Quad inline Hull-MA trend-follow with regime gate, full 12-layer stack.
Overview
EX18053 — codename Hull2EA — is a 4-line inline Hull moving-average voter that only opens a position when at least three of the four slopes agree on direction, and the remaining lines have not registered a vote in the opposite direction. The four Hull periods are 20, 34, 55, and 200 bars, all calculated directly on close[] inside the EA using a Linear Weighted Moving Average primitive rather than the iCustom/iMA pipeline. The LWMA primitive is straight sum-of-weighted-prices / sum-of-weights with descending weights (most recent bar gets the heaviest weight), and the Hull itself combines a fast LWMA at period/2 with a slow LWMA at the full period, then smooths the difference with a sqrt(period) weighted average. The result is a low-lag, low-noise trend line that flips between an up-slope and a down-slope without the cross-over delay a plain EMA would impose. The HullColor helper returns 0 when the current Hull value is greater than the previous one, 1 when smaller, and 2 when they tie — and the EA only counts votes 0 or 1, so a flat line contributes nothing and can never break a tie.
The consensus rule is therefore stricter than a simple majority: with the default InpMinAgree=3, longs require at least three of the four Hulls to be sloping up AND none sloping down (shortVotes must be 0). The same is true in reverse for shorts. That asymmetric rule means a single contradictory line in the opposite direction blocks the signal entirely, even if the other three agree — a design choice that filters out the 3-up-1-down whip-saw patterns that simpler vote schemes allow. A confidence figure is also produced, anchored at 50 and then nudged up by the magnitude of the fast Hull slope relative to ATR (50 + slope/ATR * 200, capped at 100), giving a rough sense of how decisively the fastest line is moving.
Two confirmation gates sit in front of entry. ConfirmADXStrong() requires the most recent closed-bar ADX(14) value to be at least 18 — the same threshold that defines WEAK_TREND in the regime classifier — so the EA will not open on a flat, range-bound tape even if all four Hulls happen to be sloped. ConfirmMinRR() blocks entries if TP/SL would be below 1.0, which the 3.2/1.8 default ATR multipliers comfortably clear. Optionally, HTFHullBias() runs the same Hull(35) calculation on the higher-timeframe close[] (default H1) and demands that it slope in the same direction as the entry — a 5-minute long signal against a 1-hour Hull rolling over is rejected before any sizing is computed.
The regime classifier runs every tick and feeds the no-trade gate. It is a seven-state machine driven by ADX(14), a 50-bar ATR percentile, and a 50-bar Bollinger-band width percentile. STRONG_TREND fires when ADX is at or above 25 and the current ATR sits in the top quartile of its 50-bar distribution. WEAK_TREND requires only ADX >= 18. COMPRESS is the band-width-percentile floor (<=20), EXPAND the ceiling (>=80). BREAKOUT requires high ATR (top quartile) without the ADX strength to qualify for STRONG_TREND — a volatility impulse the trend indicators have not caught up to. RANGE is a 40-70 band-width window with weak ADX. Everything else becomes CHOPPY, which is the only regime that outright blocks new entries. COMPRESS, EXPAND, BREAKOUT and RANGE all allow entries; STRONG and WEAK are the productive states.
The no-trade stack that follows the regime gate is a sequence of early returns, each logged with a reason. SpreadOK() rejects entries when the current spread exceeds 0.45 * ATR(14) — an ATR-relative spread cap that automatically relaxes in volatile conditions and tightens in quiet ones. SessionOK() simply blocks Saturday and Sunday entirely and refuses new entries after 21:00 on Friday, so a position is never opened into a weekend gap with no operator watching. DailyLossOK() sums the EA's own realized PnL for the day (filtering HistoryDeals by magic and symbol) and blocks if the cumulative loss has reached InpDailyLossPercent (default 3.0%) of effective capital. IsCapitalBelowFloor() blocks when effective capital has fallen below InpCapitalCapFloor (default $50), which is a useful guard against a blown account still firing orders. Max concurrent positions is capped at InpMaxConcurrent (default 3). Margin is verified up-front via OrderCalcMargin before any position is opened, so a rejected margin check never reaches the trade layer. Finally, a duplicate-entry guard tracks the last entry bar and direction and refuses to re-open the same direction on the same signal bar.
Sizing is fixed-fractional on the effective capital figure produced by ComputeEffectiveCapital(), which takes the minimum of account equity and InpCapitalCapAmount when the cap is non-zero, and uses pure equity otherwise (cap=0 disables it). The default 0.5% risk is converted to a stop-distance-aware lot count by dividing the dollar risk by the per-lot stop-distance loss calculated from the symbol's tick value and tick size. If InpRiskPercent is set to 0 the EA falls back to InpFixedLots (0.10), and NormalizeLots rounds the result to the broker's volume step and clamps to the min/max lot range. The whole sizing chain is therefore broker-portable: the same 0.5% risk produces different lot counts on a 5-digit gold broker and a 4-digit FX broker, but the dollar risk is identical.
Once a position is open, the ManageOpenPositions() function runs on every tick. Three management actions can trigger. The break-even one-shot fires when price has moved in the trade's favour by ATR * 1.0 (= 1R) and ratchets the stop to open + 1 point; the gate is sl < newSL so the BE only moves forward, never backward. The partial-TP at TP1 fires once per position at the same 1R profit trigger and closes half the position (PARTIAL_TP_FRACTION = 0.5), with a vol > g_volMin guard so a sub-min partial does not get rejected by the broker. The trailing stop activates when price has moved 2 * trailDist = 3R in profit, and ratchets the stop to bid/ask - ATR*1.5 from there on. A 240-bar time stop (MAX_BARS_IN_TRADE, 20 hours on M5) forcibly closes any position that has not produced either a TP hit or a stop hit by then.
Exit conditions come in two flavours beyond the SL/TP and the trailing/partial machinery. CheckRegimeExit() fires on every new bar; if the regime has flipped to CHOPPY, all EA positions are closed. If InpCloseOnReverse is true (the default) and the consensus signal has flipped to the opposite direction of the held position, that direction's positions are also closed. A separate time-exit path inside ManageOpenPositions() closes positions that exceed MAX_BARS_IN_TRADE bars in age. There is no news-window filter, no Friday-cutoff close (only a Friday-cutoff new-entry block), and no end-of-day force-close.
Pyramiding is implemented but disabled by default (InpEnablePyramid = false). When enabled, CanPyramid() allows up to PYRAMID_MAX_LEGS = 3 positions in the same direction, provided each leg is opened at least 0.5 * ATR beyond the previous leg's open price and the previous leg is currently in profit with a stop already moved to breakeven or better. Combined with the 1R BE rule, the practical effect is that pyramiding stacks winners that have survived the initial 1R pullback, rather than adding into losers.
The capital allocation cap is a two-input subsystem. When InpCapitalCapAmount is greater than zero, effective capital is the lesser of the configured cap and current equity, and IsCapitalBelowFloor() refuses new entries below InpCapitalCapFloor (default $50). This is the closest thing the EA has to a hard account-level stop and is most useful for traders who run multiple instances on the same account and want each instance to pretend it has its own dedicated sub-account. With the cap at the default 0.0, the EA uses the full account equity for sizing and the floor check never triggers.
Two operator toggles sit at the bottom of the input panel. InpDryRun defaults to true — every intended order is logged to the journal (DRYRUN BUY/SELL lots=... price=... sl=... tp=...) but no order is actually sent to the trade server. This is a deliberate safety default: the EA ships in a paper-trade state and the operator has to deliberately flip DryRun to false to go live. InpKillSwitch, when true, short-circuits the OnTick flow before any signal processing and just refreshes the dashboard — a panic-button that can be toggled without recompiling.
In a backtest, the strategy behaves like a typical 4-line Hull-MA crossover voter with conservative risk management. The custom OnTester criterion multiplies net profit by profit factor and divides by (1 + balance drawdown), and disqualifies any test with fewer than 30 trades — so a curve-fit over a handful of trades cannot win the optimization pass. Live, the entry frequency is bounded by the regime gate and the 3-of-4 vote rule; a choppy market produces very few signals, and a strong trend can produce one or two per day on M5 XAUUSD. The combination of the 1.78:1 R:R (3.2/1.8) and the regime filter is what makes the system selective: it prefers not to trade rather than to trade badly.
Strategy Deep Dive
On every tick the EA rebuilds its 7-state regime from ADX(14), a 50-bar ATR percentile, and a 50-bar Bollinger-band-width percentile, and on every new bar it asks HullConsensus() whether at least three of four inline Hull-MAs (20/34/55/200 on close) are sloping in the same direction with the opposite direction receiving zero votes. A confirmed signal then has to clear the ADX>=18, 1.78:1 R:R, and optional H1 Hull(35) agreement gates, the ATR-relative spread cap (0.45ATR), the weekday+Friday<21 session window, the 3% daily-loss and $50 capital-floor limits, the regime-not-CHOPPY gate, and the InpMaxConcurrent=3 cap before it is sized at 0.5% of effective capital and dispatched through a retried, margin-pre-checked trade request. Live positions are managed on every tick: 1R triggers a 50% partial TP and a one-shot breakeven at open+1pt, 3R activates a 1.5ATR trailing stop, and a 240-bar (20h on M5) time stop forces any surviving trade closed.
A long or short entry requires a 3-of-4 consensus among four inline Hull moving averages (periods 20, 34, 55, 200 on close) on the most recent closed bar, with zero votes in the opposite direction, plus ADX(14) at or above 18, the 1.78:1 R:R (3.2 ATR TP vs 1.8 ATR SL) intact, an optional higher-timeframe Hull(35) bias agreement on H1, ATR-relative spread within 0.45*ATR, a clean trading session (Mon-Thu all hours, Friday before 21:00, no weekend), capital above the $50 floor, daily loss under 3% of effective capital, the regime not in CHOPPY, and fewer than 3 concurrent EA positions on the symbol.
Three exit paths beyond the SL/TP: a regime-change exit closes all EA positions when the classifier flips to CHOPPY on a new bar; an opposite-signal exit (with InpCloseOnReverse=true) closes the affected direction when the quad-Hull consensus flips to the other side; and a 240-bar time stop forcibly closes any position still open after 20 hours on M5. In-trade management also closes half the position at 1R profit (partial TP), ratchets the stop to breakeven at 1R, and trails by 1.5*ATR once the trade is 3R in profit.
Initial stop-loss is 1.8 * ATR(14) price-units from the entry, normalised to the symbol's digits and pushed beyond the broker's stops-level minimum. The break-even one-shot then moves the stop to open + 1 point after the trade has moved 1R in profit, and a 1.5 * ATR trailing stop activates and ratchets forward only once the trade is 3R in profit. There is no account-level fixed drawdown cap, but the InpDailyLossLimitPercent (3% of effective capital) acts as a per-day circuit breaker that blocks new entries once tripped.
Take-profit is 3.2 * ATR(14) price-units from the entry, giving a fixed 1.78:1 reward-to-risk ratio relative to the 1.8 ATR stop. A 50% partial close is taken at the 1R mark (PARTIAL_TP_R_MULT = 1.0, PARTIAL_TP_FRACTION = 0.5) on the same in-trade management pass that triggers the breakeven one-shot. The remaining half is left to reach the full 3.2 ATR TP or to be stopped out by the trailing stop.
Suited to traders running a $100+ account on XAUUSD M5 with a swing-trader's patience and an appetite for selective, multi-confirmation trend entries rather than frequent scalps. The four-line Hull vote + regime gate combination performs best when the underlying has a clear directional bias (gold during London/NY overlap, EURUSD during London, US30 during NY open), and the conservative 1.78:1 R:R with 1R break-even and 50% partial TP rewards brokers that quote tight spreads on the active session. ECN or RAW-spread brokers are recommended so the 0.45*ATR spread filter does not block valid entries during volatile opens.
Strategy Logic
Pipsgrowth EX18053 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218053
Version: 2.00
BRIEF:
Inline quad-Hull-MA (LWMA-primitive) slope-color vote + HTF Hull-MA bias + ADX/ATR-pct/BB-width regime gate + capital-allocation-cap, full risk/sizing/in-trade mgmt. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
LWMA()HullMA()HullColor()LoadSymbolInfo()NormalizeLots()NormalizePrice()EnforceStopsDistance()ComputeEffectiveCapital()IsCapitalBelowFloor()EARealizedPnLToday()UpdateRegime()HullConsensus()- ...and 20 more
INTERNAL CONSTANTS (25 total):
HULL_DIVISOR=2.0// Hull MA divisor (WMAfast = n/2)ATR_PCTILE_LOOKBACK= 50 // Bars forATRpercentileATR_PCTILE_FLOOR= 25 // Floor percentileATR_PCTILE_CEIL= 75 // Ceiling percentileBB_PERIOD= 20 // Bollinger periodBB_DEV=2.0// Bollinger deviationADX_PERIOD= 14 //ADXperiodADX_STRONG= 25 //ADXstrong-trend thresholdADX_WEAK= 18 //ADXweak-trend thresholdHTF_HULL_PERIOD= 35 //HTFHull-MA periodBB_WIDTH_PCTILE_LOOK= 50 //BB-width percentile lookbackBB_WIDTH_COMP_PCT= 20 // Compress percentile (BBwidth)BB_WIDTH_EXP_PCT= 80 // Expand percentile (BBwidth)EXEC_RETRIES= 1 // Retries on requote/timeoutSLIPPAGE_POINTS= 20 // Default slippage- ...and 10 more
INPUT PARAMETERS (21 total across 7 groups):
- [=== Identity ===]
InpMagic=22218053// Magic number - [=== Identity ===]
InpHTF= 8 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Higher-timeframe bias TF - [=== Identity ===]
InpSignalShift= 1 // Signal bar shift (1=closed bar) - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_18053" // Trade comment - [=== Risk & Sizing ===]
InpRiskPercent=0.5// Risk per trade (% of effective cap) - [=== Risk & Sizing ===]
InpFixedLots=0.10// Fixed lots (when risk=0) - [=== Risk & Sizing ===]
InpATR_SL_Mult=1.8// SL =ATR* mult - [=== Risk & Sizing ===]
InpATR_TP_Mult=3.2// TP =ATR* mult - [=== Risk & Sizing ===]
InpATR_Trail_Mult=1.5//ATRtrailing distance - [=== Risk & Sizing ===]
InpDailyLossLimitPercent=3.0// Daily loss limit (% of effective cap) - [=== Capital Allocation Cap ===]
InpCapitalCapAmount=0.0// Real-money cap (USDequity, not notional) - [=== Capital Allocation Cap ===]
InpCapitalCapFloor=50.0// Floor below which new entries are blocked - [===
Signal(Quad Hull-MA) ===]InpHullFast= 20 // Hull #1 fast period (entry TF) - [===
Signal(Quad Hull-MA) ===]InpHullSlow= 200 // Hull #4 slow period (entry TF) - [===
Signal(Quad Hull-MA) ===]InpMinAgree= 3 // Minimum Hulls agreeing (of 4) - [=== Regime / Confirm ===]
InpUseHTFBias=true// RequireHTFHull-MA agreement - [=== Regime / Confirm ===]
InpMaxConcurrent= 3 // Max concurrent positions (thisEA/symbol) - [=== Exit / Manage ===]
InpEnablePyramid=false// Enable pyramiding (profit only) - [=== Exit / Manage ===]
InpCloseOnReverse=true// Close opposite on reversal signal - [=== Operator ===]
InpDryRun=true// Dry-run: log but do not send orders - [=== Operator ===]
InpKillSwitch=false// Kill switch (block all trading)
// Pipsgrowth EX18053 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Inline quad-Hull-MA (LWMA-primitive) slope-color vote + HTF Hull-MA bias + ADX/ATR-pct/BB-width regime gate + capital-allocation-cap, full risk/sizing/in-trade mgmt. 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 |
|---|---|---|
| InpMagic | 22218053 | Magic number |
| InpHTF | 8 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Higher-timeframe bias TF |
| InpSignalShift | 1 | Signal bar shift (1=closed bar) |
| InpTradeComment | "Psgrowth.com Expert_18053" | Trade comment |
| InpRiskPercent | 0.5 | Risk per trade (% of effective cap) |
| InpFixedLots | 0.10 | Fixed lots (when risk=0) |
| InpATR_SL_Mult | 1.8 | SL = ATR * mult |
| InpATR_TP_Mult | 3.2 | TP = ATR * mult |
| InpATR_Trail_Mult | 1.5 | ATR trailing distance |
| InpDailyLossLimitPercent | 3.0 | Daily loss limit (% of effective cap) |
| InpCapitalCapAmount | 0.0 | Real-money cap (USD equity, not notional) |
| InpCapitalCapFloor | 50.0 | Floor below which new entries are blocked |
| InpHullFast | 20 | Hull #1 fast period (entry TF) |
| InpHullSlow | 200 | Hull #4 slow period (entry TF) |
| InpMinAgree | 3 | Minimum Hulls agreeing (of 4) |
| InpUseHTFBias | true | Require HTF Hull-MA agreement |
| InpMaxConcurrent | 3 | Max concurrent positions (this EA/symbol) |
| InpEnablePyramid | false | Enable pyramiding (profit only) |
| InpCloseOnReverse | true | Close opposite on reversal signal |
| InpDryRun | true | Dry-run: log but do not send orders |
| InpKillSwitch | false | Kill switch (block all trading) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18053 Hull2EA — Quad inline Hull-MA trend-follow with regime gate, 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>
//+------------------------------------------------------------------+
//| Non-input tunables (constants) |
//+------------------------------------------------------------------+
#define HULL_DIVISOR 2.0 // Hull MA divisor (WMA fast = n/2)
#define ATR_PCTILE_LOOKBACK 50 // Bars for ATR percentile
#define ATR_PCTILE_FLOOR 25 // Floor percentile
#define ATR_PCTILE_CEIL 75 // Ceiling percentile
#define BB_PERIOD 20 // Bollinger period
#define BB_DEV 2.0 // Bollinger deviation
#define ADX_PERIOD 14 // ADX period
#define ADX_STRONG 25 // ADX strong-trend threshold
#define ADX_WEAK 18 // ADX weak-trend threshold
#define HTF_HULL_PERIOD 35 // HTF Hull-MA period
#define BB_WIDTH_PCTILE_LOOK 50 // BB-width percentile lookback
#define BB_WIDTH_COMP_PCT 20 // Compress percentile (BB width)
#define BB_WIDTH_EXP_PCT 80 // Expand percentile (BB width)
#define EXEC_RETRIES 1 // Retries on requote/timeout
#define SLIPPAGE_POINTS 20 // Default slippage
#define PYRAMID_MIN_ATR 0.5 // Min ATR spacing between pyramid legs
#define PARTIAL_TP_FRACTION 0.5 // Fraction to close at TP1
#define PARTIAL_TP_R_MULT 1.0 // TP1 trigger in R multiples
#define MAX_BARS_IN_TRADE 240 // Time-based exit, max bars
#define ATR_BE_MULT 1.0 // Break-even trigger (ATR mult)
#define MAX_SPREAD_ATR 0.45 // Max spread (ATR mult)
#define HULL_MID1_PERIOD 34 // Hull #2 mid1 period (entry TF)
#define HULL_MID2_PERIOD 55 // Hull #3 mid2 period (entry TF)
#define PYRAMID_MAX_LEGS 3 // Max pyramid legs (if pyramiding enabled)
#define TRADE_COMMENT InpTradeComment // Trade comment
//+------------------------------------------------------------------+
//| Inputs (count: 20) |
//+------------------------------------------------------------------+
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;
}
}
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.