P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18055 TrendFollow

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

Pipsgrowth.com EX18055 Hull2EA_Lite — Dual Hull MA slope trend-follow with regime gate, full 12-layer stack.

Overview

Pipsgrowth EX18055 TrendFollow is a dual-Hull-MA slope follower that decides direction from the agreement of two inlined Hull moving averages on the last closed bar, then confirms that bias with a higher-timeframe Hull and a 3-state ADX regime classifier. The whole EA sits inside a 12-layer skeleton (REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester) but the design intent is tight: trend-only entries, ATR-based stops, an early break-even, and a wide trailing stop that lets winners run.

The signal engine does not call any iCustom indicator. Instead, the EA builds two Hull series inline from iMA(LWMA) handles — a fast pair at InpHullFastPeriod=20 and a slow pair at InpHullSlowPeriod=50 — and recomputes HMA = LWMA(2·LWMA(price, n/2) − LWMA(price, n), √n) on every evaluation. The HullValue() helper copies √n bars from each of the two underlying LWMA handles, forms the raw difference series, and re-applies an LWMA pass to that difference. The result is the standard Hull smoothing kernel: low lag, good noise rejection, and no dependency on a custom indicator buffer that could de-sync from the chart. Signal is read on the last closed bar (shift=1) and is strictly +1, −1, or 0 — the long path requires the fast Hull sloping up, the slow Hull sloping up, and the fast value above the slow value; the short path mirrors that. Mixed slopes, crossovers without slope alignment, or fast crossing slow but both flat all return 0 and block entries.

A second Hull pair is calculated on a higher timeframe (InpHullHTF input mapping; default value 8 falls through to PERIOD_H1) and used purely as a confirmation filter. The HTF Hull must slope in the same direction as the chart-TF signal or the entry is rejected — this is the only real multi-timeframe agreement check in the stack. The applied price is configurable (close/open/high/low/median/typical/weighted) but defaults to close. The HTF pairing is what gives the system its 'enter with the higher-timeframe trend' character; without it the slope follower can whipsaw on a single M5 candle flipping direction.

Regime classification is intentionally compact. The RegimeState() function reads ADX(InpAdxPeriod=14) at shift=1 and maps it to a 3-state label: StrongTrend when ADX ≥ InpAdxTrendMin=22, WeakTrend when ADX ≥ 0.6·InpAdxTrendMin (about 13.2), and blocked (choppy/range) otherwise. Unlike the corpus's heavier 7-state classifiers, this one only cares about whether ADX is high enough to trust the slope. The SignalComposite() function returns the same +1/−1/0 from HullSlopeChart, with a confidence tag (70 for StrongTrend, 50 for WeakTrend, 30 for blocked-regime entries that the signal still produced) that is logged but not currently used to gate entries — ConfirmEntry() does the real gating.

The no-trade layer in NoTradeBlock() handles all the live-fire rules. It checks the InpKillSwitch input first, then spread (must be ≤ InpMaxSpreadPts=35 points = 3.5 pips on a 5-digit XAUUSD quote), then server time (only 07:00–20:59 — roughly the London + New York cash session, with Asia explicitly excluded), then weekend proximity (Friday after 21:00 blocked, full weekend blocked), then broker trade mode, then the position cap (InpMaxPositions=1 by default), then the capital floor (InpCapitalCapFloor=50 dollars), and finally the daily loss limit (InpDailyLossLimitPct=3.0 percent of effective capital, computed from the per-magic realized PnL since 00:00 server time). Any of these triggers writes a reason to the log and returns without sending an order. DailyLossExceeded() walks the deal history, filters by magic + symbol, and sums profit + swap + commission since day start.

Risk is fixed-fractional. CalcLotsByRisk() takes the SL distance in price, converts it to a dollar-per-lot figure from g_tickValue/g_tickSize, and sizes the lot so that risking InpRiskPercent=0.5% of EffectiveCapital() (which falls back to AccountInfoDouble(EQUITY) since InpCapitalCapAmount defaults to 0 = cap disabled) covers exactly that dollar distance. The result is then snapped to g_volStep and clamped to g_volMin/g_volMax via NormalizeVolume(). MarginOk() pre-checks via OrderCalcMargin() before each send, and SendMarketOrder() retries once on requote/price-off/timeout before giving up. Slippage is InpSlippage=20 points, filling is set to whatever the broker advertises via SetTypeFillingBySymbol.

