P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18024 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX18024 Adaptive XAUUSD 5M — Hull+RSI+HA adaptive trend follow, full 12-layer stack.

Overview

Pipsgrowth EX18024 is a trend-following EA built around an adaptive HMA + RSI + Heikin-Ashi signal stack, tuned specifically for short-term XAUUSD action on a 5-minute chart. The skeleton is the same 12-layer architecture used across the EX18 family (REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester), but every layer is wired for gold volatility rather than FX majors. A lot of the inputs are hidden behind the seven #define constants at the top of the source (HA_LOOKBACK, MAX_PYRAMID_LEVELS, PYRAMID_ATR_SPACING, MAX_DAILY_TRADES, MAX_BARS_IN_TRADE, SESSION_START_HOUR/END_HOUR) which gives the EA a coherent risk profile without forcing the user to think about them.

The signal layer is the unusual part. Rather than a plain MA crossover, the EA reconstructs a Hull MA(34) inside MQL5 from two iMA LWMA primitives: a half-period LWMA(17) and a full-period LWMA(34). The differenced series 2*WMA_half - WMA_full is then smoothed by a hand-rolled LWMA over sqrt(34) = 5 samples in HullMAAt(). The slope of that HMA is checked between shift=1 and shift=2 on the closed bar, and the close must also sit on the correct side of the HMA. The trend filter is then gated by a 14-period RSI whose OB/OS bands are themselves ATR-adaptive: when ATR-percentile climbs above 0.75 the bands widen by 5 points (RSI_BASE_OB 70 → 75, RSI_BASE_OS 30 → 25) to absorb fakeouts in high-vol bursts, and when ATR-percentile drops below 0.25 the bands tighten by the same amount so entries can fire earlier in quiet regimes. The third gate is an inlined Heikin-Ashi colour test — HAAt() walks 15 bars oldest-to-newest from CopyOpen/High/Low/Close and seeds HA_Open with the OHLC4 average, then iterates (prev_HA_Open + prev_HA_Close)/2. A long entry requires HMA rising, close > HMA, RSI between 50 and the adaptive OB, and the latest HA candle green; shorts mirror.

Regime is a composite of ADX(14), an ATR(50) percentile rank across the lookback, and Bollinger Bands(20, 2.0) width. RegimeClassify() returns seven states: StrongTrend (ADX ≥ 25 and ATR-pctile ≥ 0.6), WeakTrend (ADX ≥ 20 and pctile ≥ 0.4), Range, Breakout (BB expanding with pctile ≥ 0.7), Compress (pctile ≤ 0.20), Expand (BB expanding with pctile ≥ 0.5), and Choppy (ADX < 15 or buffer failure). Compress and Choppy both hard-block entries in SignalComposite() so the EA doesn't fade a sleeping market. The InpADXMin = 20 input feeds both the WeakTrend threshold and the StrongTrend gate (which adds 5 points on top).

Confirmation is a three-pronged test in ConfirmOK(). First, an HTF EMA(50) must agree with the trade direction — long only if close[1] >= emaHTF[0], short only if below. The HTF selection is InpHTFTimeframe = 8 which the MapTimeframeInt() helper maps via the default branch to PERIOD_H1, so out of the box the EA takes its higher-timeframe cue from the H1 trend. Second, the SL/TP distance must be feasible: it pre-checks slDist = 3.0 * ATR(14) and tpDist = slDist * InpMinRR(1.5) = 4.5 * ATR(14), so anything that would push either below the broker stops-level is filtered. Third, the server clock must be inside the 7-21 hour window defined by SESSION_START_HOUR and SESSION_END_HOUR. That keeps the EA trading the London-through-New-York gold session and stepping aside for the Asia lull.

Risk and sizing live in CalcLot() and TryEntry(). With InpRiskPercent = 0.5 the EA risks 0.5% of effective capital per trade, where effective capital is min(InpCapitalCapAmount, accountEquity) whenever the cap input is set non-zero; with the default InpCapitalCapAmount = 0.0 the cap is disabled and effective capital is just account equity. The $50 floor (InpCapitalCapFloor) still acts as a hard block on new entries even when the cap is off — once equity drops under $50 the EA prints a single CAP-BELOW-FLOOR message and stops opening new positions for the session. The actual lot is computed from (riskMoney / tickVal) * (tickSize / slDist), then floor-rounded to the symbol's lot step and clamped to LotsMin/LotsMax. OrderCalcMargin() is called before the send so a margin shortfall short-circuits the order without burning a request to the broker. Daily loss is a real-money check too: TodayRealizedPnL() walks the deal history from DayStamp(TimeCurrent()) to TimeCurrent() and adds profit + swap + commission only for deals with our magic, and once the absolute value reaches 3% of effective capital the entry pipeline is gated for the rest of the day.

