Pipsgrowth EX18058 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX18058 Hull2EA_Pro — Dual inline Hull-MA trend-follow with regime gate, full 12-layer stack.
Overview
Pipsgrowth EX18058 is a Hull Moving Average trend-following EA that frames every entry through a custom in-line Hull-MA engine plus a seven-state regime classifier. The Hull-MA is not loaded as an indicator — the source walks raw close arrays through a hand-rolled LWMA primitive and combines two weighted averages (n/2 and n) to construct a fast 20-period Hull and a slow 55-period Hull, then compares each to its prior value to derive a slope-color (0=up, 1=down, 2=flat). A consensus requires both Hulls to print the same slope-color before any long or short can be staged; with InpRequireBothHulls left true the EA will not accept fast-only signals even when the slow line is sideways, eliminating a class of mid-trend whipsaws. The signal is computed on the closed bar (InpSignalShift=1) so no repaint on the forming bar.
The seven-state regime classifier in UpdateRegime() drives the no-trade gate. It blends three independent measures: ADX(14) strength, an ATR(14) percentile computed over 50 bars (with the 75th-percentile ceiling used to flag expansion and the 25th to mark quiet), and a Bollinger Bands(20, 2.0) width percentile. The resulting states are STRONG_TREND (ADX ≥ 25 and ATR-percentile ≥ 75), WEAK_TREND (ADX ≥ 18), COMPRESS (BB-width-percentile ≤ 20), EXPAND (BB-width-percentile ≥ 80), BREAKOUT (ATR-percentile ≥ 75 with ADX below 25), RANGE (ADX < 18 with BB-width between the 40th and 70th percentile), and CHOPPY as the catch-all. CHOPPY is the only state that completely blocks entries; everything else remains open to confirmation, which is what gives the EA its 12-layer risk posture.
Confirmation runs through three filters before sizing fires. ConfirmADXStrong() reads the closed-bar ADX and demands the value sit at or above 18 — the same threshold that defines WEAK_TREND — so the engine is willing to enter on a weak trend provided the rest of the suite agrees. ConfirmMinRR() rejects any setting where the configured TP-multiple is not strictly larger than the SL-multiple, a sanity gate on the input ratio. If InpUseHTFBias is left at its default true, HTFHullBias() computes an independent 35-period Hull on the higher timeframe (g_InpHTF — with InpHTF=8 falling through the default branch, this resolves to H1) and the entry direction must match the HTF slope-color; the HTF return value of 0 (flat) is treated as permissive, so genuine HTF trends are required only when the bias is unambiguous.
Sizing and risk draw from a single capital pool. ComputeEffectiveCapital() returns the account equity, optionally floored by InpCapitalCapAmount (default 0.0 = cap disabled). If the resulting effective cap falls below InpCapitalCapFloor (default 50.0), IsCapitalBelowFloor() refuses to stage new entries and the dashboard prints a CAPTIAL BELOW FLOOR block. CalcLots() then converts a 0.5% risk fraction into a stop-distance-relative lot count, falling back to InpFixedLots=0.10 whenever the risk model cannot produce a positive loss-per-lot. MarginOK() pre-flights each candidate through OrderCalcMargin before any order hits the wire. A daily realized PnL watcher (InpDailyLossLimitPercent=3.0% of effective cap) blocks new entries once losses hit that threshold.
Stop placement is ATR-driven, not pip-fixed. Each new position gets SL at 1.8× the live ATR(14) (InpATR_SL_Mult) and TP at 3.2× ATR (InpATR_TP_Mult), which works out to roughly a 1:1.78 reward-to-risk ratio — a deliberate step up from a 1:1 setup. The EnforceStopsDistance() helper pushes both prices inside the broker's stops-level plus one point so the order is never rejected for being too close to market. ManageOpenPositions() runs on every tick and looks for two distinct events: a break-even ratchet (InpATR_BE_Mult=1.0, so once profit reaches 1× ATR the stop moves to open+1 point for buys, open-1 point for sells) and a forward-only trail at 1.5× ATR that activates only once profit has reached 2× the trail distance (so the trail typically begins at 3× ATR of profit). The trail and BE fire through TryModify_EX18058, which retries up to three times on requotes, timeouts, and price changes with a 100ms backoff.
Exits branch on three independent events. CheckRegimeExit() closes the entire position book whenever the regime flips to CHOPPY — a deliberately aggressive exit that treats loss of directional structure as a stop signal regardless of unrealized PnL. If InpCloseOnReverse is true (default), a fresh closed-bar signal that points opposite to the held direction calls CloseAllMyPositions() through TryClose_EX18058, which also retries three times on transient errors. SessionOK() refuses fresh entries on Friday after 21:00 server time and on weekends, so open trades are still subject to normal Friday-evening spread widening but new orders will not be staged through that window. SpreadOK() scales the maximum allowed spread to 0.45× the current ATR — a self-calibrating filter that is more permissive during high-volatility sessions and tighter during quiet tape.
Pyramiding is wired in but disabled by default. Setting InpEnablePyramid=true unlocks CanPyramid(), which permits up to InpPyramidMax=3 legs in the same direction provided every existing leg is in profit, every existing leg is already past its break-even stop, and the current price is at least 0.5× ATR (PYRAMID_MIN_ATR) beyond the oldest leg's open. The third condition is what prevents the EA from reloading the same bar — it must see actual progress before adding exposure. With pyramiding left off, InpMaxConcurrent=3 is still enforced as a hard ceiling for any combination of long and short positions.
A few distinctive engineering choices are worth flagging. First, the H1 higher-timeframe is hard-wired through the default branch of MapTimeframeInt() because InpHTF=8 is outside the 1..7 enum; this is not a bug but it does mean the HTF confirmation is effectively H1 unless the user manually picks another timeframe. Second, the order comment is fixed at "Psgrowth.com Expert_18058" — brokers and prop firms that route by comment will see this on every fill. Third, InpDryRun defaults to true, so the EA ships in a logging-only mode; live trading requires the user to flip the input off. Fourth, there is no weekly loss cap, no time stop on open positions, no partial close, and no cooldown between losses — the safety net is concentrated in the daily-loss limit, the CHOPPY regime exit, the opposite-signal close, and the trailing-stop structure rather than in time-based or loss-streak-based tripwires. Together these choices make EX18058 a tightly scoped trend rider: it waits for a strong consensus from two slope-colors, confirms with HTF and ADX, sizes to a 1:1.78 R:R, and exits on the first sign of structural failure.
Strategy Deep Dive
EX18058 reads the closed bar, walks the raw close series through a hand-rolled LWMA primitive to build a fast 20 and slow 55 Hull-MA in-line, and only stages a trade when both slope-colors agree. UpdateRegime() blends ADX(14), a 50-bar ATR percentile, and a Bollinger Bands width percentile into a 7-state classifier (STRONG_TREND / WEAK_TREND / COMPRESS / EXPAND / BREAKOUT / RANGE / CHOPPY), with CHOPPY the only state that gates entries. Confirmation is three independent filters: ConfirmADXStrong() at ADX ≥ 18, ConfirmMinRR() at TP-mult > SL-mult, and HTFHullBias() reading a 35-period Hull on the H1 chart. Sizing is 0.5% of the effective capital cap (with a 50-USD floor block), and the trade is sent only after a successful OrderCalcMargin pre-check. Stops sit at 1.8× ATR, targets at 3.2× ATR, break-even triggers at 1× ATR, and the forward-only trail at 1.5× ATR; a CHOPPY regime flip, an opposite-signal close, or a daily 3% loss limit brings the position book to zero. InpDryRun defaults to true, so the EA ships in a logging-only mode and TryClose/TryClosePartial/TryModify retry up to three times on requote, timeout, price-off, and price-changed errors with 200ms (close) or 100ms (modify) backoff.
Long entry on HullConsensus() returning +1: both the fast 20-period and slow 55-period in-line Hull-MA lines must print the same upward slope-color on the closed bar. HTFHullBias() then confirms direction on the H1 Hull(35) when InpUseHTFBias is on, and ConfirmADXStrong() requires ADX(14) >= 18. Short entry mirrors the same stack with downward slope-colors.
Exits branch on three events: CheckRegimeExit() closes the entire book when the regime classifier flips to CHOPPY; a fresh closed-bar consensus that points opposite to the held direction triggers CloseAllMyPositions() via TryClose_EX18058; and the trailing stop at 1.5x ATR, once it has ratcheted past break-even, is the slow-burn exit that lets winners run.
Per-trade stop is 1.8x ATR(14) on the closed bar, with EnforceStopsDistance() pushing it past the broker stops-level plus one point. A ratchet to open+1pt fires once profit reaches 1.0x ATR (InpATR_BE_Mult), and a 1.5x ATR forward-only trail takes over once profit clears 2x the trail distance.
Take-profit is set to 3.2x ATR(14) (InpATR_TP_Mult) at entry, giving roughly a 1:1.78 reward-to-risk ratio against the 1.8x ATR stop. ConfirmMinRR() refuses any configuration where TP-multiple is not strictly larger than SL-multiple, locking in at least 1:1.
Best deployed on XAUUSD M5 with an H1 bias chart, on a low-spread ECN broker that can deliver consistent sub-second execution (the spread gate is a 0.45x ATR multiple, so the wider the ATR the more headroom the EA has on a noisy entry tick). The minimum recommended balance is $100 with the default 0.5% risk, and the capital-cap floor at $50 keeps the EA from over-staging a small account. Weekend and Friday-after-21:00 server time are gated out, so the session window is effectively Monday through Friday daytime — pair this EA with a London/New York session schedule rather than a 24/7 grid setup.
Strategy Logic
Pipsgrowth EX18058 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218058
Version: 2.00
BRIEF:
Inline dual Hull-MA (fast/slow) slope-color consensus + 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:
ullH1Handle_dummy
KEY FUNCTIONS:
LWMA()HullMA()HullColor()LoadSymbolInfo()NormalizeLots()NormalizePrice()EnforceStopsDistance()ComputeEffectiveCapital()IsCapitalBelowFloor()EARealizedPnLToday()UpdateRegime()HullConsensus()- ...and 20 more
INTERNAL CONSTANTS (17 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)MAX_DAILY_LOSS_RETRIES= 1 // Retries on requote/timeoutSLIPPAGE_POINTS= 20 // Default slippage- ...and 2 more
INPUT PARAMETERS (24 total across 7 groups):
- [=== Identity ===]
InpMagic=22218058// Magic number - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_18058" // Trade comment - [=== 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) - [=== 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 ===]
InpATR_BE_Mult=1.0// Break-even trigger (ATRmult) - [=== Risk & Sizing ===]
InpDailyLossLimitPercent=3.0// Daily loss limit (% of effective cap) - [=== Risk & Sizing ===]
InpMaxSpreadATR=0.45// Max spread (ATRmult) - [=== 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(Hull-MA) ===]InpHullFast= 20 // Fast Hull period (entry TF) - [===
Signal(Hull-MA) ===]InpHullSlow= 55 // Slow Hull period (entry TF) - [=== Regime / Confirm ===]
InpUseHTFBias=true// RequireHTFHull-MA agreement - [=== Regime / Confirm ===]
InpRequireBothHulls=true// Require fast+slow same direction - [=== Regime / Confirm ===]
InpMaxConcurrent= 3 // Max concurrent positions (thisEA/symbol) - [=== Exit / Manage ===]
InpEnablePyramid=false// Enable pyramiding (profit only) - [=== Exit / Manage ===]
InpPyramidMax= 3 // Max pyramid legs - [=== 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 EX18058 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Inline dual Hull-MA (fast/slow) slope-color consensus + 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: ullH1Handle_dummy
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 | 22218058 | Magic number |
| InpTradeComment | "Psgrowth.com Expert_18058" | Trade comment |
| 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) |
| 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 |
| InpATR_BE_Mult | 1.0 | Break-even trigger (ATR mult) |
| InpDailyLossLimitPercent | 3.0 | Daily loss limit (% of effective cap) |
| InpMaxSpreadATR | 0.45 | Max spread (ATR mult) |
| InpCapitalCapAmount | 0.0 | Real-money cap (USD equity, not notional) |
| InpCapitalCapFloor | 50.0 | Floor below which new entries are blocked |
| InpHullFast | 20 | Fast Hull period (entry TF) |
| InpHullSlow | 55 | Slow Hull period (entry TF) |
| InpUseHTFBias | true | Require HTF Hull-MA agreement |
| InpRequireBothHulls | true | Require fast+slow same direction |
| InpMaxConcurrent | 3 | Max concurrent positions (this EA/symbol) |
| InpEnablePyramid | false | Enable pyramiding (profit only) |
| InpPyramidMax | 3 | Max pyramid legs |
| 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 EX18058 Hull2EA_Pro — Dual 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 MAX_DAILY_LOSS_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 NEWS_BLOCK_BARS 2 // Bars either side of bar-based news window (manual)
//+------------------------------------------------------------------+
//| 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;
}
}
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;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.