Stops are ATR-based and built once at entry. BuildStops() takes ATR(InpAtrPeriod=14) at shift=1 and produces SL = price − 1.8·ATR (long) and TP = price + 3.0·ATR (long), giving a 1:1.67 risk-reward that is then validated as ≥ 1.2 inside ConfirmEntry(). The R-multiple is tracked live in ManagePosition() against the original entry-to-stop distance so the trailing logic and break-even are both expressed in R-units rather than raw points. The break-even is a one-shot: once profitPts reaches InpBreakEvenAtR=1.0R, the SL ratchets to openPrice ± 1 point (so a small bid-ask friction adjustment) and never moves back. The trailing stop uses InpTrailAtrMultiplier=2.5·ATR(14) and is gated by the position being in profit by at least 0.5R — it only ever ratchets in the profitable direction (up for longs, down for shorts), respects the broker's stops/freeze level, and only updates if the new candidate is strictly better than the current SL. There is no partial take-profit in this build: positions either hit full TP, get trailed to scratch, or close on signal reversal or time.

Exit logic is dual. The first path is an opposite-signal exit — if the EA is long and HullSlopeChart(1) turns negative, or short and the slope turns positive, the position is closed via TryClose_EX18055() (3 attempts, 200ms sleep on requote/timeout/price-off/price-changed). The second path is a time-based exit: InpMaxBarsInTrade=120 bars at the working timeframe (10 hours on M5, 30 hours on M15) closes the position regardless of signal state. The time stop exists to prevent low-conviction trades from bleeding through regime transitions; it is hard-coded and has no input.

Operationally the EA ticks twice per second in spirit. OnTick() first runs ManageAllPositions() which loops over PositionsTotal() and applies ManagePosition() to every open position with the matching magic + symbol. Then it checks whether a new bar has opened (iTime shift=0 changed); if not, it returns immediately — so all signal evaluation happens exactly once per closed bar, not on every tick. The OnTester() formula is (netProfit × profitFactor) / (1 + maxDD) with a 30-trade floor, the same scoring used across the family. The risk warning in the source header is the standard 74–89% retail-loss disclosure required for European-distributed EAs.

The defaults are tuned for XAUUSD on M5 with a $100 account: 0.5% risk, 1.8·ATR SL, 3.0·ATR TP, 1R break-even, 2.5·ATR trail, 120-bar max hold, daily 3% loss cap, and 3.5-pip spread tolerance. The InpDryRun input defaults to true — the EA logs every intended trade but does not send a market order until the operator flips it off, which makes it safe to drop on a chart for the first few sessions while you confirm that the signal fires where you expect. The capital cap is disabled by default (InpCapitalCapAmount=0) so EffectiveCapital is the live equity; the $50 floor still applies as a safety net so the EA won't try to open trades on a blown account.

Strategy Deep Dive

Pipsgrowth EX18055 builds two inline Hull moving averages from iMA(LWMA) handles — fast at period 20 and slow at period 50 — then computes HMA = LWMA(2·LWMA(price, n/2) − LWMA(price, n), √n) on each evaluation by copying √n bars from each handle, forming the difference series, and re-applying an LWMA pass. Signal direction comes from HullSlopeChart(1): the long path needs fast-up + slow-up + fast > slow; the short path mirrors that; any disagreement returns 0. A second Hull pair on a higher timeframe (default H1 via InpHullHTF=8 → MapTimeframeInt default branch) acts as a confirmation filter and must agree with the chart-TF slope or the entry is rejected. The 3-state regime classifier reads ADX(14) and gates entries on StrongTrend (ADX ≥ 22) or WeakTrend (ADX ≥ 13.2), with choppy/range states blocked outright. Stops are ATR-based: SL = 1.8·ATR(14), TP = 3.0·ATR(14), 1:1.67 R:R validated at ≥ 1.2 in ConfirmEntry(). Position size is fixed-fractional at 0.5% of EffectiveCapital() against the SL distance, snapped to g_volStep. ManagePosition() handles break-even at 1R (one-shot to open+1pt) and a 2.5·ATR(14) trailing stop that activates at ≥ 0.5R and only tightens in the profitable direction; exits fire on opposite-signal or 120-bar time stop. The no-trade layer enforces 35-point spread cap, 07:00–20:59 server session (London + NY, Asia excluded), Friday-21:00 and weekend blocks, max 1 position, $50 capital floor, and 3% daily loss limit on per-magic realized PnL. InpDryRun defaults to true so the EA logs every intended trade without sending an order until the operator disables it; OrderCalcMargin pre-check and 1-attempt retry on requote/timeout protect the live send.

