P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18004 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX18004 ADXTrend_XAUUSD_5M — ADX/DI trend-following EA, full 12-layer stack.

Overview

Pipsgrowth EX18004 TrendFollow hunts directional moves on XAUUSD M5 by combining the ADX/DI cross on the last closed bar with a 7-state market regime classifier that filters out environments where the cross is most likely to fail. The EA is built to be patient. A new setup only triggers on bar close, and only after the regime layer confirms the market is tradable — so on a quiet Asian session with ADX under 15 and a flat ATR percentile, the bot simply logs the state and waits.

The signal engine is the standard ADX(14) module with three buffers: ADX main, +DI, and −DI. The InpADXThreshold input (default 25) is the floor; if ADX is below it, the cross is ignored regardless of how clean the DI line looks. With InpRequireDICross = true, the EA only fires when the DI lines actually cross on bar close, not on a persistent +DI>−DI gap. A long fires when +DI crosses above −DI and ADX≥25, with a signal confidence of 70. A short fires on the mirror image. If the cross requirement is disabled, any +DI>−DI majority with ADX above threshold logs a 55-confidence bias instead.

Before a position opens, ClassifyRegime() reads ADX, ATR(14) percentile over a 100-bar lookback, and Bollinger Band(20, 2.0) width, then assigns one of seven states: REG_STRONG_TREND, REG_WEAK_TREND, REG_RANGE, REG_COMPRESS, REG_BREAKOUT, REG_CHOPPY, or REG_NONE. Two of those states are hard-blocked: REG_CHOPPY (ADX under 15) and REG_COMPRESS (ATR below the 40th percentile and BB width under 50 points). The remaining four pass to the next stage, each with a confidence output — STRONG_TREND at 80, BREAKOUT at 85, WEAK_TREND at 55, RANGE at 40. The CHOPPY and COMPRESS cases are logged with the regime code and confidence score, but no order is submitted.

ConfirmEntry() then runs three additional checks. The HTF ADX (default PERIOD_H1) must agree: if the H1 ADX is above InpADXThreshold-5 and the H1 DI lines oppose the trade direction, the entry is rejected with the reason HTF против. A 14-period RSI midpoint filter rejects longs below 50 and shorts above 50. Finally, spread must be under InpMaxSpreadPts (300 points = 30 pips for XAUUSD) and the implied R:R (TP-mult / SL-mult = 4.0/2.0 = 2.0) must clear 1.0.

The SL is computed from ATR(14) × InpATRSLmult (default 2.0×), then run through EnforceStopsLevel() to push the distance above the broker's minimum stop distance plus a 5-point buffer. The TP is the SL distance × (InpATRTPmult / InpATRSLmult) = 2× SL by default, so the design ratio is 1:2 R:R. Lot sizing is risk-based: CalcLot() divides g_effectiveCapital × InpRiskPercent% (default 0.5% of equity, or capped at InpCapAmount if set) by the per-lot risk at the calculated SL. If risk is 0, it falls back to InpFixedLot (0.01). Volumes pass through NormalizeVolume() which floors to the lot step and clamps to the symbol's min/max.

Position management runs every tick through ManageExits(). The first check is an opposite-signal exit: if the regime and DI cross produce a long signal while only sells are open, the sell side is closed via CloseSide(POSITION_TYPE_SELL, "opp-signal"). The second is a regime-change exit: if ClassifyRegime() returns CHOPPY on any tick, all open positions for this magic are closed with the reason choppy. The third is a time stop: positions older than MAX_BARS_IN_TRADE (200 bars = roughly 16.7 hours on M5) are force-closed with the time-stop reason.

The trailing and break-even logic both run on the same per-position loop. When unrealized profit reaches 1R (defined as ATR × InpATRSLmult), the stop is ratcheted to open + 0.05×ATR for longs or open − 0.05×ATR for shorts — a tight break-even that removes the loss case but still gives the trade room to breathe. The trail is set to ATR × 2.5 from the current bid/ask, and the EA only ever moves the stop in the favorable direction (MathMax for longs, MathMin for shorts, with a 0-SL safety branch). Each modify call is wrapped in TryModify_EX18004() which retries up to 3 times on requote/timeout with 100ms sleeps.

A one-shot partial close fires when profit reaches 0.5 × the TP distance. If the resulting half volume clears the broker's minimum lot and 1.5 × min_lots, half the position is closed via TryClosePartial_EX18004() (3 retries, 200ms sleeps on transient) and the ticket is pushed into g_partialClosedTickets[] so it never fires again on the same trade.

