P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18076 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M15, H4

Pipsgrowth.com EX18076 Hull Advanced — dual Hull-MA trend-follower, full 12-layer stack.

Overview

Pipsgrowth EX18076 Hull Advanced is a dual-Hull moving-average trend follower for MT5 built around an inline computation of two Hull MAs — fast (20 bars) and slow (50 bars) — and the agreement between their slopes. The EA is engineered for the H4 and M15 timeframes, with a default pair of XAUUSD, and falls into the medium-risk category. The setup expects a low-spread broker, a minimum $100 account, and a market where ATR-based stops are wide enough to absorb gold's overnight ranges.

The Hull construction is done entirely with iMA LWMA primitives — there is no iCustom or external indicator dependency. Each Hull is computed as the difference of two linearly weighted moving averages, then smoothed with a square-root-of-period weighted average: raw = 2 × LWMA(period/2) − LWMA(period), and the smoothed value is the result of a small weighted average of length round(sqrt(period)) applied to the raw series. For the default 20/50 settings, that yields fast Hull built from LWMAs of 10 and 20 with a 4-bar smoother, and slow Hull built from LWMAs of 25 and 50 with a 7-bar smoother. The trend direction is the comparison of the Hull value at the last closed bar against the prior bar — positive slope points long, negative slope points short, flat produces no signal.

By default, both Hulls must agree before a position is opened. This is the InpRequireBoth=true input, and it is the most important signal gate: a single-Hull flip is filtered out. If the user sets InpRequireBoth=false, the system falls back to a majority vote between the two Hull directions. Each signal also carries a confidence value in the 0–100 range derived from the magnitude of the fast-Hull slope normalized by the current ATR(14); values are clamped to 100, and the confidence is reported in logs even though the strategy itself is binary in the shipped code.

The regime classifier runs on every new bar and tags the market into one of seven states. ADX(14) at or above 25 combined with an ATR percentile at or above 50% over the last 100 bars places the market in STRONG_TREND. ADX(20–25) is WEAK_TREND. A Bollinger band width that has expanded by more than 10% from the prior bar combined with an ATR percentile of 60% or more is EXPAND; expansion without the percentile gate is BREAKOUT. A width compression of 5% or more is COMPRESS, and the fallback state is RANGE. The NoTradeGates function blocks any new entries when the regime classifier cannot be computed (treated as CHOPPY) or when the regime is explicitly CHOPPY, so a high-conviction signal in a flat market is still rejected.

Confirmations are stacked on top of the signal. The HTF confirmation reads an EMA(50) on the H4 chart — buy entries must occur with price above the H4 EMA, sell entries below it. The session gate restricts entries to server hours 08:00–20:00, with explicit Friday 22:00 and full weekend blocks for liquidity reasons. The spread filter uses a rolling 50-tick average and rejects entries when the current spread exceeds max(30 points, 2× average). The candle confirmation requires that the last closed bar's direction match the signal, and the risk-to-reward gate requires the planned TP distance to be at least 1.5× the SL distance before any order is sent.

Sizing is risk-based at 0.5% of effective capital per trade, with effective capital computed as the current equity minus the day's realized P&L on this magic number. The lot calculation goes through OrderCalcMargin as a pre-flight check, and the lot is reduced automatically if the required margin would exceed 95% of free margin. The capital cap input defaults to zero (off) and acts as a soft ceiling on the capital considered for sizing when turned on. A hard floor of $50 equity shuts off entries entirely. The MaxOpenTrades input caps the EA at three concurrent positions; the symbol exposure counter also enforces a three-position cap on the chart symbol.

Position management runs on every tick, not just on new bars. At a 1R profit, half of the position is closed and the stop is moved to break-even. After the position is in profit by more than 0.5R, an ATR(14) trail at 2.5× ATR activates, ratcheting the stop forward only when a tighter stop is available. A 1-hour cooldown is triggered after three consecutive losses, blocking any new entries for the following hour. The time-based exit is 80 bars on the entry timeframe, which translates to roughly 40 hours on M30, 20 hours on M15, or 13.3 days on H4. Two more exit paths exist: the EA will close a position immediately if the dual-Hull signal flips to the opposite direction, and it will also close on a regime change to RANGE, COMPRESS, or CHOPPY.

The order layer itself is hardened. Every position action goes through a 3-attempt retry helper (TryClose_EX18076, TryClosePartial_EX18076, TryModify_EX18076) that sleeps 200ms on requotes, timeouts, price-off, or price-changed events for close operations and 100ms for modify operations. SetDeviationInPoints is set to the InpSlippagePts input (20 points default). The filling mode is auto-detected from SYMBOL_FILLING_MODEFOK if supported, otherwise IOC, otherwise RETURN. The order comment is hardcoded to "Psgrowth.com Expert_18076", and trades are tagged with the magic number 22218076.

