P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18054 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX18054 XAUUSD_M5_v3 — Quad Hull-MA stack with Jurik/Choppiness filter, full 12-layer stack.

Overview

Pipsgrowth EX18054 TrendFollow trades gold on the M5 chart by stacking four independent Hull moving averages (periods 55, 89, 144, and 233) and waiting for them to vote in the same direction before it fires an entry. The Hull MA in this EA is calculated inline rather than pulled from iMA — the function HullAt() builds a custom LWMA (linear weighted) backbone, halves it, subtracts the full LWMA, then smooths the result with a square-root-period rolling average. Each of the four Hulls gets compared to its own previous value, producing a slope-color of 0 (rising), 1 (falling), or 2 (flat). The HullSignal() function then tallies bulls vs bears across the four lines and only returns +1 (long) when InpMinVote or more Hulls (default 3) are rising and zero are falling, with the inline Jurik filter direction agreeing. The mirror condition fires shorts.

The inline Jurik filter is the second gate. JurikAt() reconstructs Mark Jurik's smoothing filter from the price series — no external indicator handle is allocated for it. With DEF_JURIK_LENGTH set to 14, the filter smooths the close over a 14-bar phase and returns its current value. The signal module compares the filter's current value to its previous value (shift 1 vs shift 2) and demands that the Jurik slope point in the same direction as the Hull vote. Without the Jurik agreement, a fully-aligned Hull stack is still not enough to enter.

The Choppiness Index acts as the third veto. ChoppinessAt() sums true range over a 14-bar window, divides by the period high-low range, and runs the result through 100 * log10(sumTR/range) / log10(period). When the index climbs above InpChopThreshold (default 61.8), the market is judged too range-bound for trend entries and the signal function returns 0. This protects the strategy from triggering fake breakouts in sideways regimes.

Once a signal survives the triple gate, the EA runs it through the regime classifier in ClassifyRegime(). The classifier reads the previous bar's ATR(14), ATR percentile over the last 100 bars, Bollinger Bands (20, 2.0) width as (upper-lower)/middle, and ADX(14). It returns one of six states: Expand (ATR percentile ≥ 80 with BB width > 0.01), StrongTrend (ADX ≥ InpAdxTrendMin=22), WeakTrend (ADX ≥ 18), Compress (ATR percentile ≤ 20 with BB width < 0.005), Range (ATR percentile ≤ 35), and Choppy (default fallback). Entries are blocked when regime is Choppy or Compress — both are interpreted as 'wait for a clean break' states. The remaining four regimes are all tradeable.

The confirmation layer in ConfirmEntry() adds three final checks. The HTF H1 EMA(50) must agree with the trade direction — the function reads h_htf_ema (the H1 EMA50 handle allocated in OnInit) and demands that the M5 close[1] be above the H1 EMA for longs, below for shorts. The RSI(14) blocks entries against extreme momentum: longs are refused if RSI > 75, shorts if RSI < 25. Finally, the live spread is compared against InpMaxSpreadPts (default 50 points) and trades are denied on wide quotes. All MT5 indicator handles (h_atr, h_adx, h_bands, h_htf_ema, h_rsi) are created in OnInit() and released in OnDeinit().

Risk and trade construction happen in CalcLots() and TryEntry(). The lot size is computed against the effective capital — that is MathMin(InpCapitalCapAmount, equity) if a cap is set, otherwise raw equity, with today's realized PnL folded back in via EffectiveCapitalToday(). The risk budget per trade is InpRiskPercent (default 0.5%) of effective capital. The SL distance is InpAtrSlMult × ATR(14) (default 2.0×), the TP distance is InpAtrTpMult × ATR(14) (default 3.0×) — a hard-coded 1:1.5 reward-to-risk ratio, with a final InpMinRR (default 1.2) gate that refuses entries when the realized R:R falls below threshold after broker stop-level adjustment. m_trade.SetDeviationInPoints(20) allows 20 points of slippage, and OrderCalcMargin pre-checks free margin before the order is sent. A retry loop handles requotes and price-change errors with one refresh of rates.