Exits are stacked. The most aggressive is opposite-signal: ManageInTrade() calls SignalComposite(RegimeClassify()) every tick and closes the position if the signal flips. The most patient is time: MAX_BARS_IN_TRADE = 288 means a position is force-closed after ~24 hours on the M5 chart even if everything else is quiet. In between sits a 50% partial close at the 1R mark, a break-even move to open ± 2 points at 1R, and a forward-only ATR trail at 2.5 * ATR(14) that only ever tightens above (for longs) the entry price. SL is sent to the broker at 3x ATR(14) and TP at 4.5x ATR(14) for a fixed 1:1.5 R:R, but the in-trade logic actually runs the show — by the time the broker-side SL would be hit, the EA has usually either trailed past it or already closed on an opposite signal.

Scaling is the part most EX18s leave off. PyramidAllowed() permits up to MAX_PYRAMID_LEVELS = 3 positions on the same side, but only when each existing same-side position is already in profit by at least PYRAMID_ATR_SPACING = 1.5 * ATR(14) from its open. This makes pyramids a 'ride the winner' feature rather than a martingale: a 1.5-ATR move on gold at typical M5 ranges is several hours of trend, so the second and third adds only fire on genuine continuation. The MAX_POSITIONS = 5 global ceiling still caps total exposure, and MAX_DAILY_TRADES = 10 keeps one bad session from turning into a hundred-order blow-up.

The OnTester formula is the family standard — (netProfit * profitFactor) / (1 + balanceDrawdownPct), with a 30-trade floor. That criterion is what PipsGrowth's optimizer maximizes, so when back-testing this EA the genetic pass will tend to prefer parameter sets that combine high net return with low drawdown rather than raw profit. On a slow broker, expect 1-2 trades per session on quiet days and 4-6 on volatile ones; the MAX_DAILY_TRADES = 10 ceiling is almost never the binding constraint for gold M5.

Strategy Deep Dive

Each tick, OnTick first checks the kill switch and refreshes rates, then runs ManageInTrade over every open position (opposite-signal, partial, BE, ATR trail, time exit). On a fresh bar, it calls RegimeClassify() for a 0-6 state, then SignalComposite() which reconstructs the HMA(34) from two LWMAs and applies the close-side test, the adaptive RSI band test (whose OB/OS shift by ±5 points based on a 50-bar ATR percentile rank), and the inlined Heikin-Ashi color test. A non-zero signal must then pass ConfirmOK() (HTF EMA(50) agreement, 1:1.5 R:R feasibility, server 7-21 session) and NoTradeBlock() (rolling-spread cap, stops-level feasibility, MAX_POSITIONS=5, MAX_PYRAMID_LEVELS=3 same-side, terminal trade permission, filling mode). Surviving signals reach TryEntry() where CalcLot sizes the position from 0.5% risk, OrderCalcMargin verifies free margin, PyramidAllowed checks that any existing same-side position is already 1.5x ATR(14) in profit, and the broker send fires with 30-point slippage plus a one-time retry on requote/timeout/price-off.

Entry Signal

Buys fire when the reconstructed HMA(34) slopes up on the closed bar and the close sits above it, the 14-period RSI sits between 50 and an ATR-adaptive overbought ceiling (70 widening to 75 in high-vol regimes, tightening to 65 in low-vol), and an inlined Heikin-Ashi walk of 15 bars shows a green candle. Shorts are the mirror image. Entries are additionally gated by RegimeClassify() (no Choppy or Compress), ConfirmOK() requiring the H1 EMA(50) directional agreement plus a 1.5:1 R:R feasibility check, and the 7-21 server-time window. Pyramids up to 3 levels on the same side are allowed only after each existing position has moved 1.5x ATR(14) in profit from its open.

Exit Signal