The pyramid layer is off by default. With InpPyramidMaxLevels > 0 (max 5), ManageScaling() runs after ManageExits(), checks that all existing positions in the direction are profitable by 0.5 × ATR, then re-uses TryEntry() to add a layer. The scaling inherits all the same regime, signal, confirm, and no-trade gates as the original entry, so a pyramid add on a weak regime is impossible.

Safety sits across the whole stack. NoTrade() blocks entries if the kill switch is on, if spread exceeds 300 points, if the server hour is outside 7-21, on weekends, if the effective capital drops below InpCapFloor (default $50), if realized daily loss has hit 3% of effective capital, if the weekly loss has hit 9%, if InpMaxConcurrent (default 1) positions are already open, or if g_consecLosses ≥ 3 and we are still inside the 5-bar cooldown window. All PnL tracking walks HistoryDealsTotal() for deals matching this magic and this symbol only — no other EAs are touched. The dry-run switch (InpDryRun = true by default) lets you log every signal that would have fired without sending an order, which is how you should first run this EA on a live terminal.

The OnTester formula is (STAT_PROFIT × STAT_PROFIT_FACTOR) / (1 + STAT_BALANCE_DDREL_PERCENT), which weights the optimization criterion toward both net return and the profit factor while penalizing the relative balance drawdown. If the test has fewer than 30 trades, OnTester returns 0 to suppress noisy optimizations.

What to expect in backtest: because the EA only fires on a closed-bar ADX/DI cross and the regime gate rejects CHOPPY and COMPRESS, the trade frequency on XAUUSD M5 is moderate — typically a handful of setups per London-NY session, fewer during the Asia overlap. The default 1:2 R:R and 0.5% risk per trade means a long quiet trend produces a steady string of small wins plus the occasional 2R home run, while a choppy week will mostly produce cooldown-driven silence rather than losses. The partial close at 0.5×TP locks in roughly 1R on every winner regardless of where the final exit lands, which is what gives the equity curve its smoother look in optimizer runs.

Strategy Deep Dive

The EA processes a single closed bar per cycle: it reads ADX(14) plus +DI and −DI on bar 1, runs them through a 7-state regime classifier built on ADX, ATR(14) percentile over 100 bars, and Bollinger Band(20, 2.0) width, and blocks entries on CHOPPY and COMPRESS states. Surviving setups then face three confirmations — H1 ADX/DI agreement, RSI(14) midpoint at 50, and a spread/limit check — before CalcLot() sizes the order at 0.5% risk with an ATR(14) × 2.0 stop and a 2× TP. ManageExits() watches every tick: opposite-signal closes the side, CHOPPY regime closes the basket, the time stop at 200 bars force-closes the trade, the break-even at 1R moves the stop to open ± 0.05×ATR, the ATR trail at 2.5×ATR walks the stop in the favorable direction only, and a 50% partial close fires at 0.5× TP distance. The pyramid layer (off by default) re-uses the same entry path, gated on all existing layers being profitable by 0.5× ATR, and every modify or close call is wrapped in a 3-retry helper that pauses 100-200ms on requote/timeout.

Entry Signal

A long fires when +DI crosses above −DI on the last closed M5 bar while ADX(14) sits at or above 25, the 7-state regime classifier returns STRONG_TREND, WEAK_TREND, RANGE, or BREAKOUT (CHOPPY and COMPRESS are blocked), the H1 ADX/DI direction agrees, RSI(14) is above 50, spread is under 300 points, and the implied R:R clears 1.0. The order is then sized via 0.5% risk of effective capital against an ATR(14) × 2.0 stop, with TP at 2× SL by default.

Exit Signal

Exits run on every tick: an opposite ADX/DI cross closes the existing side, a CHOPPY regime classification closes all positions for this magic, and a 200-bar time stop force-closes any aged trade. After 1R of profit, the stop ratchets to open ± 0.05×ATR (break-even), then trails at 2.5×ATR from current price in the favorable direction only. At 0.5× the TP distance, half the position is closed as a one-shot partial and the ticket is locked from re-partial.

Stop Loss

Stop loss is computed as ATR(14) × 2.0 (configurable via InpATRSLmult) and clamped above the broker's stops level plus a 5-point buffer. The stop then ratchets to break-even at open ± 0.05×ATR once profit reaches 1R, and trails at 2.5×ATR from the current bid/ask thereafter, moving only in the favorable direction. A 200-bar time stop also force-closes any position that lingers too long.