Position management runs on every tick. ManageOpen() walks every open position with the matching magic and does four things in sequence. First, PositionBEPrice() checks if price has moved 1R in profit (where R is the initial ATR-multiple SL distance) and, if so, ratchets the stop to entry plus the spread point — the standard break-even step. Second, an ATR trailing stop kicks in at InpTrailAtrMult × ATR(14) (default 2.5×) and only moves forward — never backwards. The trailing modifies the SL in TryModify_EX18054(), which retries up to three times with 100ms sleeps on requote or timeout. Third, at 1R in profit DEF_PARTIAL_FRACTION (50%) of the position is closed via TryClosePartial_EX18054() — three retries with 200ms sleeps on transient errors — leaving the remainder to run under the trailing stop. Fourth, after DEF_MAX_BARS_IN_TRADE (120 bars = 10 hours on M5) elapses, the position is force-closed by TryClose_EX18054(). ExitOnReverse() additionally closes any position whose direction contradicts a new opposite-signal vote, with DEF_EXIT_ON_REVERSE defaulted to true.

The no-trade gate in NoTradeAllowed() is the safety layer. It refuses entries when: InpKillSwitch is on, effective capital has fallen below InpCapitalCapFloor (default $50, but only active when InpCapitalCapAmount > 0), CountMyPositions() has reached InpMaxConcurrent (default 3), a cooldown window is active, the daily realized loss has hit 3% of equity, the weekly realized loss has hit 6% of equity (both pulled from RealizedPnLSince() which scans history deals by magic and symbol), the current broker-server time is outside the 08:00-20:00 window configured by InpSessionStart/InpSessionEnd, or the EA is past the Friday 20:00 server cutoff (the IsNearFridayCutoff() guard, which is DEF_AVOID_FRIDAY_CUTOFF=true). The 4-hour cooldown in TrackLossesForCooldown() activates when three consecutive losing deals accumulate during the day, resetting the loss counter on any winning deal.

The InpDryRun flag (default true) makes the EA a paper-trader out of the box — SendMarket(), ModifySLTP(), and the partial-close calls all print their intended actions to the log without actually placing or modifying orders. Set it to false to go live. OnTester() returns (net × profit_factor) / (1 + balance_dd_percent) for any backtest with at least 30 trades, scoring strategies by risk-adjusted return rather than raw profit. The order comment is hard-coded to Psgrowth.com Expert_18054 for downstream journal filtering. Magic 22218054 must remain unique per chart to keep position-counting and the cooldown counter correct.

For live deployment, the recommended minimum balance is $100 — the 0.5% risk per trade keeps the loss-on-stop well under 1% of equity per position. The 08:00-20:00 server-time window captures the London and the first half of the New York session, when gold volatility is highest. The 50-point spread cap and the 60-point hardcoded m_trade.SetDeviationInPoints(20) mean the EA prefers tight-spread execution — a RAW-spread or ECN account is recommended for both XAUUSD and any other instrument the strategy is ported to. The InpMinRR=1.2 floor and the Regime-block rules will turn the EA off during quiet Asian sessions, so don't be surprised by a low trade frequency during low-volatility weeks — the system is designed to wait for clean trend setups rather than to trade every session.

Strategy Deep Dive

Each tick refreshes the symbol, rolls the daily/weekly equity baselines, then calls ClassifyRegime() to score ADX, ATR percentile, and Bollinger width into one of six states. HullSignal() builds four inline Hull MAs (55/89/144/233), compares each to its previous value, and counts aligned slope-color votes. The inline Jurik-14 filter and Choppiness-14 veto can suppress the signal even when the Hull stack aligns. Surviving signals pass through ConfirmEntry() (H1 EMA50, RSI 75/25, spread ≤ 50pt), NoTradeAllowed() (kill switch, capital floor, max 3 concurrent, 4h cooldown, 3% daily / 6% weekly loss, 08:00-20:00 server window, Friday 20:00 cutoff), then TryEntry() sizes via CalcLots() against effective capital at 0.5% risk and sends with OrderCalcMargin pre-check. ManageOpen() runs the break-even, trailing stop, 50% partial at 1R, and 120-bar time-stop in sequence on every tick.

Entry Signal

Long entry fires when at least 3 of the 4 inline Hull MAs (periods 55, 89, 144, 233) are sloping up with no opposing slope, the inline Jurik-14 filter direction agrees, and the Choppiness Index sits below 61.8. The trade is then confirmed by H1 EMA(50) alignment, RSI(14) position gate (75/25 extremes block), and a 50-point spread cap. Short entries are the mirror image, evaluated on closed bar (shift=1) to eliminate repaint risk.

Exit Signal

Exit occurs on opposite Hull-signal vote (DEF_EXIT_ON_REVERSE=true), at 1R break-even (entry + spread point, one-shot), via 2.5×ATR(14) forward-only trailing stop, on 50% partial close at 1R (PT1 mark), and on a 120-bar time stop (10 hours M5). TryClose_EX18054 retries the close up to 3 times with 200ms sleeps on requote or price-changed errors.

