P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX16001 Trend

MT5 Expert Advisor (Open Source) · XAUUSD · M5, M15

Pipsgrowth.com EX16001 TRACE+ Trend — Kalman slope + AVWAP + Hurst + ATR pullback, full 12-layer stack.

Overview

TRACE+ Trend waits for an institutional-grade signal stack to converge before sending any order. At the heart of the entry path sits a 2x2 local-linear Kalman filter that tracks the price level and slope jointly, an AVWAP anchor that re-roots on every break event, a Hurst R/S hysteresis gate that distinguishes persistent from choppy markets, and an ATR-percentile regime classifier that labels the current volatility state. Every layer is visible on the chart panel that the EA paints in the upper-left corner: slope z-score, Hurst exponent, ADX reading, ATR percentile, and the current regime string update on every closed bar.

The Kalman state is initialized on the first bar and updated with process noise scaled by ATR squared. The level gets q=0.01ATR^2, the slope gets q=0.001ATR^2, and the observation noise is r=0.05*ATR^2. The slope is then z-scored against a 300-bar rolling buffer maintained in rollSlope[]. The PercentRankOf helper computes the rank of the current slope within that buffer, and the entry hurdle InpEntryHurdleRank=0.80 by default requires the current slope to be in the top quintile of its own recent history. This is the trend strength test: only slopes that are unusually steep relative to the recent background earn entry.

The pullback entry band sits 0.6 to 1.2 ATR below the Kalman level for longs, and 0.6 to 1.2 ATR above for shorts (PULL_MIN_ATR=0.60, PULL_MAX_ATR=1.20). Price must be inside that band on the previous closed bar — not chasing the trend but pulling back into the structure. The AVWAP, anchored to the most recent slope-sign flip or any bar where |slope_z|>1.5, must agree with direction: long only if the close is above the AVWAP, short only below. When the AVWAP has not yet produced a valid value during the first AVWAP_MIN_BARS=10 bars after anchor, the agreement gate is waived so the EA can still trade early in a fresh trend.

A higher-timeframe filter reads the H1 50-EMA (HTF_PERIOD=PERIOD_H1, HTF_EMA_PERIOD=50) and requires the current-TF close to sit on the right side of a rising or falling H1 EMA. The HTF agreement can be disabled via InpHtfAgreeEnabled=false for pure single-TF behavior. The ClassifyRegime function labels the current state across seven buckets. StrongTrend requires ADX >= 30 and ATR-rank >= 0.7. WeakTrend is ADX >= 20 with ATR-rank >= 0.5. Expand requires ATR-rank >= 0.85 and a wide Bollinger width. Compress is ATR-rank <= 0.15. Breakout needs ATR-rank >= 0.65 and Bollinger width > 0.7. Range fires when ADX < 10. Choppy is the default bucket. RegimeAllowsEntry returns true only for StrongTrend, WeakTrend, Breakout, and Expand, blocking entries in Range, Compress, and Choppy.

The Hurst exponent is computed from a 200-bar R/S window (HURST_WINDOW=200) with a Hysteresis gate. It must rise above InpHurstOn=0.53 to turn the gate on, and only fall below HURST_OFF_THRESH=0.49 to turn it off. The 0.04 spread between ON and OFF prevents whipsaw on choppy regimes and reflects the EA's structural preference for persistent, trending markets. When the gate is off, entries are blocked with the reason hurst_low.

Risk is sized at InpRiskPercent=0.50% of effective capital per trade. The lot calculation is risk_money divided by stop_distance_in_ticks multiplied by tick_value_per_lot, then clamped to the broker's lot step, minimum, and maximum via ClampVolume. Initial stop is set at the higher of the 14-bar Recent Low and the Kalman level minus 1.2 ATR, with an additional cap that the stop cannot be more than 0.5 ATR beyond the close. Minimum required R/R is InpMinRR=1.50; the projected reward is TP_FINAL_R_MULT=3.0 ATR from the band midpoint, so the stop geometry implies a 3R TP at the upper end of the typical R/R window.