Exits run on a stack: opposite-signal close (SignalComposite flips on the live tick), 50% partial close at the 1R mark, break-even move to entry ± 2 points at 1R, forward-only ATR(14)*2.5 trail that ratchets above entry, and a hard time exit at 288 M5 bars (~24h). When a partial fires, the in-trade ManageInTrade loop still owns the residual, so the broker-side TP at 4.5x ATR(14) is effectively a backstop for the few cases the live logic misses.

Stop Loss

Initial stop is 3.0x ATR(14) submitted to the broker, then handed off to in-trade management: at the 1R mark the stop is ratcheted to entry ± 2 points, and a forward-only trail of 2.5x ATR(14) tightens from there. Effective risk per trade is also capped at 0.5% of effective capital via CalcLot, and the InpCapitalCapFloor = 50 blocks any new entries once account equity drops under $50.

Take Profit

TP is sent at 4.5x ATR(14) for a fixed 1:1.5 R:R, but the live ManageInTrade loop normally closes the position via opposite-signal, 50% partial at 1R, or time exit long before the broker TP would be hit. There is no separate basket TP — the trade exits are per-position only.

Best For

Minimum recommended balance: $100 (or the broker's minimum lot-size threshold above whatever the InpCapitalCapFloor=$50 hard floor demands). Best deployed on XAUUSD M5 with a low-spread ECN broker — the rolling-spread cap is the binding constraint on quiet weekends, and gold's typical M5 spread will keep it from firing. The hardcoded 7-21 server-time window makes it a London-and-New-York session EA rather than a 24/7 system, so don't expect activity during the Asian session. The OnTester formula (net*pf)/(1+dd) with a 30-trade floor means you should optimize over a long enough window (12+ months) to populate that floor and let the regime classifier see multiple expansion/compression cycles.

Strategy Logic

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

Family: TrendFollow Magic: 22218024 Version: 2.00

BRIEF: Adaptive Hull MA slope + ATR-adaptive RSI + Heikin-Ashi color trend-follow. HMA inlined from iMA LWMA; HA inlined from CopyOHLC. Buy: HMA up AND close>HMA AND 50<RSI<adaptOB AND HA green. Sell: mirror. Regime gate (ADX+ATR-pctile+BB-width), HTF confirm, capital-allocation-cap, BE+ATR-trail+partial+opp-exit+ time-exit exits, profit-gated pyramid scaling, full exec layer, OnTester custom criterion. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • DayStamp()
  • EffectiveCapital()
  • TodayRealizedPnL()
  • NormalizePrice()
  • StopsLevelPrice()
  • ClampVolume()
  • CountOurs()
  • CountOursByType()
  • CloseAllOurs()
  • CopyBufSafe()
  • RegimeClassify()
  • HullMAAt()
  • ...and 15 more

INTERNAL CONSTANTS (22 total):

  • ATR_REGIME_PERIOD = 50 // ATR percentile lookback (regime)
  • BB_REGIME_PERIOD = 20 // Bollinger width period (regime)
  • BB_REGIME_DEV = 2.0 // Bollinger width deviation (regime)
  • ADX_REGIME_PERIOD = 14 // ADX period (regime)
  • HTF_EMA_PERIOD = 50 // HTF EMA period (confirm)
  • ATR_SIGNAL_PERIOD = 14 // ATR period for SL/TP/trail
  • ATR_VOL_LOOKBACK = 50 // ATR lookback for adaptive RSI
  • HIGH_VOL_PCTILE = 0.75 // ATR percentile above which RSI bands widen
  • LOW_VOL_PCTILE = 0.25 // ATR percentile below which RSI bands tighten
  • RSI_BASE_OB = 70.0 // RSI base overbought level
  • RSI_BASE_OS = 30.0 // RSI base oversold level
  • RSI_NEUTRAL = 50.0 // RSI neutral mid
  • HA_LOOKBACK = 15 // Bars for inlined Heikin-Ashi walk
  • MAX_POSITIONS = 5 // Max concurrent (hard cap)
  • MAX_PYRAMID_LEVELS = 3 // Max pyramid levels (when enabled)
  • ...and 7 more

INPUT PARAMETERS (19 total across 5 groups):

  • [=== Identity ===] InpMagicNumber = 22218024 // Magic Number (222xxx)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18024" // Trade comment
  • [=== Identity ===] InpDryRun = true // Dry-run (no live sends)
  • [=== Identity ===] InpKillSwitch = false // Kill switch (block everything)
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk % per trade (of effective_capital)
  • [=== Risk & Sizing ===] InpFixedLot = 0.01 // Fixed lot fallback (risk=0)
  • [=== Risk & Sizing ===] InpDailyLossLimitPct = 3.0 // Daily loss limit % (of effective_capital)
  • [=== Risk & Sizing ===] InpCapitalCapAmount = 0.0 // Capital cap amount ($ REAL MONEY equity)
  • [=== Risk & Sizing ===] InpCapitalCapFloor = 50.0 // Capital floor ($ — block new entries below)
  • [=== Signal (Hull + Adaptive RSI) ===] InpHullPeriod = 34 // Hull MA period (n)
  • [=== Signal (Hull + Adaptive RSI) ===] InpRSIPeriod = 14 // RSI period
  • [=== Signal (Hull + Adaptive RSI) ===] InpAdaptiveStrength = 5.0 // Max RSI band adjustment (points, ATR-adaptive)
  • [=== Regime & Confirmation ===] InpADXMin = 20.0 // Min ADX for StrongTrend gating
  • [=== Regime & Confirmation ===] InpHTFTimeframe = 8 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF trend agreement TF
  • [=== Regime & Confirmation ===] InpMinRR = 1.5 // Minimum reward:risk ratio
  • [=== Exit / In-Trade Management ===] InpATRSLmult = 3.0 // Initial SL = mult * ATR
  • [=== Exit / In-Trade Management ===] InpBETriggerR = 1.0 // Break-even trigger (R multiples)
  • [=== Exit / In-Trade Management ===] InpTrailATRmult = 2.5 // ATR trailing distance (mult)
  • [=== Exit / In-Trade Management ===] InpPartialPct = 50.0 // Partial close % at TP1 (1R)
Pseudocode
// Pipsgrowth EX18024 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Adaptive Hull MA slope + ATR-adaptive RSI + Heikin-Ashi color trend-follow. HMA inlined from iMA LWMA; HA inlined from CopyOHLC. Buy: HMA up AND close>HMA AND 50<RSI<adaptOB AND HA green. Sell: mirror. Regime gate (ADX+ATR-pctile+BB-width), HTF confirm, capital-allocation-cap, BE+ATR-trail+partial+opp-exit+ time-exit exits, profit-gated pyramid scaling, full exec layer, OnTester custom criterion. 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

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
InpMagicNumber22218024Magic Number (222xxx)
InpTradeComment"Psgrowth.com Expert_18024"Trade comment
InpDryRuntrueDry-run (no live sends)
InpKillSwitchfalseKill switch (block everything)
InpRiskPercent0.5Risk % per trade (of effective_capital)
InpFixedLot0.01Fixed lot fallback (risk=0)
InpDailyLossLimitPct3.0Daily loss limit % (of effective_capital)
InpCapitalCapAmount0.0Capital cap amount ($ REAL MONEY equity)
InpCapitalCapFloor50.0Capital floor ($ — block new entries below)
InpHullPeriod34Hull MA period (n)
InpRSIPeriod14RSI period
InpAdaptiveStrength5.0Max RSI band adjustment (points, ATR-adaptive)
InpADXMin20.0Min ADX for StrongTrend gating
InpHTFTimeframe8Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF trend agreement TF
InpMinRR1.5Minimum reward:risk ratio
InpATRSLmult3.0Initial SL = mult * ATR
InpBETriggerR1.0Break-even trigger (R multiples)
InpTrailATRmult2.5ATR trailing distance (mult)
InpPartialPct50.0Partial close % at TP1 (1R)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18024.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18024 Adaptive XAUUSD 5M — Hull+RSI+HA adaptive trend follow, 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  position;
CSymbolInfo    sym;
CAccountInfo   acc;

//============================== 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_InpHTFTimeframe = PERIOD_H1;
input group "=== Identity ==="
input long     InpMagicNumber       = 22218024;             // Magic Number (222xxx)
input string   InpTradeComment      = "Psgrowth.com Expert_18024"; // Trade comment
input bool     InpDryRun            = true;                // Dry-run (no live sends)
input bool     InpKillSwitch        = false;               // Kill switch (block everything)

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

Full source code available on download

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

Tags:ex18024trendfollowpipsgrowthfreemt5xauusd

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