Take Profit

Take profit is the SL distance × (InpATRTPmult / InpATRSLmult), giving a 1:2 R:R at defaults (2.0× ATR for SL, 4.0× ATR for TP). A one-shot partial close fires at 0.5× the TP distance, locking in roughly 1R on every winner; the remaining half is then managed by the trailing stop.

Best For

Minimum recommended balance: $100. Best run on XAUUSD M5 (works on any timeframe) with a low-spread broker that keeps point spreads under 300 (≤ 30 pips on gold) and a server on GMT+0/+1/+2/+3 so the 7-21 server-hour window captures the London-NY overlap. Suitable for MEDIUM-risk accounts that want a single position at a time, with 0.5% per-trade risk and a 1:2 R:R as the default profile. The InpCapAmount cap and InpCapFloor floor make it a good fit for prop-firm-style evaluation accounts where protecting a hard equity ceiling matters more than scaling up.

Strategy Logic

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

Family: TrendFollow Magic: 22218004 Version: 2.00

BRIEF: ADX/DI trend-follow with regime gating — +DI/-DI cross while ADX>threshold on last CLOSED bar, wrapped in ADX+ATR- percentile+BB-width regime classifier, HTF trend confirm, RSI midpoint filter, spread/session/no-trade gates, ATR-based SL/ TP, break-even + partial TP + ATR trailing, pyramid OFF by default, OnTester metric. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • RawSignal()
  • ConfirmEntry()
  • NoTrade()
  • TryEntry()
  • ManageExits()
  • ManageScaling()
  • EnforceStopsLevel()
  • RespectStops()
  • NormalizeVolume()
  • CalcLot()
  • MarginOk()
  • CountOurPositions()
  • ...and 10 more

INTERNAL CONSTANTS (18 total):

  • ATR_PERIOD = 14 // ATR period (vol regime)
  • ATR_PCTILE_LOOKBACK = 100 // ATR percentile window
  • BB_PERIOD = 20 // Bollinger period
  • BB_DEV = 2.0 // Bollinger deviation
  • BE_TRIGGER_R = 1.0 // Break-even trigger (R multiples)
  • TRAIL_ATR_MULT = 2.5 // ATR trailing multiplier
  • MAX_BARS_IN_TRADE = 200 // Max bars in trade (time stop)
  • SESSION_START_HOUR = 7 // Session start (server hour)
  • SESSION_END_HOUR = 21 // Session end (server hour)
  • COOLDOWN_AFTER_LOSS = 3 // Consecutive losses to trigger cooldown
  • WEEKLY_LOSS_PCT = 9.0 // Weekly loss limit (% effective)
  • ATR_PCTILE_LOW = 40.0 // %ile below which regime = Compress
  • ATR_PCTILE_HIGH = 85.0 // %ile above which regime = Expand/Breakout
  • BB_SZ_LOW_PCT = 30.0 // BB width percentile (compress cutoff)
  • PARTIAL_TP_FRAC = 0.50 // fraction to close at BE
  • ...and 3 more

INPUT PARAMETERS (19 total across 7 groups):

  • [=== Identity ===] InpMagic = 22218004 // Magic number
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18004" // Trade comment
  • [=== Identity ===] InpDryRun = true // Dry-run: skip live orders
  • [=== Identity ===] InpKillSwitch = false // Emergency kill switch
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk % per trade (effective_capital)
  • [=== Risk & Sizing ===] InpFixedLot = 0.01 // Fixed lot if risk=0
  • [=== Risk & Sizing ===] InpDailyLossLimitPct = 3.0 // Daily loss limit (% effective)
  • [=== Risk & Sizing ===] InpMaxConcurrent = 1 // Max concurrent trades (this magic)
  • [=== Capital Allocation Cap ===] InpCapAmount = 0.0 // Real-money cap ($)
  • [=== Capital Allocation Cap ===] InpCapFloor = 50.0 // Floor below which no entries ($)
  • [=== Signal (ADX/DI) ===] InpADXPeriod = 14 // ADX period
  • [=== Signal (ADX/DI) ===] InpADXThreshold = 25 // Min ADX for trend
  • [=== Signal (ADX/DI) ===] InpRequireDICross = true // Require +DI/-DI cross
  • [=== Regime Filter ===] InpHTFTimeframe = PERIOD_H1 // Higher TF for trend agreement
  • [=== Exit / Manage ===] InpATRSLmult = 2.0 // ATR SL multiplier
  • [=== Exit / Manage ===] InpATRTPmult = 4.0 // ATR TP multiplier (R:R)
  • [=== Execution ===] InpMaxSpreadPts = 300 // Max spread (points)
  • [=== Execution ===] InpSlippagePts = 20 // Slippage (points)
  • [=== Execution ===] InpPyramidMaxLevels = 0 // Pyramids (0=OFF, max 5)