Stop Loss

Initial stop is InpAtrSlMult (default 2.0) × ATR(14) distance from the entry price, normalized to the symbol's stop-level minimum. A break-even step moves the stop to entry + spread point once price reaches 1R profit (one-shot, no offset). The 2.5×ATR(14) forward-only trail activates after BE and never moves backwards.

Take Profit

Initial TP is InpAtrTpMult (default 3.0) × ATR(14) from entry — a hard-coded 1:1.5 reward-to-risk against the 2.0×ATR stop. An InpMinRR (default 1.2) gate refuses the order if the realized R:R falls below threshold after broker stop-level adjustment. Half the position is closed at 1R via TryClosePartial_EX18054; the remaining half runs under the trailing stop until exit-on-reverse, time-stop, or 2.5×ATR trail.

Best For

Minimum recommended balance $100 (the 0.5% risk per trade keeps the worst-case loss per position under 1% of equity). Pairs: XAUUSD primary; the inline Hull math ports cleanly to any liquid FX major. The 08:00-20:00 server-time window targets the London and the first half of the New York session, when gold's realized volatility is highest. Best with a RAW-spread or ECN account — the 50-point spread cap and 20-point slippage allowance assume tight execution. InpDryRun defaults to true; set it to false to go live.

Strategy Logic

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

Family: TrendFollow Magic: 22218054 Version: 2.00

BRIEF: Quad inline Hull-MA stack (55/89/144/233) slope-color vote, smoothed via inline Jurik filter direction and Choppiness filter. Entry on bar-close when >=3 of 4 Hull align and no opposing vote, gated by ADX/ATR-percentile/Bollinger-width regime classifier. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • HullLWMA()
  • HullAt()
  • JurikAt()
  • ChoppinessAt()
  • DayStart()
  • WeekStart()
  • NormPrice()
  • NormVol()
  • StopsLevelPts()
  • FreezePts()
  • EffectiveCapitalToday()
  • RealizedPnLSince()
  • ...and 20 more

INTERNAL CONSTANTS (1 total):

  • DEF_TRADE_COMMENT = InpTradeComment // --- Indicator handles

INPUT PARAMETERS (22 total across 6 groups):

  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade, % of effective capital
  • [=== Risk & Sizing ===] InpMaxLotSize = 10.0 // Hard lot cap
  • [=== Risk & Sizing ===] InpDailyLossLimitPct = 3 // Daily loss limit, % of effective capital
  • [=== Risk & Sizing ===] InpMaxConcurrent = 3 // Max concurrent positions (symbol+magic)
  • [=== Risk & Sizing ===] InpKillSwitch = false // Master kill switch
  • [=== Capital Allocation Cap ===] InpCapitalCapAmount = 0.0 // Cap amount in account currency ($)
  • [=== Capital Allocation Cap ===] InpCapitalCapFloor = 50.0 // Floor; block new entries below
  • [=== Signal: Hull Stack ===] InpHull1_Period = 55 // Hull fast period (bars)
  • [=== Signal: Hull Stack ===] InpHull4_Period = 233 // Hull slowest period (bars)
  • [=== Signal: Hull Stack ===] InpMinVote = 3 // Minimum aligned Hull votes (of 4)
  • [=== Signal: Hull Stack ===] InpChopThreshold = 61.8 // Choppiness upper block threshold
  • [=== Regime / Confirm ===] InpAdxTrendMin = 22.0 // ADX min for StrongTrend regime
  • [=== Regime / Confirm ===] InpMaxSpreadPts = 50 // Max spread, points (0=off)
  • [=== Regime / Confirm ===] InpMinRR = 1.2 // Minimum reward:risk ratio
  • [=== ATR SL/TP & Management ===] InpAtrSlMult = 2.0 // SL = ATR x mult
  • [=== ATR SL/TP & Management ===] InpAtrTpMult = 3.0 // TP = ATR x mult
  • [=== ATR SL/TP & Management ===] InpTrailAtrMult = 2.5 // ATR trailing multiplier (0=off)
  • [=== Session / Operation ===] InpSessionStart = "08:00" // Session start (broker server time HH:MM)
  • [=== Session / Operation ===] InpSessionEnd = "20:00" // Session end (broker server time HH:MM)
  • [=== Session / Operation ===] InpMagicNumber = 22218054 // Magic number
  • [=== Session / Operation ===] InpTradeComment = "Psgrowth.com Expert_18054" // Trade comment
  • [=== Session / Operation ===] InpDryRun = true // Dry-run: skip actual order sends
