P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18029 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX18029 EX20 XAUUSD 5M — HA+SuperTrend+Hull consensus trend follow, full 12-layer stack.

Overview

Pipsgrowth EX18029 is a multi-layer trend-following EA for XAUUSD on the M30 working timeframe (its InpTimeframe input defaults to 4, which the embedded MapTimeframeInt() switch maps to PERIOD_M30). It does not rely on the M5 entries that several sibling TrendFollow variants use, so its decisions are made on closed 30-minute candles, with the H1 chart acting as the higher-timeframe confirmation channel through a 50-period EMA. The source opens with a description of the 12-layer architecture: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester. Magic number 22218029 is hard-coded, and the trade comment string is fixed to Psgrowth.com Expert_18029.

The signal layer is built from four fully inlined primitives, none of which are pulled from MetaTrader's standard indicator set. The first primitive is a hand-rolled Heikin-Ashi color function (HeikinAshiColor) that walks four bars from oldest to newest, recomputing haC = (O+H+L+C)/4 and haO = (prev_haO + prev_haC)/2, and returns +1 when the latest closed bar's haC > haO and -1 when it is below. The second is an inline SuperTrend (SuperTrendSide) over InpStAtrPeriod = 22 bars of ATR with InpStMultiplier = 3.0, computing upper and lower bands, flipping the trend state when Close crosses them, and returning +1 for an uptrend or -1 for a downtrend. The third is a reconstructed Hull Moving Average slope (HullSlope) operating on InpHullPeriod = 20 — it builds WMA_full(period) and WMA_half(period/2) from price, takes 2*WMA_half - WMA_full to form the HMA series, smooths the result with a WMA(sqrt(period)) of period 5, and returns +1/-1 depending on whether the latest HMA value is above or below its previous reading. The fourth vote is a simple EMA-trend agreement: close[1] above or below the entry-timeframe EMA(InpEmaPeriod = 50). The four binary votes are summed, and a trade is allowed only when three or more align.

A higher-timeframe confirmation step is layered on top of the 3-of-4 consensus. The EA maintains a separate iMA handle for the H1 50-period EMA (h_emaH) and demands that the H1 close at shift=1 sit on the correct side of that EMA before either a long or a short can fire. The vote counters and confirmation flags are exposed in the log line that the order-placement routine prints, so the operator can audit every decision: BUY ha=1 st=1 hull=1 ema=1 htf=1 reg=4 votes=4. The same string format applies to short entries, and the integer value at the end of the log line is the regime enum.

Regime classification is performed in ClassifyRegime() and works on the most recent closed bar's ATR, ADX, Bollinger Band width, and a 50-bar ATR percentile (computed inside ATRPercentile by counting how many of the last 50 ATR samples are greater than the current value). The output is one of seven states: R_STRONG_TREND when ADX >= 27 and ATR > 1.10 * ATR_percentile, R_WEAK_TREND when ADX >= InpAdxMinTrend = 20, R_EXPAND when ATR > 1.30 * ATR_percentile, R_BREAKOUT when Bollinger width exceeds 1.10 * ATR_percentile, R_RANGE otherwise, R_COMPRESS when ADX < 15 and Bollinger width is below 0.6 * ATR_percentile, and R_CHOPPY when ADX < 15 and the width is not in the compress band. Entries are only allowed in the four trend-or-expansion regimes — R_STRONG_TREND, R_WEAK_TREND, R_BREAKOUT, and R_EXPAND. The other three regimes are not only filtered out at entry but actively force-closed: when the regime is R_CHOPPY or R_COMPRESS, CloseSide() runs in both directions with the reason REGIME_LEAVE.