Position management combines five exit mechanisms. A one-shot break-even fires at InpBE_R_Mult=1.0 R, moving the stop to entry plus one R. A 50% partial close (PARTIAL_PCT=0.50) fires at TP1_R_MULT=1.0 R. A Chandelier trail at InpChandelierK=3.0 ATR ratchets the stop behind the high-water mark. A 30/50/70 MFE-ATR lock ladder progressively moves the stop to entry plus 30%, 50%, and 70% of the favorable excursion at LOCK_30_ATR=1.0, LOCK_50_ATR=1.8, LOCK_70_ATR=2.6. The hard time exit fires at InpMaxBarsInTrade=200 bars. Opposite-signal and regime-flip exits are layered on top of all of these.

The default state of the EA is dry-run mode. InpDryRun=true logs every intended trade with full parameters and exits but does not place orders. Set InpDryRun=false to engage live trading. A long list of no-trade gates runs before the entry logic. InpKillSwitch=true immediately closes any open position. The InpCapitalCapFloor=50 floor blocks entries when effective capital drops below that value. Daily and weekly realized loss limits are checked against InpDailyLossLimitPct=3.0 and InpWeeklyLossLimitPct=6.0 of effective capital, both computed by walking the deal history filtered by magic number. The spread ceiling InpMaxSpreadPoints=50 is enforced via SpreadPoints(). The consecutive-loss cooldown triggers after InpCooldownAfterLoss=2 losses and blocks entries for COOLDOWN_BARS=5 bars. The per-bar duplicate-entry guard prevents multiple entries on the same closed bar.

The OnTester custom criterion weighs raw profit and profit factor against balance drawdown: criterion = (net_profit * profit_factor) / (1 + balance_dd_percent). A minimum of 30 trades is required to produce a non-zero score, which prevents the optimizer from latching onto lucky small samples. The hard-coded MAX_DRAWDOWN_PCT=20.0 is an internal safety stop.

Five native indicator handles are created in OnInit and released in OnDeinit: iATR(14), iADX(14), iBands(20, 0, 2.0, PRICE_CLOSE), iMA(50, MODE_EMA, PRICE_CLOSE) on the current timeframe, and iMA(50, MODE_EMA, PRICE_CLOSE) on H1. The retry helpers TryClose_EX16001, TryClosePartial_EX16001, and TryModify_EX16001 each attempt up to 3 times on REQUOTE, TIMEOUT, PRICE_OFF, and PRICE_CHANGED retcodes with 200ms sleeps on close attempts and 100ms sleeps on modify attempts, and unlike many EAs in this family these are actually wired into the live management path — the partial close, the break-even modify, and the trailing-stop modify all flow through them.

Strategy Deep Dive

The Kalman filter maintains a 2x2 state (level and slope) and is updated each bar with process noise scaled by ATR squared — the slope of that local-linear fit is z-scored against a 300-bar rolling buffer. A signal needs that slope-rank to clear 0.80 and the z-score to stay on the correct side. The AVWAP, anchored to the most recent slope-sign flip or any |slope_z|>1.5 break, supplies a volume-weighted reference that the entry must align with. A 200-bar Hurst R/S estimate sits behind a hysteresis gate, opening at 0.53 and closing at 0.49 so the EA only trades persistent markets. The H1 50-EMA agreement layer forces alignment with the higher-timeframe trend. The ClassifyRegime function reads ADX, ATR-percentile, and Bollinger width to bucket the current state across seven regimes; entries are only allowed in StrongTrend, WeakTrend, Breakout, and Expand. ManageOpenPosition runs every tick and stacks five exit mechanisms — break-even at +1R, 50% partial at +1R, 3xATR Chandelier trail, 30/50/70 MFE-ATR lock ladder, and a 200-bar time exit — while OppositeSignal and regime-flip exits sit on top.

Entry Signal

