P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18039 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX18039 GB10 5.2 — self-contained Hull MA Trend-Follow EA, full spec stack.

Overview

Pipsgrowth EX18039 TrendFollow is a Hull Moving Average slope-reversal EA designed to buy the first bar of a fresh HMA turn and sell the first bar of a fresh HMA turn-down on XAUUSD M5. The HMA is computed inline in the CalcHMA() function from WMA primitives (no iCustom, no .mqh, no external indicator): it builds raw[i] = 2*WMA(period/2) - WMA(period) for sqrt(period)+1 bars, then WMA-weights the raw series so the newest bar carries the highest weight. With InpHMAPeriod = 21 the half-window is 10, the full window is 21, and the smoothing window is 4 — the standard Hull recipe. The signal function HmaSignal() evaluates slope_now = h1 - h2 and slope_prev = h2 - h3 on the last closed bar (shift 1) and emits a buy only when slope_prev <= 0 and slope_now > 0, or a sell in the mirror case. That is a strict zero-crossing of the HMA slope, not a price-pullback pattern. A confidence score is derived from |slope| / h1 * 1000 * 50 + 25, capped at 100, and TryEntry() rejects any signal with confidence below 30.

Entries are gated by a higher-timeframe trend agreement check. HTFTrendDir() pulls an EMA(50) on the selected HTF (InpHTFTrendTF = 8 maps through the MapTimeframeInt() switch, which falls back to PERIOD_H1 for any value outside 1..7, so the effective HTF is H1) and returns +1 only if the H1 close is above the EMA and the EMA is rising, or -1 only if the close is below and the EMA is falling. A long HMA turn with an H1 downtrend is dropped, and the no-trade reason is logged as "HTF trend disagrees". An R/R floor of 1.0 is also enforced — if InpATRSLmult / InpATRTPmult drops below 1, the EA refuses to send.

The regime classifier ClassifyRegime() runs on every tick and reads 50 bars of ATR(14), 3 bars of ADX(14) main, and 30 bars of Bollinger Bands(20, 2.0) width. It returns one of six states: REG_STRONG_TREND (ADX >= 22 and ATR-percentile > 0.6), REG_WEAK_TREND (ADX >= 18 and ATR-percentile > 0.4), REG_COMPRESS (current BB-width < prior 30-bar width * 0.75 and ATR-percentile < 0.35), REG_EXPAND (current BB-width > prior width * 1.35 and ATR-percentile > 0.55), REG_CHOPPY (ADX < 15 or ATR-percentile < 0.20), and REG_RANGE as the residual. The choppy state is the only one that hard-blocks entries in CanTradeNew(). All other regimes are valid trading contexts; the compress and expand states let the EA act on volatility squeezes and bursts without forcing a flat book.

Risk is sized off an effective-capital pool. UpdateEffectiveCapital() reads account equity and, if InpCapitalCapAmount > 0, caps it at that input, otherwise uses full equity. CalcLot() converts the ATR-based SL distance into lots via tick_value / tick_size, applying ClampVolume() to the broker's lot step and min/max. With InpRiskPercent = 0.5 the EA targets 0.5% of effective capital at risk per trade, InpDailyLossLimitPercent = 3.0 enforces a 3% realized-loss daily circuit-breaker (scanned from deal history filtered by DEAL_MAGIC), and InpCapitalCapFloor = 50 blocks any entries below that equity floor. The cooldown logic in OnTradeTransaction() watches for three consecutive losing DEAL_ENTRY_OUT events and engages a 4-hour lockout (g_cooldown_until = TimeCurrent() + 4*3600) before resetting the counter. With InpMaxConcurrent = 3 the EA caps the open-position count to 3.

Position management is layered. ManagePositions() runs once per tick before any new entry attempt. At InpBreakEvenR = 1.0 the stop is ratcheted to the open price once price has travelled 1R in profit, enforced through EnforceStopsDistance() which respects the broker's SYMBOL_TRADE_STOPS_LEVEL. At the same 1R trigger, 50% of the position is closed via TryClosePartial_EX18039(), gated so that the remaining volume still exceeds 1.5 * LotsMin. The 2.5*ATR trailing stop (Chandelier style) advances the stop forward only — never backwards — and re-uses EnforceStopsDistance to keep the broker happy. Exits are wired to three events: an opposite HMA turn calls TryClose_EX18039(), a regime shift into CHOPPY with r_dist <= 0 calls the same close helper (so choppy collapses underwater), and a 200-bar time-based exit kicks in if a trade has been open longer than InpMaxBarsInTrade. Each close/modify attempt gets up to three retries with 200ms (close) or 100ms (modify) sleeps on REQUOTE, TIMEOUT, PRICE_OFF, or PRICE_CHANGED retcodes.