Risk control revolves around a capital cap. On every tick the EA recomputes g_effective_capital as MathMin(InpCapitalCapAmount, equity) when the cap is positive and otherwise uses raw equity. With InpCapitalCapAmount = 0.0 the cap is effectively off, but InpCapitalCapFloor = 50.0 still blocks trading if equity drops below $50. Per-trade risk is InpRiskPercent = 0.5% of the effective capital, and CalcLot() derives the lot size from the SL distance in price, the tick value, and the tick size. A daily realized P&L check is enforced by RealizedPnLToday(), which sums the profit, swap, and commission of every deal in the current server-day history with the matching magic and symbol; if that figure falls to or below -3.0% of the effective capital, no new entries fire until the next server day. InpCooldownAfterLosses = 3 puts a per-EA cooldown gate in g_cooldown_until after a streak of three losing trades, and InpMaxConcurrent = 5 limits the open-position count per direction. A spread filter (SpreadOK) compares the current spread in points against 4 * (ATR(14)/4 in points), with a 30-point floor, and refuses entries when the spread is wider than four times the recent ATR-implied baseline.

Stop-loss and take-profit are distance-based and built from the same ATR(14) reading at the moment of entry. InpAtrSlMult = 1.5 and InpAtrTpMult = 2.5 give an asymmetric 1:1.67 R:R — wider targets than the 1:1.5 or 1:1.5 variants used elsewhere in the family. The minimum stop distance is enforced against the broker's SYMBOL_TRADE_STOPS_LEVEL and SYMBOL_FREEZE_LEVEL, whichever is larger, so positions never open closer to price than the exchange permits. Once a position is open, ManagePositions() runs on every tick: when the trade reaches 1R of profit, the stop is moved to open ± StopsLevelPts() to break even; afterwards the stop is ratcheted forward at InpAtrTrailMult = 2.5 of ATR, but only when the new stop is on the profitable side of the entry price. The EA does not implement a partial close — the only header-bullet feature it does not wire up is the partial TP — so exits happen either at the initial TP, at the ATR trailing stop, at the break-even ratchet, on an opposite-side vote, or on a regime change to CHOPPY or COMPRESS.

The order-sending routine is wrapped to cope with requotes and price changes. PlaceOrder() checks the margin requirement through OrderCalcMargin() before sending and refuses to send if the lot is too large for the free margin. The trade object is configured with SetDeviationInPoints(30) so the broker is allowed up to 30 points of slippage. On TRADE_RETCODE_REQUOTE, TRADE_RETCODE_TIMEOUT, or TRADE_RETCODE_PRICE_OFF, the routine refreshes the symbol rates and re-sends the order once before giving up. Position-level helpers TryClose_EX18029, TryClosePartial_EX18029, and TryModify_EX18029 each loop up to three attempts, sleeping 200 ms for closes and 100 ms for modifications between attempts, so transient requotes do not abort a critical break-even or trail modification.

The OnTester pass/fail formula is (netProfit * profitFactor) / (1 + maxRelativeDrawdown) with a hard floor of 30 trades — fewer than 30 trades returns zero, so the optimizer refuses to credit a back-test whose sample size is too small. The InpDryRun input is set to true by default, which makes the EA print DRYRUN log lines instead of submitting real orders; the user must explicitly turn this off before live use. InpKillSwitch is an additional safety valve: when set to true it short-circuits CanTrade() with the reason KILL_SWITCH and no orders are placed until the input is reset. Together with the regime-forced exits, the daily loss limit, the loss-streak cooldown, and the ATR-based stops, the EA is designed to fail safely before it fails expensively — a useful property for a multi-indicator trend system on a fast instrument like gold.

Strategy Deep Dive

On every tick the EA refreshes the capital cap and runs ManagePositions() to ratchet stops. On a new closed bar (one-shot guard via g_last_entry_bar), it copies 100 bars of OHLC plus the ATR buffer, classifies the regime from ADX(14), ATR-percentile(50), and Bollinger width, and reads the four signal votes from inline Heikin-Ashi color, an inline SuperTrend(22, 3.0), an inline Hull MA(20) slope, and the close-vs-EMA(50) agreement. A 3-of-4 majority combined with H1 EMA(50) confirmation is required to fire, and only the four trend-or-expansion regimes gate entries; CHOPPY and COMPRESS force-close all open positions with reason REGIME_LEAVE. Order submission goes through CalcLot() for 0.5%-of-equity sizing, MarginOK() for margin validation, and PlaceOrder() with a 30-point slippage budget and one retry on requote/timeout/price-changed. Modify/close helpers loop three attempts with 200/100 ms sleeps between them. The OnTester fitness function (net * pf) / (1 + maxDD) enforces a 30-trade floor before scoring a back-test pass.