The Kalman local-linear slope must be in the top quintile of its own 300-bar history (PercentRankOf >= 0.80) and the z-score must be positive. Price on the previous closed bar must sit inside the pullback band 0.6-1.2 ATR below the Kalman level for longs (mirror for shorts). The AVWAP, anchored to the most recent slope-sign flip or |slope_z|>1.5 break, must agree with direction, and the H1 50-EMA must also agree. Regime must be StrongTrend, WeakTrend, Breakout, or Expand. Hurst gate must be ON, spread must be under 50 points, and the projected R/R must be at least 1.5.

Exit Signal

Five exit mechanisms stack: a one-shot break-even at +1R moves the stop to entry, a 50% partial close fires at +1R, a 3xATR Chandelier trailing stop ratchets behind the high-water mark, a 30/50/70 MFE-ATR lock ladder progressively moves the stop to open+30%/50%/70% of favorable excursion at MFE-ATR thresholds 1.0/1.8/2.6, and a hard time exit at 200 bars fires InpMaxBarsInTrade. The 3R MFE target is the final-TP exit. Opposite-signal and regime-flip exits are layered on top of all of these.

Stop Loss

Initial stop is set at the higher of the 14-bar RecentLow and Kalman level minus 1.2 ATR, capped so it cannot be more than 0.5 ATR beyond the close (SL_ATR_FLOOR=1.20). The stop is then actively ratcheted by break-even at +1R, the 30/50/70 MFE-ATR lock ladder, and a 3xATR Chandelier trail. A hard equity drawdown safety stop of 20% is hard-coded as MAX_DRAWDOWN_PCT.

Take Profit

No fixed take-profit is set on entry — TP exits are managed adaptively. The first target is a 50% partial close at +1R (TP1_R_MULT=1.0). The final TP exit is the 3xATR MFE target (TP_FINAL_R_MULT=3.0) or the Chandelier stop ratchet, whichever fires first. A minimum R/R of InpMinRR=1.50 must be present at entry for the trade to be taken at all.

Best For

Minimum recommended balance: $100 on XAUUSD M5 or M15. Best paired with an ECN or low-spread broker where the 50-point spread ceiling does not block most of the session. The risk stack (0.5% per trade, 3% daily loss limit, 6% weekly loss limit, 20% hard DD cap, single concurrent position, 2-loss 5-bar cooldown) suits a patient trend-following operator rather than a high-frequency scalper. The InpDryRun=true default means the EA starts in dry-run mode and must be explicitly switched to live trading before any real order is sent.

Strategy Logic

Pipsgrowth EX16001 Trend — Strategy Logic Analysis (from .mq5 source)

Family: Trend Magic: 22216001 Version: 2.00

BRIEF: TRACE+ trend EA — Kalman local-linear slope z-score over percentile hurdle + AVWAP anchor agreement + Hurst hysteresis gate + ATR pullback bands. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • TickSize()
  • TickValuePerLot()
  • VolMin()
  • VolMax()
  • VolStep()
  • StopsLevel()
  • SpreadPoints()
  • NormalizePrice()
  • ClampVolume()
  • PushFIFO()
  • PercentileSimple()
  • PercentRankOf()
  • ...and 28 more

INTERNAL CONSTANTS (30 total):

  • ATR_PERIOD = 14 // ATR period for slope/z computation
  • ATR_SMOOTH_PCT_N = 200 // ATR-percentile window
  • BB_PERIOD = 20 // Bollinger width period
  • BB_DEVIATION = 2.0 // Bollinger deviation (std)
  • HTF_PERIOD = PERIOD_H1 // Higher timeframe for trend agreement
  • HTF_EMA_PERIOD = 50 // HTF EMA agreement period
  • KALMAN_Q_LEVEL_F = 0.01 // Kalman process noise level factor (×ATR²)
  • KALMAN_Q_SLOPE_F = 0.001 // Kalman process noise slope factor (×ATR²)
  • KALMAN_R_OBS_F = 0.05 // Kalman obs noise factor (×ATR²)
  • HURST_OFF_THRESH = 0.49 // Hurst hysteresis off (down-cross)
  • HURST_WINDOW = 200 // Hurst R/S window
  • PULL_MIN_ATR = 0.60 // Min pullback distance (×ATR)
  • PULL_MAX_ATR = 1.20 // Max pullback distance (×ATR)
  • SWING_LOOKBACK = 14 // Swing lookback for initial SL
  • SL_ATR_FLOOR = 1.20 // Initial SL ATR floor
  • ...and 15 more