Entry Signal

Entries require both an inlined fast Hull MA (period 20) and slow Hull MA (period 50) to slope in the same direction on the last closed bar, with the fast series on the correct side of the slow series, plus a matching higher-timeframe Hull (default H1) and a 3-state ADX regime of StrongTrend (ADX ≥ 22) or WeakTrend (ADX ≥ 13.2). The signal is read once per closed bar, not on every tick, and the resulting order is sized to risk 0.5% of effective capital against a 1.8·ATR(14) stop.

Exit Signal

Exits are dual: the position closes via TryClose_EX18055() when HullSlopeChart(1) flips to the opposite sign (opposite-signal exit), and also closes when the trade has been open for 120 bars on the working timeframe (10 hours on M5, 30 on M15) regardless of signal state. The 1R break-even is not an exit — it ratchets the stop to entry+1 point — and the 2.5·ATR(14) trailing stop is monotonic, only ever tightening the stop in the profitable direction.

Stop Loss

Stop-loss is computed at entry as 1.8×ATR(14) on the last closed bar, snapped to the broker's stops/freeze level via AdjustStop(), and then ratcheted to entry+1 point once the trade reaches 1R (one-shot break-even, no regression). After the trade is in profit by ≥ 0.5R, the stop trails at 2.5×ATR(14) below the current bid (for longs) and only ever tightens in the profitable direction.

Take Profit

Take-profit is fixed at entry at 3.0×ATR(14) above entry (for longs) or below entry (for shorts), giving a 1:1.67 R:R that ConfirmEntry() validates as ≥ 1.2 before sending the order. There is no partial take-profit in this build — positions are either closed by hitting the full TP, by the opposite-signal exit, by the 120-bar time stop, or by the trailing stop tightening after a reversal.

Best For

This EA is built for XAUUSD on M5 or M15 with a $100 starting balance and a MEDIUM risk profile — the 0.5% per-trade risk, 3% daily loss cap, and 1.8·ATR stop produce a curve that scales with equity rather than fixed lots. The London + New York 07:00–20:59 server-time window and 35-point spread cap (3.5 pips on a 5-digit XAUUSD quote) suit a low-spread ECN broker with deep liquidity, and the InpDryRun=true default makes it safe to attach to a chart for the first few sessions before live trading. Run it on symbols with a clear regime — trending metals during their active session — and avoid ranging sessions where the 3-state regime classifier will block most signals anyway.

Strategy Logic

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

Family: TrendFollow Magic: 22218055 Version: 2.00

BRIEF: Inline Hull MA (fast + slow) computed from iMA(LWMA) handles; signal = slope direction of both HMA series on last CLOSED bar (shift=1), gated by ADX+ATR regime layer, HTF trend agreement, session/spread/news no-trade layer, capital- allocation cap on effective equity, ATR-based SL/TP, break-even at 1R, ATR trail, opposite-signal exit, time-based exit. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • FastHalf
  • FastFull
  • SlowHalf
  • SlowFull
  • HTFhalf
  • HTFfull
  • Adx
  • Atr