Execution safety is non-trivial. SendMarket() calls OrderCalcMargin() before any trade send, refuses if margin_req > free_margin, and runs a 2-attempt retry loop on requote/timeout/price-off/price-changed retcodes. With InpDryRun = true the default, every order is logged via PrintFormat with the [DRYRUN] prefix instead of being sent to the broker, so the EA can be paper-traded end-to-end on a live account. SetTypeFillingBySymbol() auto-detects FOK / IOC / Return per symbol. The spread gate in SpreadOK() rejects entries when the live spread exceeds SYMBOL_SPREAD * 3 + 10 points, and SessionOK() blocks weekends plus the 21:00–07:00 server-time band. There is no news feed wired — the EA is session-, spread-, and regime-gated, not event-gated.

On the test side, OnTester() returns (STAT_PROFIT * STAT_PROFIT_FACTOR) / (1 + STAT_EQUITY_DD), with a 30-trade floor and the equity-DD floored at 1.0 to avoid a divide-by-zero. The function is named explicitly so optimizer passes can be sorted by this composite score rather than raw net profit. In live use, the EA trades HMA slope reversals filtered by H1 trend agreement, with a six-state regime classifier, 1:1.5 R:R, ATR-Chandelier trail, partial take-profit at 1R, and a 200-bar time cap. A user who wants only the highest-conviction trades can raise InpHMAPeriod to 28 or 34 (slower turns) and lift the confidence floor in the source from 30 to 45, which will mechanically cut the trade count and concentrate entries on stronger HMA hooks.

Strategy Deep Dive

On every tick, ClassifyRegime() reads 50 bars of ATR(14), 3 bars of ADX(14), and 30 bars of Bollinger Bands(20, 2.0) width to return one of six states (StrongTrend, WeakTrend, Compress, Expand, Range, Choppy); Choppy is the only state that hard-blocks entries in CanTradeNew(). The signal then comes from HmaSignal() evaluating slope_now = h1 - h2 against slope_prev = h2 - h3 on the last closed bar of an inline-computed HMA(21), requiring slope_prev <= 0 < slope_now for longs (mirror for shorts), with a confidence score of |slope|/price * 1000 * 50 + 25 floored at 30. The HTF confirm is read by HTFTrendDir() from an EMA(50) on H1 (the input InpHTFTrendTF = 8 falls through MapTimeframeInt to PERIOD_H1 by default), and a long HMA turn with a falling H1 trend is rejected. Lot size is computed in CalcLot() against effective capital (full equity or capped at InpCapitalCapAmount), targeting InpRiskPercent = 0.5% per trade. Position management runs in ManagePositions() on every tick: break-even at 1R via EnforceStopsDistance, 50% partial close at 1R, a 2.5*ATR Chandelier trailing stop that only ratchets forward, plus opposite-signal, regime-choppy, and 200-bar time exits. Spread and session gates run in SpreadOK() (avg * 3 + 10 points) and SessionOK() (Mon-Fri 07:00–21:00 server), and OnTradeTransaction() engages a 4-hour cooldown after 3 consecutive DEAL_ENTRY_OUT losses.

Entry Signal

Long entry on a strict HMA(21) slope reversal at the last closed bar: slope_prev = h2 - h3 must be <= 0 and slope_now = h1 - h2 must be > 0 (mirror for shorts). The H1 EMA(50) trend must agree, confidence computed from |slope|/price must be >= 30, and the live spread must stay inside SYMBOL_SPREAD * 3 + 10 points within the 07:00–21:00 server-time window on a weekday.

Exit Signal

Exits stack four events: an opposite HMA turn calls the close helper, a regime shift into CHOPPY with r_dist <= 0 forces a close, a 200-bar time cap triggers TryClose_EX18039, and 50% of the position is taken at 1R via TryClosePartial_EX18039 with the trailing stop ratcheted forward at 2.5*ATR(14) once price is in profit.

Stop Loss

Initial stop is 2.0 * ATR(14) away from entry, with EnforceStopsDistance() widening the SL whenever the broker's SYMBOL_TRADE_STOPS_LEVEL would otherwise be violated. The break-even helper ratchets SL to the open price once price has travelled 1R, and a 2.5*ATR Chandelier trailing stop then advances the stop forward only.

Take Profit

Initial take-profit is 3.0 * ATR(14) from entry, giving a 1:1.5 R:R against the 2.0*ATR stop. Half of the position is also closed at 1R via TryClosePartial_EX18039, so the EA realizes partial profit before the trailing stop takes over the rest of the trade.

Best For

Best suited to XAUUSD on the M5 timeframe with a minimum recommended balance of $100 (the InpCapitalCapFloor = 50 effectively blocks sub-$50 equity, and 0.5% risk per trade scales cleanly above that floor). Use a low-spread ECN broker with a 20-point slippage tolerance, run it during the 07:00–21:00 server window so the H1 EMA(50) trend agreement has stable bars to read, and pair it with the default MEDIUM risk profile — the 1:1.5 R:R plus 2.5*ATR trail expects the underlying to trend, not chop, so the HMA hook will underperform on XAUUSD pairs that are pinned in tight ranges.