INPUT PARAMETERS (20 total across 6 groups):

  • [=== Identity ===] InpMagic = 22216001 // Magic number (unique per EA)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_16001" // Trade comment
  • [=== Identity ===] InpDryRun = true // Dry-run mode (no real orders)
  • [=== Identity ===] InpKillSwitch = false // Kill switch (closes/all blocks)
  • [=== Risk & Sizing ===] InpRiskPercent = 0.50 // Risk % of effective capital per trade
  • [=== Risk & Sizing ===] InpDailyLossLimitPct = 3.00 // Daily realized loss limit (% of effective cap)
  • [=== Risk & Sizing ===] InpWeeklyLossLimitPct = 6.00 // Weekly realized loss limit (% of effective cap)
  • [=== Risk & Sizing ===] InpMaxConcurrent = 1 // Max concurrent trades (this magic)
  • [=== Risk & Sizing ===] InpCooldownAfterLoss = 2 // Cooldown bars after N consecutive losses
  • [=== Risk & Sizing ===] InpMaxSpreadPoints = 50.0 // Max allowed spread (points)
  • [=== Capital Allocation Cap ===] InpCapitalCapAmount = 0.0 // Capital cap (real money $)
  • [=== Capital Allocation Cap ===] InpCapitalCapFloor = 50.00 // Floor below which entries are blocked
  • [=== Signal ===] InpEntryHurdleRank = 0.80 // Kalman slope %rank hurdle (0..1)
  • [=== Signal ===] InpHurstOn = 0.53 // Hurst ON threshold (hysteresis)
  • [=== Regime & Confirm ===] InpAdxThreshold = 20.0 // ADX min for trend regime
  • [=== Regime & Confirm ===] InpHtfAgreeEnabled = true // Require HTF-EMA agreement
  • [=== Regime & Confirm ===] InpMinRR = 1.50 // Min required R/R for entry
  • [=== Exit & Manage ===] InpChandelierK = 3.0 // ATR trailing multiple (Chandelier)
  • [=== Exit & Manage ===] InpBE_R_Mult = 1.0 // Break-even at +R multiple
  • [=== Exit & Manage ===] InpMaxBarsInTrade = 200 // Max bars in trade (time exit)
Pseudocode
// Pipsgrowth EX16001 Trend — Execution Flow (from source analysis)
// Family: Trend
// TRACE+ trend EA — Kalman local-linear slope z-score over percentile hurdle + AVWAP anchor agreement + Hurst hysteresis gate + ATR pullback bands. 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:
M5M15

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
InpMagic22216001Magic number (unique per EA)
InpTradeComment"Psgrowth.com Expert_16001"Trade comment
InpDryRuntrueDry-run mode (no real orders)
InpKillSwitchfalseKill switch (closes/all blocks)
InpRiskPercent0.50Risk % of effective capital per trade
InpDailyLossLimitPct3.00Daily realized loss limit (% of effective cap)
InpWeeklyLossLimitPct6.00Weekly realized loss limit (% of effective cap)
InpMaxConcurrent1Max concurrent trades (this magic)
InpCooldownAfterLoss2Cooldown bars after N consecutive losses
InpMaxSpreadPoints50.0Max allowed spread (points)
InpCapitalCapAmount0.0Capital cap (real money $)
InpCapitalCapFloor50.00Floor below which entries are blocked
InpEntryHurdleRank0.80Kalman slope %rank hurdle (0..1)
InpHurstOn0.53Hurst ON threshold (hysteresis)
InpAdxThreshold20.0ADX min for trend regime
InpHtfAgreeEnabledtrueRequire HTF-EMA agreement
InpMinRR1.50Min required R/R for entry
InpChandelierK3.0ATR trailing multiple (Chandelier)
InpBE_R_Mult1.0Break-even at +R multiple
InpMaxBarsInTrade200Max bars in trade (time exit)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX16001.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX16001 TRACE+ Trend — Kalman slope + AVWAP + Hurst + ATR pullback, 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>

