P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18017 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX18017 HullSuperTrend_XAUUSD_5M — Hull MA + SuperTrend composite trend-follow, full 12-layer stack.

Overview

EX18017 is a closed-bar trend follower built around two hand-rolled indicators that have to agree on direction before the EA will open a position. The first is a Hull Moving Average at period 55 — a longer setting than the typical 14 or 20, and computed in-line from two LWMA primitives (a WMA at n/2 and a WMA at n) differenced and smoothed again over √n samples. The second is a SuperTrend with a 10-bar ATR and a 3.0 multiplier, also computed in-line by walking backward through 50 bars of high/low/close data, maintaining upper and lower bands (HL2 ± mult × ATR), and flipping trend direction whenever a close crosses the active band. The 3.0 multiplier is wider than the conventional 2.0, so the band resists early whipsaws and the EA stays out of the first bars of a reversal. The 55-period Hull smooths through the same noise. Together they form a slow, deliberate composite that prefers persistence over sensitivity.

The entry vote is three-way. A long requires the Hull to be sloping up (HMA[1] > HMA[2]), the SuperTrend to be in direction +1, and the previous bar's close to sit above the Hull value. A short inverts all three. The signal is read on the closed bar, so a new position opens at the open of the next bar, not mid-tick. If any of the three legs disagrees, the EA returns 0 and does not enter.

A seven-state regime classifier runs in front of the signal. It uses ADX(14), a 50-bar ATR-percentile, and a Bollinger-width expand/contract check. StrongTrend is ADX ≥ 25 with percentile ≥ 60%. WeakTrend is ADX ≥ 20 with percentile ≥ 40%. Range is the catch-all low-conviction state. Breakout fires when Bollinger Bands are expanding and the ATR percentile is ≥ 70%. Compress is percentile ≤ 20%. Expand is expanding with percentile ≥ 50%. Choppy is ADX < 15. The pipeline blocks Choppy and Compress outright — those are the regimes where the wide SuperTrend would lag a real move and the EA would take a stop it shouldn't. Range, Expand, Breakout, StrongTrend, and WeakTrend are all permitted. The classifier recomputes every closed bar.

Confirmation runs after the signal fires. The EA pulls a 50-period EMA from the higher timeframe (default H1) and requires the entry bar's close to sit on the correct side of that line. A long signal with close[1] < H1-EMA(50) is rejected. A short signal with close[1] > H1-EMA(50) is rejected. That single H1 filter is the most important reduction in counter-trend losses on a 5-minute gold chart — it forces the EA to trade with the dominant cycle, not against it. The EA also checks a minimum reward-to-risk ratio of 1.5 using the ATR proxy: if the computed SL would not produce at least 1.5× its distance in TP, the trade is skipped before any sizing happens. The session window is hard-coded 07:00 to 21:00 server time.

Risk and sizing are percentage-based. The default is 0.5% of effective capital per trade. Effective capital is min(InpCapitalCapAmount, account equity) when the cap is enabled, otherwise raw equity, with a $50 floor below which new entries are blocked. Lot is computed from the per-trade risk budget divided by the per-lot risk at the actual SL distance in tick-value terms. If the proposed SL would land inside the broker's stops-level, the EA widens it by 10 points to clear the constraint; the TP widens in proportion. An OrderCalcMargin pre-check refuses the send if the required margin exceeds free margin.

Stop and target are ATR-derived. Initial stop is 3.0 × ATR(10). Target is 1.5 × that distance, so the trade opens at a fixed 1:1.5 reward-to-risk ratio. The 1.5 minimum-RR gate in confirmation is the same number, which means the EA will never open a position whose computed TP would be inside the minimum ratio.

In-trade management has three moving parts. When price moves 1R in favor, the stop is ratcheted to break-even plus a 2-point buffer (the buffer covers the spread and the commission so the BE move is not a guaranteed loss on the way out). After that, a 2.5× ATR trailing stop takes over and walks behind the position. At 1R, 50% of the position is closed — but only if the residual volume would still be at least 1.5× the broker's minimum lot, otherwise the partial is skipped to avoid leaving an un-closeable stub. Two hard exits complete the loop: a time exit at 288 bars (approximately 24 hours on M5), and an opposite-signal exit the moment the composite flips. Both run inside ManageInTrade(), which executes on every tick, not just on bar close.

Pyramid: the PyramidAllowed function exists and enforces two conditions — at most 3 same-side positions, and the existing position must be at least 2.0 × ATR in profit before a scale-in is allowed. The build has no input toggle to turn it on, so it sits in standby. A user who wants scaling would have to edit the source.

Execution and risk rails. The OnTester criterion is (net × profit factor) / (1 + balance drawdown), with a 30-trade minimum. Order sends retry once on requote, timeout, or price-off. Closes and partials run a 3-attempt loop with 200 ms between attempts. Modifications get 3 attempts at 100 ms intervals. Slippage is set to 30 points. The daily loss cap is 3% of effective capital. Max open positions is 5, max new entries per day is 10, and the spread is filtered by a rolling 50-bar average — the cap is the larger of 3× the average or (average + 20) points, so a sudden spread spike blocks one cycle, not the whole day. The EA ships with InpDryRun=true as the default, so it logs what it would have done without sending orders until you flip the switch.

Strategy Deep Dive