Entry Signal

Long entries require at least three of four inline signal votes to align: Heikin-Ashi color positive (haC > haO on the most recent closed bar), SuperTrend side positive (inlined ATR-period 22, multiplier 3.0), Hull MA slope positive (period 20, smoothed with WMA(sqrt(20))), and entry-timeframe close above the 50-period EMA. A separate H1 confirmation (H1 close above the H1 EMA(50)) must agree with the side. The regime classifier must return STRONG_TREND, WEAK_TREND, BREAKOUT, or EXPAND; CHOPPY, COMPRESS, and RANGE block entries. Short entries are the mirror image.

Exit Signal

Positions exit in one of four ways: a 3-of-4 vote flips to the opposite side (e.g. SELL closes BUYs with reason OPPOSITE_BUY); the regime classifier transitions into R_CHOPPY or R_COMPRESS, which triggers CloseSide() in both directions with the reason REGIME_LEAVE; the initial TP is hit at 2.5×ATR(14); or the ATR trailing stop at 2.5×ATR(14) is touched after a 1R break-even ratchet to entry ± broker stops level. The 1R break-even is a one-shot move on the first bar the trade prints with MathAbs(price - open) >= 1R.

Stop Loss

Stop-loss is set on order placement at 1.5× the ATR(14) reading of the most recent closed bar, then floored against SYMBOL_TRADE_STOPS_LEVEL and SYMBOL_FREEZE_LEVEL so the SL is never placed inside the broker's minimum stop zone. Once the trade prints 1R of profit, the stop is ratcheted to open ± StopsLevelPts() (one-shot), and subsequently trailed forward at 2.5×ATR(14) only when the new stop is on the profitable side of the entry price.

Take Profit

Take-profit is set on order placement at 2.5× the ATR(14) reading of the most recent closed bar — 1.67× the SL distance, producing a fixed 1:1.67 R:R at entry. The TP is delivered as a single broker-side take-profit order (not split into multiple targets) and is also floored against the broker's minimum stop distance.

Best For

Designed for XAUUSD M30 with a 0.5%-per-trade risk budget and a $50 effective-capital floor (recommended account size from the configured parameters: $100 minimum). Best run on a low-spread ECN or raw-spread account with sub-30-point typical gold spread, since the spread filter compares current spread against 4 × (ATR(14)/4 in points) with a 30-point floor. The 7-21 server-time session and 30-minute decision cadence suit swing desks and end-of-day gold setups more than M1/M5 scalping — operator who wants a multi-vote trend system that does not martingale and re-evaluates only once per closed bar.

Strategy Logic

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

Family: TrendFollow Magic: 22218029 Version: 2.00