Pseudocode
// Pipsgrowth EX18004 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// ADX/DI trend-follow with regime gating — +DI/-DI cross while ADX>threshold on last CLOSED bar, wrapped in ADX+ATR- percentile+BB-width regime classifier, HTF trend confirm, RSI midpoint filter, spread/session/no-trade gates, ATR-based SL/ TP, break-even + partial TP + ATR trailing, pyramid OFF by default, OnTester metric. 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
InpMagic22218004Magic number
InpTradeComment"Psgrowth.com Expert_18004"Trade comment
InpDryRuntrueDry-run: skip live orders
InpKillSwitchfalseEmergency kill switch
InpRiskPercent0.5Risk % per trade (effective_capital)
InpFixedLot0.01Fixed lot if risk=0
InpDailyLossLimitPct3.0Daily loss limit (% effective)
InpMaxConcurrent1Max concurrent trades (this magic)
InpCapAmount0.0Real-money cap ($)
InpCapFloor50.0Floor below which no entries ($)
InpADXPeriod14ADX period
InpADXThreshold25Min ADX for trend
InpRequireDICrosstrueRequire +DI/-DI cross
InpHTFTimeframePERIOD_H1Higher TF for trend agreement
InpATRSLmult2.0ATR SL multiplier
InpATRTPmult4.0ATR TP multiplier (R:R)
InpMaxSpreadPts300Max spread (points)
InpSlippagePts20Slippage (points)
InpPyramidMaxLevels0Pyramids (0=OFF, max 5)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18004.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18004 ADXTrend_XAUUSD_5M — ADX/DI trend-following EA, 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  posInfo;
CSymbolInfo    sym;
CAccountInfo   acc;

//================== INPUTS (12-22 hard cap) ========================
input group "=== Identity ==="
input long     InpMagic              = 22218004;              // Magic number
input string   InpTradeComment       = "Psgrowth.com Expert_18004";       // Trade comment
input bool     InpDryRun             = true;                 // Dry-run: skip live orders
input bool     InpKillSwitch         = false;                // Emergency kill switch

input group "=== Risk & Sizing ==="
input double   InpRiskPercent        = 0.5;                  // Risk % per trade (effective_capital)
input double   InpFixedLot           = 0.01;                 // Fixed lot if risk=0
input double   InpDailyLossLimitPct  = 3.0;                  // Daily loss limit (% effective)
input int      InpMaxConcurrent      = 1;                    // Max concurrent trades (this magic)

input group "=== Capital Allocation Cap ==="
// InpCapEnabled removed — use InpCapAmount=0 to disable                 // Enable capital cap
input double   InpCapAmount          = 0.0;                // Real-money cap ($)
input double   InpCapFloor           = 50.0;                 // Floor below which no entries ($)

input group "=== Signal (ADX/DI) ==="
input int      InpADXPeriod          = 14;                   // ADX period
input int      InpADXThreshold       = 25;                   // Min ADX for trend
input bool     InpRequireDICross     = true;                 // Require +DI/-DI cross

input group "=== Regime Filter ==="
input int      InpHTFTimeframe       = PERIOD_H1;            // Higher TF for trend agreement

input group "=== Exit / Manage ==="
input double   InpATRSLmult          = 2.0;                  // ATR SL multiplier
input double   InpATRTPmult          = 4.0;                  // ATR TP multiplier (R:R)

input group "=== Execution ==="
input int      InpMaxSpreadPts       = 300;                  // Max spread (points)
input int      InpSlippagePts        = 20;                   // Slippage (points)
input int      InpPyramidMaxLevels   = 0;                    // Pyramids (0=OFF, max 5)
//================== INPUTS END (21 total) ==========================
//
// Tunables below are intentionally #define constants (not inputs) to
// respect the 22-input cap. Edit + recompile to change.
#define ATR_PERIOD          14       // ATR period (vol regime)
#define ATR_PCTILE_LOOKBACK 100      // ATR percentile window
#define BB_PERIOD           20       // Bollinger period
#define BB_DEV              2.0      // Bollinger deviation

Full source code available on download

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

Tags:ex18004trendfollowpipsgrowthfreemt5xauusd

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