KEY FUNCTIONS:

  • HullValue()
  • full_period_safe()
  • AtrValue()
  • AdxValue()
  • NormalizeVolume()
  • AdjustStop()
  • TodayStart()
  • TodayRealizedPnL()
  • EffectiveCapital()
  • DailyLossExceeded()
  • RegimeState()
  • HullSlopeChart()
  • ...and 15 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (23 total across 6 groups):

  • [=== Hull Signal ===] InpHullFastPeriod = 20 // Fast Hull period (bars)
  • [=== Hull Signal ===] InpHullSlowPeriod = 50 // Slow Hull period (bars)
  • [=== Hull Signal ===] InpHullHTF = 8 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF confirmation timeframe
  • [=== Hull Signal ===] InpHullPrice = 1 // Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted) // Hull source price
  • [=== Regime Filter ===] InpAdxPeriod = 14 // ADX period (bars)
  • [=== Regime Filter ===] InpAdxTrendMin = 22.0 // ADX min for trend entry
  • [=== Regime Filter ===] InpAtrPeriod = 14 // ATR period (bars)
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (% of eff. capital)
  • [=== Risk & Sizing ===] InpMagicNumber = 22218055 // Magic number
  • [=== Risk & Sizing ===] InpTradeComment = "Psgrowth.com Expert_18055" // Trade comment
  • [=== Risk & Sizing ===] InpMaxPositions = 1 // Max concurrent positions (this symbol)
  • [=== Risk & Sizing ===] InpDailyLossLimitPct = 3.0 // Daily loss limit (% of eff. capital)
  • [=== Risk & Sizing ===] InpMaxBarsInTrade = 120 // Max bars in trade before exit
  • [=== Capital Allocation Cap ===] InpCapitalCapAmount = 0.0 // Cap on real-money equity ($)
  • [=== Capital Allocation Cap ===] InpCapitalCapFloor = 50.0 // Floor below which entries block ($)
  • [=== Exits (ATR-based) ===] InpAtrSlMultiplier = 1.8 // SL = mult * ATR
  • [=== Exits (ATR-based) ===] InpAtrTpMultiplier = 3.0 // TP = mult * ATR
  • [=== Exits (ATR-based) ===] InpBreakEvenAtR = 1.0 // Break-even trigger (R-multiple)
  • [=== Exits (ATR-based) ===] InpTrailAtrMultiplier = 2.5 // ATR trailing multiplier
  • [=== Execution ===] InpSlippage = 20 // Max slippage (points)
  • [=== Execution ===] InpMaxSpreadPts = 35.0 // Max allowed spread (points)
  • [=== Execution ===] InpDryRun = true // Dry-run (no live orders)
  • [=== Execution ===] InpKillSwitch = false // Kill switch (blocks new trades)
Pseudocode
// Pipsgrowth EX18055 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Inline Hull MA (fast + slow) computed from iMA(LWMA) handles; signal = slope direction of both HMA series on last CLOSED bar (shift=1), gated by ADX+ATR regime layer, HTF trend agreement, session/spread/news no-trade layer, capital- allocation cap on effective equity, ATR-based SL/TP, break-even at 1R, ATR trail, opposite-signal exit, time-based exit. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

ON_INIT:
    Create indicator handles: FastHalf, FastFull, SlowHalf, SlowFull, HTFhalf, HTFfull, Adx, Atr
    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:
M5M15

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
InpHullFastPeriod20Fast Hull period (bars)
InpHullSlowPeriod50Slow Hull period (bars)
InpHullHTF8Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF confirmation timeframe
InpHullPrice1Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted) // Hull source price
InpAdxPeriod14ADX period (bars)
InpAdxTrendMin22.0ADX min for trend entry
InpAtrPeriod14ATR period (bars)
InpRiskPercent0.5Risk per trade (% of eff. capital)
InpMagicNumber22218055Magic number
InpTradeComment"Psgrowth.com Expert_18055"Trade comment
InpMaxPositions1Max concurrent positions (this symbol)
InpDailyLossLimitPct3.0Daily loss limit (% of eff. capital)
InpMaxBarsInTrade120Max bars in trade before exit
InpCapitalCapAmount0.0Cap on real-money equity ($)
InpCapitalCapFloor50.0Floor below which entries block ($)
InpAtrSlMultiplier1.8SL = mult * ATR
InpAtrTpMultiplier3.0TP = mult * ATR
InpBreakEvenAtR1.0Break-even trigger (R-multiple)
InpTrailAtrMultiplier2.5ATR trailing multiplier
InpSlippage20Max slippage (points)
InpMaxSpreadPts35.0Max allowed spread (points)
InpDryRuntrueDry-run (no live orders)
InpKillSwitchfalseKill switch (blocks new trades)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18055.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18055 Hull2EA_Lite — Dual Hull MA slope 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>

//=================================================================//
//                            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_InpHullHTF = PERIOD_H1;
ENUM_APPLIED_PRICE g_InpHullPrice = PRICE_CLOSE;
input group "=== Hull Signal ==="
input int               InpHullFastPeriod   = 20;            // Fast Hull period (bars)
input int               InpHullSlowPeriod   = 50;            // Slow Hull period (bars)
input int InpHullHTF = 8; // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1)     // HTF confirmation timeframe
input int InpHullPrice = 1; // Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted)   // Hull source price

ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
   switch(tf)
   {
      case 1: return PERIOD_M1;
      case 2: return PERIOD_M5;

Full source code available on download

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

Tags:ex18055trendfollowpipsgrowthfreemt5xauusd

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_EX18055.mq5
File Size35.0 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M5M15
Currency Pairs
XAUUSD
Min. Deposit$100