Strategy Logic

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

Family: TrendFollow Magic: 22218039 Version: 2.00

BRIEF: HMA slope reversal on last closed bar confirmed by HTF EMA trend + ADX regime + ATR-based SL/TP/trail. Full spec

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • HMA_WMA()
  • CalcHMA()
  • NormPrice()
  • ClampVolume()
  • StopsLevelPoints()
  • EnforceStopsDistance()
  • DailyRealizedPnL()
  • UpdateEffectiveCapital()
  • RegimeName()
  • HmaSignal()
  • HTFTrendDir()
  • SpreadOK()
  • ...and 14 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (18 total across 4 groups):

  • [=== Identity & Exec ===] InpMagic = 22218039 // Magic number (id)
  • [=== Identity & Exec ===] InpDeviation = 20 // Slippage allowed (points)
  • [=== Identity & Exec ===] InpDryRun = true // Dry-run: log only, no sends (bool)
  • [=== Identity & Exec ===] InpKillSwitch = false // Kill switch: blocks new entries (bool)
  • [=== Identity & Exec ===] InpTradeComment = "Psgrowth.com Expert_18039" // Order comment
  • [=== Capital & Risk ===] InpCapitalCapAmount = 0.0 // Cap on real-money equity ($)
  • [=== Capital & Risk ===] InpCapitalCapFloor = 50.0 // Floor: block entries if effective<$ (money)
  • [=== Capital & Risk ===] InpRiskPercent = 0.5 // Risk per trade (% of effective)
  • [=== Capital & Risk ===] InpDailyLossLimitPercent = 3.0 // Daily loss limit (% of effective)
  • [=== Capital & Risk ===] InpMaxConcurrent = 3 // Max concurrent positions (count)
  • [=== Signal - HMA TrendFollow ===] InpHMAPeriod = 21 // Hull MA period (bars)
  • [=== Signal - HMA TrendFollow ===] InpHTFTrendTF = 8 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF trend timeframe (TF)
  • [=== Signal - HMA TrendFollow ===] InpADXMinTrend = 22.0 // Min ADX main for trend regime (adx)
  • [=== Regime & Exits ===] InpATRPeriod = 14 // ATR period (bars)
  • [=== Regime & Exits ===] InpATRSLmult = 2.0 // SL = mult * ATR (mult)
  • [=== Regime & Exits ===] InpATRTPmult = 3.0 // TP = mult * ATR (mult)
  • [=== Regime & Exits ===] InpBreakEvenR = 1.0 // Break-even trigger at R multiple (R)
  • [=== Regime & Exits ===] InpTrailATRmult = 2.5 // ATR trailing multiplier (mult)
Pseudocode
// Pipsgrowth EX18039 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// HMA slope reversal on last closed bar confirmed by HTF EMA trend + ADX regime + ATR-based SL/TP/trail. Full spec

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

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

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
InpMagic22218039Magic number (id)
InpDeviation20Slippage allowed (points)
InpDryRuntrueDry-run: log only, no sends (bool)
InpKillSwitchfalseKill switch: blocks new entries (bool)
InpTradeComment"Psgrowth.com Expert_18039"Order comment
InpCapitalCapAmount0.0Cap on real-money equity ($)
InpCapitalCapFloor50.0Floor: block entries if effective<$ (money)
InpRiskPercent0.5Risk per trade (% of effective)
InpDailyLossLimitPercent3.0Daily loss limit (% of effective)
InpMaxConcurrent3Max concurrent positions (count)
InpHMAPeriod21Hull MA period (bars)
InpHTFTrendTF8Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF trend timeframe (TF)
InpADXMinTrend22.0Min ADX main for trend regime (adx)
InpATRPeriod14ATR period (bars)
InpATRSLmult2.0SL = mult * ATR (mult)
InpATRTPmult3.0TP = mult * ATR (mult)
InpBreakEvenR1.0Break-even trigger at R multiple (R)
InpTrailATRmult2.5ATR trailing multiplier (mult)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18039.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18039 GB10 5.2 — self-contained Hull MA Trend-Follow EA, full spec stack."

#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.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_InpHTFTrendTF = PERIOD_H1;
input group "=== Identity & Exec ==="
input int              InpMagic                 = 22218039;          // Magic number (id)
input int              InpDeviation             = 20;              // Slippage allowed (points)
input bool             InpDryRun                = true;            // Dry-run: log only, no sends (bool)
input bool             InpKillSwitch            = false;           // Kill switch: blocks new entries (bool)
input string           InpTradeComment          = "Psgrowth.com Expert_18039"; // Order comment

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;

Full source code available on download

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

Tags:ex18039trendfollowpipsgrowthfreemt5xauusd

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_EX18039.mq5
File Size32.8 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M5
Currency Pairs
XAUUSD
Min. Deposit$100