On every tick the EA first calls ManageInTrade(), which handles break-even, ATR trailing, partial close, time exit, and opposite-signal exit on each open position. On a new bar, OnTick() runs the once-per-bar pipeline: capital-cap check, daily-loss check, regime classification (ADX + ATR-percentile + Bollinger width → 7 states), signal composite (hand-rolled 55-period Hull slope, hand-rolled 10-bar/3.0×ATR SuperTrend direction, and close-vs-Hull agreement, all on the closed bar), HTF confirmation (H1 EMA(50) close-side agreement), no-trade block (spread, stops-level feasibility, regime, max positions, max daily, terminal/filling), and finally TryEntry() which sizes the lot from 0.5% of effective capital and the actual SL distance, then sends a market order with one retry on requote/timeout/price-off. Indicator stack: 7 handles — iADX(14), iATR(50) regime, iBands(20,2) regime, iMA LWMA at n/2 and at n for the Hull, iATR(10) for SuperTrend, and iMA EMA(50) on the HTF.

Entry Signal

Long entry fires when the hand-rolled 55-period Hull MA slopes up (HMA[1] > HMA[2]), the inlined 10-bar/3.0×ATR SuperTrend direction is +1, and the previous bar's close is above the Hull value — all three must agree on a closed bar. Short entry inverts all three conditions. A long is then rejected if close[1] is below the H1 50-EMA, and a short is rejected if close[1] is above it. The signal is also blocked in Choppy (ADX < 15) and Compress (ATR-percentile ≤ 20%) regimes.

Exit Signal

Three exit paths run inside ManageInTrade() on every tick. The time exit closes any position older than 288 bars (~24h on M5). The opposite-signal exit closes a long the moment the composite flips to sell, and a short the moment it flips to buy. Once price has moved 1R in favor, 50% of the position is closed (only if the residual is at least 1.5× the broker's minimum lot) and the stop is ratcheted to break-even plus a 2-point buffer; from there, a 2.5× ATR trailing stop walks the position until one of the hard exits fires.

Stop Loss

Initial stop is 3.0 × ATR(10), placed at the entry tick and never tightened inside that envelope. If the proposed SL would fall inside the broker's stops-level, the EA widens it by 10 points to clear the constraint. After the trade moves 1R in favor, the stop is moved to break-even (entry + 2 points for buys, entry − 2 points for sells) one-shot, then a 2.5× ATR trailing stop takes over.

Take Profit

Take profit is 1.5 × the initial SL distance, giving a fixed 1:1.5 reward-to-risk ratio at entry. The minimum-RR gate of 1.5 inside the confirmation step prevents the EA from attempting the trade if the volatility regime would force an unfavorable ratio, so the 1:1.5 is a floor, not a cap. The TP is also widened by 10 points in proportion to the SL whenever the SL is forced wider to clear the broker's stops-level.

Best For

Best on XAUUSD M5 with a low-spread gold broker (typical spread ≤ 30 cents, tight stops-level) and an account that has cleared the $50 capital floor. The 07:00–21:00 server window maps to a session that captures the London–New York overlap on a GMT+2 broker, which is exactly the volatility regime this composite is built for. A $100 minimum deposit works for a micro-lot account; the 0.5% risk rule will not size up beyond that, so traders expecting larger positions on a $100 balance will be disappointed. The H1 EMA(50) filter assumes a clean higher-timeframe trend, so the EA underperforms in week-long consolidations where H1 is sideways. Run the backtest with InpDryRun=true first, then flip it off and validate on a cent or micro account before going live.

Strategy Logic

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

Family: TrendFollow Magic: 22218017 Version: 2.00

BRIEF: Hull MA slope + SuperTrend(HT) composite flip. Hull = LWMA(2*WMA(n/2) - WMA(n), sqrt(n)) [inlined from iMA LWMA]. Super = HL2 +/- ATR*mult, flip on close vs band [inlined iATR]

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

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

INTERNAL CONSTANTS (16 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)
  • MAX_POSITIONS = 5 // Max concurrent (hard cap)
  • MAX_PYRAMID_LEVELS = 3 // Max pyramid levels (when enabled)
  • PYRAMID_ATR_SPACING = 2.0 // Min ATR spacing between pyramid adds
  • SPREAD_ROLL_BARS = 50 // Rolling-average spread window
  • MAX_DAILY_TRADES = 10 // Max new entries per day
  • MAX_BARS_IN_TRADE = 288 // Max bars in trade (~24h on M5)
  • SESSION_START_HOUR = 7 // Session start (server time)
  • SESSION_END_HOUR = 21 // Session end (server time)
  • NEWS_WINDOW_MINUTES = 0 // Manual news blackout (0 = disabled)
  • SLIPPAGE_POINTS = 30 // Order deviation in points
  • ...and 1 more

INPUT PARAMETERS (19 total across 5 groups):

  • [=== Identity ===] InpMagicNumber = 22218017 // Magic Number (222xxx)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18017" // 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 MA + SuperTrend) ===] InpHullPeriod = 55 // Hull MA period (n)
  • [=== Signal (Hull MA + SuperTrend) ===] InpSTPeriod = 10 // SuperTrend ATR period
  • [=== Signal (Hull MA + SuperTrend) ===] InpSTMultiplier = 3.0 // SuperTrend ATR multiplier
  • [=== 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 EX18017 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Hull MA slope + SuperTrend(HT) composite flip. Hull = LWMA(2*WMA(n/2) - WMA(n), sqrt(n)) [inlined from iMA LWMA]. Super = HL2 +/- ATR*mult, flip on close vs band [inlined iATR]

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
InpMagicNumber22218017Magic Number (222xxx)
InpTradeComment"Psgrowth.com Expert_18017"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)
InpHullPeriod55Hull MA period (n)
InpSTPeriod10SuperTrend ATR period
InpSTMultiplier3.0SuperTrend ATR multiplier
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_EX18017.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18017 HullSuperTrend_XAUUSD_5M — Hull MA + SuperTrend composite 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       = 22218017;            // Magic Number (222xxx)
input string   InpTradeComment      = "Psgrowth.com Expert_18017";// 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:ex18017trendfollowpipsgrowthfreemt5xauusd

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