Pipsgrowth EX18051 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX18051 Hull_GB — Inline dual Hull MA consensus with SuperTrend/HA confirm, full 12-layer stack.
Overview
EX18051 is built around an uncommon twist on the standard Hull Moving Average: instead of computing a single Hull line from close prices, it runs three parallel Hull instances — one fed by the high of each bar (HullH), one by the low (HullL), and one by the close (HullC). Each instance calculates its own WMA of the full period, the WMA of half the period, twice the half minus the full, then a final WMA smooth of the result with period equal to the square root of the base period (the textbook Hull construction). Each Hull is asked to color itself green, pink, or flat by comparing the current bar output to the prior bar output against the threshold InpHullThresh (0.0001 price units, deliberately tiny so noise gets counted as flat). The signal function HullSignal() counts how many of the three lines are green on the most recent closed bar and how many are pink. If at least InpReqAgree (default 2) of them are green AND the close Hull has remained green across the last 3 closed bars, the EA reads a long bias. The same test in pink yields short bias. The 3-bar stability requirement is the EA's main defense against whipsaw: a single bar of disagreement breaks the streak and the signal is dropped, which means a flip from green to pink needs the close Hull to hold pink for three consecutive bars before any short trade is taken.
The signal alone is never enough. Every candidate trade has to clear ConfirmDir(), a 2-of-3 panel of confirmations. The first vote comes from an inline Heikin-Ashi transform: the EA builds HA open and close arrays from the OHLC bars (passing close for the open array as a smoothing approximation), then asks whether the most recent closed HA bar is green for longs or pink for shorts. The second vote is the inline SuperTrend: an ATR(22) channel with multiplier 3.0 wraps price, and the trend flag flips when close breaks the opposite band. The third vote is the higher-timeframe EMA(50) on the user-selected HTF (default H4 per InpHTF=6). For a long, the current HTF close must sit above the EMA(50); for a short, below. Two of these three must agree, so a pure Hull signal with no corroboration from any of HA, SuperTrend, or HTF EMA is rejected before it ever reaches the risk layer.
Regime detection runs every tick from a 5-state classifier: STRONG_TREND when ADX is at or above 25 and ATR-percentile is at least 60; WEAK_TREND when ADX is at least 20 and ATR-percentile at least 40; BREAKOUT when Bollinger bandwidth is wider than 10% of the midline and ATR-percentile is at least 70; RANGE when BB width collapses below 4%; and CHOPPY as the catch-all when nothing else fits. CHOPPY blocks new entries outright and forces the ManageExits() pass to close any open position attributed to this magic; RANGE blocks entries too. So the EA will only put on trades when the market is actually moving in a usable way.
Risk is sized off an effective capital figure that is either the live account equity or, when InpCapAmt is set above zero, the smaller of the cap amount and the equity. A floor of InpCapFloor (default $50) blocks trading entirely when the cap or equity would fall below it. Each trade risks InpRiskPct (0.5%) of that effective capital, with the stop loss distance calculated as 1.6× ATR(14) on the closed bar. Lot size comes from CalcLots(), which divides risk money by the per-lot loss at the chosen SL distance using the symbol's tick value and tick size, then normalizes to the broker's volume step, minimum, and maximum. A margin pre-check calls OrderCalcMargin() and refuses to send if free margin cannot cover the order. There is no scaling, no martingale, and no grid; the EA's only safety net beyond the regime gate is a per-trade ATR-based stop plus a global daily realized-loss limit of InpDailyLoss (3% of effective capital), a 30-minute cooldown that triggers when ConsecutiveLosses() walks the last seven days of DEAL_ENTRY_OUT history and counts three losses in a row, and a hard cap of InpMaxOpen (3) concurrent positions on the symbol under this magic number.
In-trade management runs every tick. The first line of defense is a break-even move that fires once the position is at 0.5R in profit (half of the 1:2 target). AdjustToStops() makes sure the new stop respects the broker's stops-level, and a one-shot guard means the BE only happens once. At InpTP_R × R (1.6×ATR × 2 = 3.2×ATR from entry), the position is partially closed: 50% of the volume is closed via TryClosePartial_EX18051, with a [P] tag in the comment preventing re-trigger. A forward-only ATR trail at 2.0× ATR(14) starts ratcheting the stop loss after that. Regime change to CHOPPY triggers an immediate full close with reason "REGIME_CHOPPY". The opposite-signal logic recomputes HullC color on each tick and closes any open position whose direction is now opposed by the new Hull color, tagged "OPPOSITE_SIGNAL". Both the close helpers and the modify helper retry up to three times with 100–200ms sleeps on requote, timeout, price-changed, or price-off retcodes. Filling mode is auto-detected by symbol via SetTypeFillingBySymbol().
Execution defaults to InpDryRun=true, which logs intended orders to the journal without sending them, and InpKillSwitch=false. The trade comment is hardcoded as "Psgrowth.com Expert_18051". The expected runtime footprint is roughly four indicator handles (ATR, ADX, Bollinger Bands, and the HTF EMA) plus three inline Hull objects and one inline SuperTrend, which keeps the per-tick cost low enough for M5 use. A backtest on XAUUSD M5 will be dominated by trend-quality segments; flat or choppy weeks can produce long losing streaks that hit the daily loss limit or trip the cooldown, so reviewers should focus on quality-of-trend periods and on the win rate of the partial-close step rather than the raw trade count. Strategy optimization should start from the 2-of-3 confirm and the regime thresholds (ADX 20/25, BB width 0.04/0.10, ATR-percentile 40/60/70) before touching risk or Hull period.
Strategy Deep Dive
Each tick, the EA refreshes equity, today's realized PnL, and a 7-day consecutive-loss count, then runs ComputeRegime() against ADX(14), ATR(14) percentile, and Bollinger bandwidth to assign one of five regime states. On a new bar of the working timeframe, three inline Hull MA instances (one per High, Low, Close, all at InpHullPeriod=21) compute their WMA-based Hull outputs; HullSignal() tallies how many of the three are green or pink against InpHullThresh=0.0001 and demands the close Hull hold its color for 3 consecutive bars before it returns +1 or -1. ConfirmDir() then takes a 2-of-3 vote: inline Heikin-Ashi color, inline SuperTrend(22, 3.0) direction, and HTF EMA(50) close-vs-line agreement, killing any signal that lacks two of those. NoTradeReason() rejects the rest on the grounds of kill switch, spread above 30 points, out-of-session (08:00–20:00 server), capital-floor breach, 3% daily loss, CHOPPY/RANGE regime, active 30-min cooldown, or already holding 3 positions under magic 22218051. Surviving signals get sized to 0.5% of effective capital (capped by InpCapAmt with a $50 floor) at a 1.6× ATR(14) stop and a 2.0R target, with the opposing-direction positions flattened first. In-trade management runs every tick: 0.5R break-even, 50% partial close at 2R, a 2.0× ATR(14) forward-only trail, CHOPPY-regime close, and an opposite-Hull-color close, all routed through retry helpers that handle requote/timeout/price-changed failures in three 100–200ms attempts.
EX18051 enters long when at least 2 of 3 inline Hull MA instances (on High, Low, and Close) print green on the closed bar with a slope above InpHullThresh=0.0001, AND the close-based Hull has remained green for the last 3 closed bars for stability, AND 2 of 3 confirmations agree: inline Heikin-Ashi green, inline SuperTrend(ATR 22, mult 3.0) bullish, or HTF EMA(50) close above the line. Short is the mirror: 2+ pink Hulls, 3-bar pink stability, plus 2-of-3 confirming pink/bearish readings. New entries are blocked when regime is CHOPPY or RANGE, when daily realized loss has hit 3% of effective capital, when 3 consecutive losses have armed a 30-minute cooldown, when capital has fallen below the $50 floor, or when the symbol already carries 3 positions under this magic number.
EX18051 exits a position for one of four reasons: an opposite Hull color flip on the closed bar (HullC turning pink for longs, green for shorts) flagged OPPOSITE_SIGNAL; a regime change to CHOPPY during the tick-driven ManageExits() pass, which forces an immediate full close tagged REGIME_CHOPPY; the InpKillSwitch kill switch, which closes every open position attributed to this magic; or a successful close of the remaining 50% at the partial-TP point. The first 50% is already taken at 2R by the partial close, after which the ATR trail handles the rest.
Per-trade stop is hard-pinned to 1.6× ATR(14) on the closed bar at signal time, adjusted to respect the broker's stops-level via AdjustToStops(). The break-even floor engages at 0.5R in profit (half the 2R target) and slides the stop to entry ± 1 point, again respecting stops-level. A forward-only ATR trail at 2.0× ATR(14) then takes over, ratcheting the stop behind price on every tick that improves the level.
Take profit is fixed at 2.0R (where R equals the 1.6× ATR(14) stop distance, giving 3.2× ATR from entry). At that price the EA executes a 50% partial close via TryClosePartial_EX18051 — tagged [P] in the comment to prevent re-trigger — and lets the ATR trail manage the remaining 50% for the runner.
EX18051 is configured for XAUUSD on M5 by default and is well matched to a $100 minimum account thanks to the 0.5% per-trade risk and 0.01-lot-capable symbols. The 8:00–20:00 server-time window and the 30-point spread filter assume a low-spread ECN/RAW broker with a gold pair that prices actively through the London and New York sessions. Run it only when ADX and ATR-percentile can both build a regime classification, and disable InpDryRun only after forward-testing the partial-close and trail behavior on a demo account under the live capital-cap setting you intend to use.
Strategy Logic
Pipsgrowth EX18051 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218051
Version: 2.00
BRIEF:
Inline dual Hull MA (H/L/C) slope-color consensus drives the core signal. Entries fire on closed bar when >=N of three Hull lines agree on color, HTF EMA(50) confirms direction, and inline SuperTrend/Heikin-Ashi confirm. REGIME (ADX + ATR-pct + BB-width) gates entries/sizing/trail. Risk sized off effective_ capital with ATR SL. Full in-trade management (BE/partial TP/ ATR trail/opposite-signal/time/regime-change exits). Capital allocation cap enforces per-magic dollar isolation. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
NormPrice()NormVol()StopsLevelPrice()AdjustToStops()BufVal()GetRates()ComputeEffectiveCapital()ConsecutiveLosses()RealizedPnLToday()CalcLots()CountOpen()ComputeRegime()- ...and 10 more
INTERNAL CONSTANTS (1 total):
MAGIC_NUM= 22218051L // --- handles
INPUT PARAMETERS (27 total across 6 groups):
- [=== General ===]
InpTF= 0 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Working timeframe - [=== General ===]
InpHTF= 6 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) //HTFtrend timeframe - [=== General ===]
InpDryRun=true// Dry-run (no live sends) - [=== General ===]
InpKillSwitch=false// Emergency kill switch - [=== General ===]
InpTradeComment= "Psgrowth.com Expert_18051" // Trade comment - [=== Signal — Hull + Confirm ===]
InpHullPeriod= 21 // Hull MA period - [=== Signal — Hull + Confirm ===]
InpHullThresh=0.0001// Hull color threshold (price units) - [=== Signal — Hull + Confirm ===]
InpReqAgree= 2 // Hull lines agreeing (1..3) - [=== Signal — Hull + Confirm ===]
InpHTF_EMA= 50 //HTFEMAperiod - [=== Signal — Hull + Confirm ===]
InpSupATR= 22 //SuperTrendATRperiod - [=== Signal — Hull + Confirm ===]
InpSupMult=3.0//SuperTrendmultiplier - [=== Signal — Hull + Confirm ===]
InpDir=DIR_BOTH// Trade direction - [=== Regime ===]
InpADX= 14 //ADXperiod - [=== Regime ===]
InpATR= 14 //ATRperiod - [=== Regime ===]
InpBBDev=2.0// Bollinger deviation - [=== Risk &
Sizing(offeffective_capital) ===]InpRiskPct=0.5// Risk per trade (% eff cap) - [=== Risk &
Sizing(offeffective_capital) ===]InpATR_SL=1.6//ATRSL multiplier - [=== Risk &
Sizing(offeffective_capital) ===]InpTP_R=2.0// TP in R multiples - [=== Risk &
Sizing(offeffective_capital) ===]InpTrailATR=2.0//ATRtrailing multiplier - [=== Risk &
Sizing(offeffective_capital) ===]InpDailyLoss=3.0// Max daily loss (% eff cap) - [=== Capital Allocation Cap ===]
InpCapAmt=0.0// Capital cap amount (0=disabled, $) - [=== Capital Allocation Cap ===]
InpCapFloor=50.0// Capital cap floor ($) - [=== No-Trade / Exec ===]
InpMaxSpread= 30 // Max spread (points) - [=== No-Trade / Exec ===]
InpStartHour= 8 // Session start hour (server) - [=== No-Trade / Exec ===]
InpEndHour= 20 // Session end hour (server) - [=== No-Trade / Exec ===]
InpMaxOpen= 3 // Max concurrent trades - [=== No-Trade / Exec ===]
InpSlippage= 20 //Slippage(points)
// Pipsgrowth EX18051 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Inline dual Hull MA (H/L/C) slope-color consensus drives the core signal. Entries fire on closed bar when >=N of three Hull lines agree on color, HTF EMA(50) confirms direction, and inline SuperTrend/Heikin-Ashi confirm. REGIME (ADX + ATR-pct + BB-width) gates entries/sizing/trail. Risk sized off effective_ capital with ATR SL. Full in-trade management (BE/partial TP/ ATR trail/opposite-signal/time/regime-change exits). Capital allocation cap enforces per-magic dollar isolation. 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 |
|---|---|---|
| InpTF | 0 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Working timeframe |
| InpHTF | 6 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF trend timeframe |
| InpDryRun | true | Dry-run (no live sends) |
| InpKillSwitch | false | Emergency kill switch |
| InpTradeComment | "Psgrowth.com Expert_18051" | Trade comment |
| InpHullPeriod | 21 | Hull MA period |
| InpHullThresh | 0.0001 | Hull color threshold (price units) |
| InpReqAgree | 2 | Hull lines agreeing (1..3) |
| InpHTF_EMA | 50 | HTF EMA period |
| InpSupATR | 22 | SuperTrend ATR period |
| InpSupMult | 3.0 | SuperTrend multiplier |
| InpDir | DIR_BOTH | Trade direction |
| InpADX | 14 | ADX period |
| InpATR | 14 | ATR period |
| InpBBDev | 2.0 | Bollinger deviation |
| InpRiskPct | 0.5 | Risk per trade (% eff cap) |
| InpATR_SL | 1.6 | ATR SL multiplier |
| InpTP_R | 2.0 | TP in R multiples |
| InpTrailATR | 2.0 | ATR trailing multiplier |
| InpDailyLoss | 3.0 | Max daily loss (% eff cap) |
| InpCapAmt | 0.0 | Capital cap amount (0=disabled, $) |
| InpCapFloor | 50.0 | Capital cap floor ($) |
| InpMaxSpread | 30 | Max spread (points) |
| InpStartHour | 8 | Session start hour (server) |
| InpEndHour | 20 | Session end hour (server) |
| InpMaxOpen | 3 | Max concurrent trades |
| InpSlippage | 20 | Slippage (points) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18051 Hull_GB — Inline dual Hull MA consensus with SuperTrend/HA confirm, 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 posInfo;
CSymbolInfo symInfo;
//============================ INPUTS (18 total) ====================
enum ENUM_TRADE_DIR { DIR_BOTH=0, DIR_LONG=1, DIR_SHORT=2 };
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_InpTF = PERIOD_H1;
ENUM_TIMEFRAMES g_InpHTF = PERIOD_H1;
input group "=== General ==="
input int InpTF = 0; // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Working timeframe
input int InpHTF = 6; // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF trend timeframe
input bool InpDryRun = true; // Dry-run (no live sends)
input bool InpKillSwitch = false; // Emergency kill switch
input string InpTradeComment = "Psgrowth.com Expert_18051"; // Trade comment
ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{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.