BRIEF: Inline Heikin-Ashi color + SuperTrend side + Hull-MA slope consensus + EMA trend + ADX/ATR-pct/BB-width regime gate. Full risk/capital-cap/exits wired: ATR SL/TP, ATR trailing, break- even, partial TP, daily-loss limit, cooldown, kill-switch. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • CBuf()
  • CopyOHLC()
  • Norm()
  • StopsLevelPts()
  • ClampVolume()
  • BarTime()
  • ATRPercentile()
  • HeikinAshiColor()
  • SuperTrendSide()
  • WMA_series()
  • WMA_diff_series()
  • HullSlope()
  • ...and 14 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (22 total across 6 groups):

  • [=== Identity ===] InpTimeframe = 4 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Working timeframe
  • [=== Identity ===] InpMagic = 22218029 // Magic number
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18029" // Trade comment
  • [=== Signal (EMA / HA / SuperTrend / Hull) ===] InpEmaPeriod = 50 // Trend EMA period (entry TF)
  • [=== Signal (EMA / HA / SuperTrend / Hull) ===] InpHtfEmaPeriod = 50 // HTF trend EMA period (H1)
  • [=== Signal (EMA / HA / SuperTrend / Hull) ===] InpStAtrPeriod = 22 // SuperTrend ATR period
  • [=== Signal (EMA / HA / SuperTrend / Hull) ===] InpStMultiplier = 3.0 // SuperTrend ATR multiplier
  • [=== Signal (EMA / HA / SuperTrend / Hull) ===] InpHullPeriod = 20 // Hull MA period
  • [=== Regime (ADX/ATR-pct/BB-width) ===] InpAdxPeriod = 14 // ADX period
  • [=== Regime (ADX/ATR-pct/BB-width) ===] InpAdxMinTrend = 20.0 // ADX min for trend regimes
  • [=== Regime (ADX/ATR-pct/BB-width) ===] InpAtrPctLookback = 50 // ATR percentile lookback
  • [=== Risk & Sizing (Capital Cap mandatory) ===] InpCapitalCapAmount = 0.0 // Capital cap (real money $)
  • [=== Risk & Sizing (Capital Cap mandatory) ===] InpCapitalCapFloor = 50.0 // Min effective capital floor
  • [=== Risk & Sizing (Capital Cap mandatory) ===] InpRiskPercent = 0.5 // Risk per trade (% effective cap)
  • [=== Risk & Sizing (Capital Cap mandatory) ===] InpDailyLossLimitPercent = 3.0 // Daily loss limit (% effective cap)
  • [=== Risk & Sizing (Capital Cap mandatory) ===] InpMaxConcurrent = 5 // Max concurrent positions
  • [=== Risk & Sizing (Capital Cap mandatory) ===] InpCooldownAfterLosses = 3 // Cooldown after N consecutive losses (bars)
  • [=== Trade Management ===] InpAtrSlMult = 1.5 // ATR SL multiplier
  • [=== Trade Management ===] InpAtrTpMult = 2.5 // ATR TP multiplier
  • [=== Trade Management ===] InpAtrTrailMult = 2.5 // ATR trailing multiplier
  • [=== Control ===] InpDryRun = true // Dry-run mode (no real orders)
  • [=== Control ===] InpKillSwitch = false // Emergency kill switch
Pseudocode
// Pipsgrowth EX18029 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Inline Heikin-Ashi color + SuperTrend side + Hull-MA slope consensus + EMA trend + ADX/ATR-pct/BB-width regime gate. Full risk/capital-cap/exits wired: ATR SL/TP, ATR trailing, break- even, partial TP, daily-loss limit, cooldown, kill-switch. 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
InpTimeframe4Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Working timeframe
InpMagic22218029Magic number
InpTradeComment"Psgrowth.com Expert_18029"Trade comment
InpEmaPeriod50Trend EMA period (entry TF)
InpHtfEmaPeriod50HTF trend EMA period (H1)
InpStAtrPeriod22SuperTrend ATR period
InpStMultiplier3.0SuperTrend ATR multiplier
InpHullPeriod20Hull MA period
InpAdxPeriod14ADX period
InpAdxMinTrend20.0ADX min for trend regimes
InpAtrPctLookback50ATR percentile lookback
InpCapitalCapAmount0.0Capital cap (real money $)
InpCapitalCapFloor50.0Min effective capital floor
InpRiskPercent0.5Risk per trade (% effective cap)
InpDailyLossLimitPercent3.0Daily loss limit (% effective cap)
InpMaxConcurrent5Max concurrent positions
InpCooldownAfterLosses3Cooldown after N consecutive losses (bars)
InpAtrSlMult1.5ATR SL multiplier
InpAtrTpMult2.5ATR TP multiplier
InpAtrTrailMult2.5ATR trailing multiplier
InpDryRuntrueDry-run mode (no real orders)
InpKillSwitchfalseEmergency kill switch
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18029.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18029 EX20 XAUUSD 5M — HA+SuperTrend+Hull consensus 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>

//================= INPUTS (22 total, grouped) =======================
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_InpTimeframe = PERIOD_H1;
input group "=== Identity ==="
input int InpTimeframe = 4; // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1)  // Working timeframe
input long   InpMagic                    = 22218029;   // Magic number
input string InpTradeComment             = "Psgrowth.com Expert_18029"; // Trade 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:ex18029trendfollowpipsgrowthfreemt5xauusd

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