Pseudocode
// Pipsgrowth EX18054 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Quad inline Hull-MA stack (55/89/144/233) slope-color vote, smoothed via inline Jurik filter direction and Choppiness filter. Entry on bar-close when >=3 of 4 Hull align and no opposing vote, gated by ADX/ATR-percentile/Bollinger-width regime classifier. 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
InpRiskPercent0.5Risk per trade, % of effective capital
InpMaxLotSize10.0Hard lot cap
InpDailyLossLimitPct3Daily loss limit, % of effective capital
InpMaxConcurrent3Max concurrent positions (symbol+magic)
InpKillSwitchfalseMaster kill switch
InpCapitalCapAmount0.0Cap amount in account currency ($)
InpCapitalCapFloor50.0Floor; block new entries below
InpHull1_Period55Hull fast period (bars)
InpHull4_Period233Hull slowest period (bars)
InpMinVote3Minimum aligned Hull votes (of 4)
InpChopThreshold61.8Choppiness upper block threshold
InpAdxTrendMin22.0ADX min for StrongTrend regime
InpMaxSpreadPts50Max spread, points (0=off)
InpMinRR1.2Minimum reward:risk ratio
InpAtrSlMult2.0SL = ATR x mult
InpAtrTpMult3.0TP = ATR x mult
InpTrailAtrMult2.5ATR trailing multiplier (0=off)
InpSessionStart"08:00"Session start (broker server time HH:MM)
InpSessionEnd"20:00"Session end (broker server time HH:MM)
InpMagicNumber22218054Magic number
InpTradeComment"Psgrowth.com Expert_18054"Trade comment
InpDryRuntrueDry-run: skip actual order sends
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18054.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18054 XAUUSD_M5_v3 — Quad Hull-MA stack with Jurik/Choppiness filter, 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         m_trade;
CPositionInfo  m_position;
CSymbolInfo    m_symbol;
CAccountInfo   m_account;
COrderInfo     m_order;
CDealInfo      m_deal;

//============================== INPUTS ==============================
input group "=== Risk & Sizing ==="
input double   InpRiskPercent       = 0.5;     // Risk per trade, % of effective capital
input double   InpMaxLotSize        = 10.0;    // Hard lot cap
input int      InpDailyLossLimitPct = 3;       // Daily loss limit, % of effective capital
input int      InpMaxConcurrent      = 3;      // Max concurrent positions (symbol+magic)
input bool     InpKillSwitch         = false;  // Master kill switch

input group "=== Capital Allocation Cap ==="
// InpCapitalCapEnabled removed — use InpCapitalCapAmount=0 to disable    // Enable capital cap (real-money $)
input double   InpCapitalCapAmount  = 0.0;   // Cap amount in account currency ($)
input double   InpCapitalCapFloor   = 50.0;    // Floor; block new entries below

input group "=== Signal: Hull Stack ==="
input int      InpHull1_Period      = 55;      // Hull fast period (bars)
input int      InpHull4_Period      = 233;     // Hull slowest period (bars)
input int      InpMinVote           = 3;       // Minimum aligned Hull votes (of 4)
input double   InpChopThreshold     = 61.8;    // Choppiness upper block threshold

input group "=== Regime / Confirm ==="
input double   InpAdxTrendMin       = 22.0;    // ADX min for StrongTrend regime
input int      InpMaxSpreadPts      = 50;      // Max spread, points (0=off)
input double   InpMinRR             = 1.2;     // Minimum reward:risk ratio

input group "=== ATR SL/TP & Management ==="
input double   InpAtrSlMult         = 2.0;     // SL = ATR x mult
input double   InpAtrTpMult         = 3.0;     // TP = ATR x mult
input double   InpTrailAtrMult      = 2.5;     // ATR trailing multiplier (0=off)

input group "=== Session / Operation ==="
input string   InpSessionStart      = "08:00"; // Session start (broker server time HH:MM)
input string   InpSessionEnd        = "20:00"; // Session end (broker server time HH:MM)
input int      InpMagicNumber       = 22218054;  // Magic number
input string   InpTradeComment      = "Psgrowth.com Expert_18054"; // Trade comment
input bool     InpDryRun            = true;    // Dry-run: skip actual order sends
//============================== INPUTS END ===========================

//--- Hardcoded sensible defaults (not user-tunable to keep inputs <=22)
#define DEF_HULL2_PERIOD        89
#define DEF_HULL3_PERIOD        144

Full source code available on download

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

Tags:ex18054trendfollowpipsgrowthfreemt5xauusd

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