//==================== TUNABLE CONSTANTS (not inputs) ====================
#define ATR_PERIOD          14        // ATR period for slope/z computation
#define ATR_SMOOTH_PCT_N    200       // ATR-percentile window
#define BB_PERIOD           20        // Bollinger width period
#define BB_DEVIATION        2.0       // Bollinger deviation (std)
#define HTF_PERIOD          PERIOD_H1 // Higher timeframe for trend agreement
#define HTF_EMA_PERIOD      50        // HTF EMA agreement period
#define KALMAN_Q_LEVEL_F    0.01      // Kalman process noise level factor (×ATR²)
#define KALMAN_Q_SLOPE_F    0.001     // Kalman process noise slope factor (×ATR²)
#define KALMAN_R_OBS_F      0.05      // Kalman obs noise factor (×ATR²)
#define HURST_OFF_THRESH    0.49      // Hurst hysteresis off (down-cross)
#define HURST_WINDOW        200       // Hurst R/S window
#define PULL_MIN_ATR        0.60      // Min pullback distance (×ATR)
#define PULL_MAX_ATR        1.20      // Max pullback distance (×ATR)
#define SWING_LOOKBACK      14        // Swing lookback for initial SL
#define SL_ATR_FLOOR        1.20      // Initial SL ATR floor
#define HEADROOM_R_MIN      1.50      // Min projected R for entry
#define ROLLING_WINDOW      300       // Slope rolling window (percentile)
#define SLOPE_Z_FLOOR       0.0       // Min slope z for long bias / max for short
#define TP1_R_MULT          1.0       // First target R multiple (partial 50%)
#define TP_FINAL_R_MULT     3.0       // Final target R multiple
#define LOCK_30_ATR         1.0       // MFE ATR for 30% lock
#define LOCK_50_ATR         1.8       // MFE ATR for 50% lock
#define LOCK_70_ATR         2.6       // MFE ATR for 70% lock
#define MAX_DRAWDOWN_PCT    20.0      // Equity DD% safety hard stop
#define AVWAP_ANCHOR_THRESH 0.50      // BOCPD-break threshold (cp_prob)
#define AVWAP_MIN_BARS      10        // Min bars after anchor for AVWAP use
#define NEWS_WINDOW_MIN     0         // Manual news window minutes (0=off)
#define MAX_SYMBOL_EXPOSURE 1         // Max simultaneous positions on this symbol
#define PARTIAL_PCT         0.50      // Partial close fraction at TP1
#define COOLDOWN_BARS       5         // Bars cooldown after a losing close

//==================== INPUTS (21 total, grouped) ========================
input group "=== Identity ==="
input int      InpMagic              = 22216001;   // Magic number (unique per EA)
input string   InpTradeComment       = "Psgrowth.com Expert_16001"; // Trade comment
input bool     InpDryRun             = true;      // Dry-run mode (no real orders)
input bool     InpKillSwitch         = false;     // Kill switch (closes/all blocks)

input group "=== Risk & Sizing ==="
input double   InpRiskPercent        = 0.50;      // Risk % of effective capital per trade
input double   InpDailyLossLimitPct  = 3.00;      // Daily realized loss limit (% of effective cap)
input double   InpWeeklyLossLimitPct = 6.00;      // Weekly realized loss limit (% of effective cap)
input int      InpMaxConcurrent      = 1;         // Max concurrent trades (this magic)
input int      InpCooldownAfterLoss  = 2;         // Cooldown bars after N consecutive losses
input double   InpMaxSpreadPoints    = 50.0;      // Max allowed spread (points)

input group "=== Capital Allocation Cap ==="

Full source code available on download

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

Tags:ex16001trendpipsgrowthfreemt5xauusd

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