In dry-run mode, which is the default (InpDryRun=true), no live orders are sent; the EA prints each would-be entry to the journal and updates its internal state so the strategy logic can be validated visually before going live. The OnTester formula in the Strategy Tester is (net × profit factor) / (1 + balance drawdown), and a minimum of 30 trades is required before a result is returned — combinations that survive this filter tend to be the ones that produce stable equity curves in walk-forward. The OnInit function returns INIT_FAILED if any of the eight indicator handles cannot be created — Hull LWMA pairs for fast and slow, ADX(14), ATR(14), Bollinger Bands(20, 2.0), and the H4 EMA(50) — so the EA will not run on a chart where the data history is too short for the longest calculation. The OnDeinit function releases all eight handles cleanly.

Strategy Deep Dive

Pipsgrowth EX18076 runs entirely from inlined LWMA primitives — there is no iCustom or external indicator dependency — and constructs the fast and slow Hull MAs by taking 2×LWMA(period/2)−LWMA(period) and then applying a small weighted smoothing of round(sqrt(period)) bars. On every closed bar, the trend classifier reads ADX(14) plus an ATR(14) percentile rank over a 100-bar lookback plus a Bollinger band width delta to bucket the market into STRONG_TREND, WEAK_TREND, EXPAND, BREAKOUT, COMPRESS, RANGE, or CHOPPY; the CHOPPY bucket is the one that blocks entries via NoTradeGates. Position management runs on every tick — partial close at 1R, break-even at 1R, ATR(14) trail at 2.5× after 0.5R, opposite-signal close, regime-change close, and a hard 80-bar time stop — and every order action is wrapped in a 3-attempt retry helper that sleeps 200ms on requotes/price-offs for closes and 100ms for modifies. Sizing is 0.5% of equity (net of today's realized P&L for this magic) clamped by margin headroom; the risk layer adds a $50 capital floor, 3% daily and 6% weekly loss limits, and a one-hour cooldown after three consecutive losses. The eight indicator handles — four for the Hull LWMA halves and fulls, plus ADX, ATR, Bands, and the H4 EMA(50) — are created in OnInit and released in OnDeinit; the EA returns INIT_FAILED if any handle creation fails, so it refuses to run on a chart with insufficient history.

Entry Signal

Pipsgrowth EX18076 fires a long when both the fast Hull (20) and slow Hull (50) slope up on the last closed bar and a short when both slope down, with an additional gate requiring the H4 EMA(50) to agree, the spread to stay under max(30 points, 2× the 50-tick average), and the previous closed candle to match the direction. Entries are restricted to server hours 08:00–20:00, blocked on Friday after 22:00 and across the weekend, and rejected when the regime classifier returns CHOPPY, when the effective capital falls below $50, when daily loss exceeds 3%, or when weekly loss exceeds 6%. A one-hour cooldown is enforced after three consecutive losing closes, and at most three positions are open concurrently for this magic.

Exit Signal

Positions are closed via three layered exits: an opposite-signal close when the dual-Hull consensus flips, a regime-change close when the classifier returns RANGE, COMPRESS, or CHOPPY, and a hard time stop at 80 bars on the entry timeframe. Partial profit-taking closes 50% of the position at 1R, and the stop is moved to break-even on the same 1R trigger. A 2.5× ATR(14) trailing stop activates after 0.5R and ratchets forward only when a tighter level is available.

Stop Loss

The stop-loss is set to 1.8× the ATR(14) value of the last closed bar at the moment of entry, snapped to respect the broker's stops-level minimum. After the trade reaches 1R, the stop is moved to break-even (open price plus stops-level), and a 2.5× ATR(14) trailing stop takes over once the trade is in profit by more than 0.5R.

Take Profit

The take-profit is fixed at 3.0× ATR(14) from entry, giving a 1:1.67 reward-to-risk ratio when paired with the 1.8× ATR stop. Half of the position is also closed at 1R as a partial TP, locking in realized profit before the full target is hit.

Best For

Pipsgrowth EX18076 is tuned for the H4 and M15 timeframes on XAUUSD, with a minimum recommended balance of $100, and is rated medium risk given the 0.5% per-trade risk and the 1.8× ATR stop sized for gold's intraday range. The 8–20 server session gate and the 30-point (3-pip) hard spread cap point to brokers that offer competitive gold pricing during London and New York hours — ECN or RAW accounts with deep liquidity, not standard accounts that widen the spread during the rollover. The default is InpDryRun=true, so test the EA in the Strategy Tester or on a demo before going live, and consider widening InpAtrSlMult to 2.02.5 when running on the H4 timeframe to keep stops proportional to the higher-bar ATR.

Strategy Logic

Pipsgrowth EX18076 TrendFollow — Strategy Logic Analysis (from .mq5 source)

Family: TrendFollow Magic: 22218076 Version: 2.00

BRIEF: Self-contained Hull-MA trend-follower. Dual inline Hull-MA (fast+slow) consensus on last CLOSED bar drives +1/-1/0 signal. Entries gated by REGIME (ADX + ATR-pct + Bollinger width), CONFIRM (HTF trend + session + spread + candle-close), NO-TRADE gates (news window, max daily loss, max open/exposure, weekend), SIZING via effective_capital (capital cap), RISK hard SL ATR-based, IN-TRADE break-even + partial TP + ATR-trail + opposite-signal exit + time exit. Pyramid default OFF. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Adx
  • Atr
  • Bands
  • HtfMa
  • HullFastFull
  • HullFastHalf
  • HullSlowFull
  • HullSlowHalf

KEY FUNCTIONS:

  • NormP()
  • MinStopsDist()
  • RefreshSym()
  • SpreadPoints()
  • ClampVolume()
  • EffectiveCapital()
  • RealizedPnLToday()
  • RealizedPnLThisWeek()
  • HullRawSeries()
  • HullValue()
  • HullSignal()
  • ConfirmChecks()
  • ...and 13 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (20 total across 5 groups):

  • [=== Identity ===] InpDryRun = true // Dry-run mode (no live orders)
  • [=== Identity ===] InpKillSwitch = false // Kill switch (flatten+block)
  • [=== Identity ===] InpMagic = 22218076 // Magic number
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18076" // Order comment
  • [=== Identity ===] InpSlippagePts = 20 // Max slippage (points)
  • [=== Hull Signal (LWMA-inlined) ===] InpHullFastPeriod = 20 // Fast Hull period (bars)
  • [=== Hull Signal (LWMA-inlined) ===] InpHullSlowPeriod = 50 // Slow Hull period (bars)
  • [=== Hull Signal (LWMA-inlined) ===] InpHullDivisor = 2.0 // Hull divisor (ratio)
  • [=== Hull Signal (LWMA-inlined) ===] InpRequireBoth = true // Require both Hulls to agree
  • [=== Risk & Sizing ===] InpCapitalCapAmount = 0.0 // Capital cap ($ equity)
  • [=== Risk & Sizing ===] InpCapitalCapFloor = 50.0 // Floor below which no entries ($)
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (% of effective)
  • [=== Risk & Sizing ===] InpDailyLossPct = 3.0 // Daily loss limit (% of effective)
  • [=== Risk & Sizing ===] InpWeeklyLossPct = 6.0 // Weekly loss limit (% of effective)
  • [=== Risk & Sizing ===] InpMaxOpenTrades = 3 // Max concurrent trades
  • [=== Entry / SL / TP ===] InpAtrSlMult = 1.8 // SL = ATR * mult (ratio)
  • [=== Entry / SL / TP ===] InpAtrTpMult = 3.0 // TP = ATR * mult (ratio)
  • [=== Manage / Exit ===] InpBreakEvenAtR = 1.0 // Break-even trigger (R-multiple)
  • [=== Manage / Exit ===] InpAtrTrailMult = 2.5 // ATR trail distance (mult)
  • [=== Manage / Exit ===] InpMaxBarsInTrade = 80 // Max bars in trade (0=off)
Pseudocode
// Pipsgrowth EX18076 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Self-contained Hull-MA trend-follower. Dual inline Hull-MA (fast+slow) consensus on last CLOSED bar drives +1/-1/0 signal. Entries gated by REGIME (ADX + ATR-pct + Bollinger width), CONFIRM (HTF trend + session + spread + candle-close), NO-TRADE gates (news window, max daily loss, max open/exposure, weekend), SIZING via effective_capital (capital cap), RISK hard SL ATR-based, IN-TRADE break-even + partial TP + ATR-trail + opposite-signal exit + time exit. Pyramid default OFF. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

ON_INIT:
    Create indicator handles: Adx, Atr, Bands, HtfMa, HullFastFull, HullFastHalf, HullSlowFull, HullSlowHalf
    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

Optimized Brokers:
ExnessIC Markets
Optimized Symbols:
XAUUSD
Optimized Timeframes:
M15H4

How to Install This EA on MT5

  1. 1Download the .mq5 file using the button above
  2. 2Open MetaTrader 5 on your computer
  3. 3Click File → Open Data Folder in the top menu
  4. 4Navigate to MQL5 → Experts and paste the .mq5 file there
  5. 5In MT5, right-click Expert Advisors in the Navigator panel → Refresh
  6. 6Drag the EA onto an H4 or Daily chart for best results
  7. 7Configure EMA periods, ADX threshold, and lot size in the dialog
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
InpDryRuntrueDry-run mode (no live orders)
InpKillSwitchfalseKill switch (flatten+block)
InpMagic22218076Magic number
InpTradeComment"Psgrowth.com Expert_18076"Order comment
InpSlippagePts20Max slippage (points)
InpHullFastPeriod20Fast Hull period (bars)
InpHullSlowPeriod50Slow Hull period (bars)
InpHullDivisor2.0Hull divisor (ratio)
InpRequireBothtrueRequire both Hulls to agree
InpCapitalCapAmount0.0Capital cap ($ equity)
InpCapitalCapFloor50.0Floor below which no entries ($)
InpRiskPercent0.5Risk per trade (% of effective)
InpDailyLossPct3.0Daily loss limit (% of effective)
InpWeeklyLossPct6.0Weekly loss limit (% of effective)
InpMaxOpenTrades3Max concurrent trades
InpAtrSlMult1.8SL = ATR * mult (ratio)
InpAtrTpMult3.0TP = ATR * mult (ratio)
InpBreakEvenAtR1.0Break-even trigger (R-multiple)
InpAtrTrailMult2.5ATR trail distance (mult)
InpMaxBarsInTrade80Max bars in trade (0=off)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18076.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18076 Hull Advanced — dual Hull-MA trend-follower, 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>

//============================ INPUTS ================================
input group "=== Identity ==="
input bool        InpDryRun           = true;       // Dry-run mode (no live orders)
input bool        InpKillSwitch       = false;      // Kill switch (flatten+block)
input ulong       InpMagic            = 22218076;   // Magic number
input string      InpTradeComment     = "Psgrowth.com Expert_18076";  // Order comment
input int         InpSlippagePts      = 20;         // Max slippage (points)

input group "=== Hull Signal (LWMA-inlined) ==="
input int         InpHullFastPeriod   = 20;         // Fast Hull period (bars)
input int         InpHullSlowPeriod   = 50;         // Slow Hull period (bars)
input double      InpHullDivisor      = 2.0;        // Hull divisor (ratio)
input bool        InpRequireBoth      = true;       // Require both Hulls to agree

input group "=== Risk & Sizing ==="
// InpCapitalCapEnabled removed — use InpCapitalCapAmount=0 to disable      // Capital cap enabled
input double      InpCapitalCapAmount  = 0.0;     // Capital cap ($ equity)
input double      InpCapitalCapFloor   = 50.0;      // Floor below which no entries ($)
input double      InpRiskPercent       = 0.5;       // Risk per trade (% of effective)
input double      InpDailyLossPct      = 3.0;       // Daily loss limit (% of effective)
input double      InpWeeklyLossPct     = 6.0;       // Weekly loss limit (% of effective)
input int         InpMaxOpenTrades     = 3;         // Max concurrent trades

input group "=== Entry / SL / TP ==="
input double      InpAtrSlMult        = 1.8;        // SL = ATR * mult (ratio)
input double      InpAtrTpMult        = 3.0;        // TP = ATR * mult (ratio)

input group "=== Manage / Exit ==="
input double      InpBreakEvenAtR     = 1.0;        // Break-even trigger (R-multiple)
input double      InpAtrTrailMult     = 2.5;        // ATR trail distance (mult)
input int         InpMaxBarsInTrade   = 80;         // Max bars in trade (0=off)
//============================ GLOBALS ===============================

//--- Hardcoded constants (not exposed as inputs to keep input count <= 22)
#define ADX_PERIOD         14
#define ADX_STRONG         25.0
#define ADX_WEAK           20.0
#define ATR_PERIOD         14
#define ATR_PCT_LOOKBACK   100
#define BANDS_PERIOD       20
#define BANDS_DEV          2.0
#define HTF_TIMEFRAME      PERIOD_H4
#define HTF_MA_PERIOD      50
#define SESS_START_H       8
#define SESS_END_H         20
#define MAX_SPREAD_PTS     30.0
#define MIN_RR             1.5

Full source code available on download

Educational purposes only. Do NOT use with real money. Test on demo accounts only.

Tags:ex18076trendfollowpipsgrowthfreemt5xauusd

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

Community

Sign in to contributeSign In

Educational purposes only. Do NOT use with real money. Test on demo accounts only.

File NamePipsgrowth_com_EX18076.mq5
File Size33.8 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M15H4
Currency Pairs
XAUUSD
Min. Deposit$100