Pipsgrowth EX18034 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5
Pipsgrowth.com EX18034 EX30 — multi-filter trend consensus (Hull+SuperTrend+HA+EMA) with regime gate and capital cap.
Overview
EX18034 is a four-filter trend consensus engine. Rather than betting the trade on a single moving-average cross, it asks four independent questions on the last closed M5 bar and only acts when the answers line up. The four filters are: where the close sits relative to a 50-period EMA on the current timeframe, the sign of an inlined Hull MA(20) slope, the side of an inlined SuperTrend(22, 3.0×ATR), and the colour of the most recent Heikin-Ashi candle. Each filter gets one vote, and TrendSignal() returns a directional bias only when at least three of the four agree and the fourth is silent. Confidence is then reported as the vote count times twenty-five, so a 3-vote agreement prints 75 and a unanimous 4-vote print returns 100; the value is informational because the gate is the 3-of-4 rule, not the integer.
The Hull MA(20) is rebuilt in code from two LWMA handles rather than fetched from a built-in Hull indicator. HullValue() pulls the full-period LWMA and the half-period LWMA, computes two-times-half minus full, then runs a final LWMA of length sqrt(20)≈4 over that difference — the textbook Hull reconstruction. HullSlope() compares the value at shift=1 with shift=2 and returns +1, -1, or 0. The SuperTrend is also inlined. SuperTrendSide() holds the previous band and direction in module-level state (st_prev_dir, st_prev_upper, st_prev_lower) so the bands can ratchet in the standard SuperTrend way: a close above the prior upper band flips the side to +1, a close below the prior lower band flips to -1, and the current band is whichever of the local upper/lower or the carried value is tighter given the previous close. Heikin-Ashi color is computed by recursively walking back two bars — the HA-Open of the last closed bar is the average of the previous HA-Open and HA-Close, and HA-Close is the mean of the underlying OHLC. No third-party indicator handles are required for the signal stack.
The regime gate that sits on top of the consensus is a five-state classifier, not the seven-state version seen on some siblings. RegimeGet() reads ATR(14), ADX(14), and Bollinger Bands(20, 2.0) and computes the ATR-percentile over a 100-bar window (InpAtrLookback=100) and a parallel BB-width percentile over the same lookback. The five states are: REG_BREAKOUT when ADX is at or above InpAdxTrendMin (20) and both the ATR and BB-width percentiles sit at or above the 70th percentile, REG_STRONG_TREND for ADX above 20 without the volatility-pop confirmation, REG_WEAK_TREND for ADX between 18 and 20, REG_RANGE for low-volatility compression at the 30th percentile or below on both ATR and BB-width, and REG_CHOPPY as the residual catch-all. The 100-bar percentile is a longer memory than the 50-bar version used elsewhere in the family, which makes the regime label slower to flip and less prone to whipsawing around news spikes.
The confirm step applies after the signal fires. Confirm() reads the H1 EMA(50) and demands that the H1 close sits on the correct side of it, refuses to act when ADX is below 18 even if the four-vote consensus passed, and rejects trades when the configured reward-to-risk is below 1.0. There is no built-in higher-timeframe selector input — the HTF is hard-coded to PERIOD_H1. The 1.5 R:R default feeds straight into the position builder, so the take-profit distance is 1.5× the stop distance.
Stop placement uses ATR(14) and a fixed 2.0× multiplier. SendOrder() also enforces the broker's stops-level and freeze-level floors via AdjustForStops(), pushing the SL and TP a few points further out if the broker's minimum would otherwise be violated. The take-profit is set 3.0×ATR from the entry (2.0×ATR stop times the 1.5 R:R ratio). All lots are sized off effective capital, which on a fresh run equals account equity but can be reined in by InpCapAmount when a non-zero value is set. The default cap of 0 means the cap is effectively disabled and full equity is used. CalcLots() multiplies effective capital by the 0.5% risk percent, divides by the per-lot loss implied by the ATR stop distance and the symbol's tick value, then normalizes to the broker's lot step. CalcLots returns zero if effective capital has fallen below InpCapFloor (50 by default), which is what blocks entries on a blown account.
In-trade management has three legs and runs every tick regardless of whether a new entry is being considered. Once price has moved one R in the favourable direction, the stop is ratcheted to entry plus two points minus the broker stop floor, locking in a scratch-free break-even. The 50% partial close fires the moment the bid/ask touches open plus 1.5×R, halving the position and letting the remaining half run. The trailing stop is a 2.5×ATR forward-only ratchet that walks on every tick and only ever tightens — it never moves backwards. If the four-vote consensus flips against the open position, the entire position is closed at market through TryClose_EX18034(), which loops up to three attempts with 200 ms sleeps on requote, timeout, price-off, and price-changed retcodes. There is no time-based exit, no daily-trade cap, and no weekly loss limit on this build — the only account-level kill is the per-magic 3% daily realised PnL cap and the global InpKillSwitch input.
Pyramid add-ons are compiled into the binary but the default input is false, so out of the box EX18034 will not stack positions. If you flip InpPyramidEnabled to true, PyramidAllowed() will gate add-on entries behind regime not being CHOPPY or RANGE, a fresh bar having formed since the last entry, total position count being below the lesser of five and InpMaxOpen, and the existing same-direction position already in profit. The OnTester criterion is the standard (net × profit-factor) / (1 + relative drawdown) with a 30-trade floor, so the strategy optimizer will favour runs that combine profitability with a smooth equity curve rather than a single lucky streak.
In dry-run mode (the default), the EA prints what it would have done without sending orders. Switch InpDryRun off to go live. Order comments are tagged with the magic 22218034 and the string Psgrowth.com Expert_18034 so backtests and live journals can be filtered by comment. The header lists XAUUSD M5 as the suggested deployment but every parameter is symbol-agnostic — point out the EA at any XAU/USD, XAG/USD, or major pair that your broker offers, on any timeframe, and the same logic will run.
Strategy Deep Dive
Every tick the EA refreshes the symbol and pulls the four primary handles (ATR(14), ADX(14), BB(20,2), EMA(50)) plus the H1 ATR and H1 EMA for the confirm step. RegimeGet() classifies the market into one of five states using a 100-bar ATR-percentile plus a 100-bar BB-width-percentile, and CHOPPY is the only state that blocks outright. TrendSignal() then asks the four filters for a vote each — Hull slope, inlined SuperTrend side, inlined Heikin-Ashi colour, and EMA-side — and emits a direction only when at least three filters agree and the fourth is silent. Confirm() layers the H1 EMA cross-check, an ADX≥18 floor, and the R/R sanity check on top. SendOrder() sizes lots from effective capital, builds the 2.0×ATR stop and 1.5R take-profit, and calls the broker with a 20-point slippage and a single requote/timeout retry. ManagePositions() runs on every tick to apply the BE, partial, and trail legs, and to flip the position when the consensus reverses.
Entry is a 3-of-4 equal-weight consensus: close vs EMA(50), inlined Hull MA(20) slope, inlined SuperTrend(22, 3.0×ATR) side, and the colour of the most recent Heikin-Ashi candle. The Confirm() gate then requires the H1 EMA(50) close to sit on the same side, ADX≥18, regime not in CHOPPY, and the configured R/R above 1.0 before a position is sent.
Exits run on three rails: a one-shot break-even ratchet to entry+2pt once price reaches 1R, a 50% partial close at open+1.5R, and a 2.5×ATR forward-only trailing stop. A full close fires when the four-vote consensus flips against the open side, dispatched through a three-attempt retry loop on requote and timeout retcodes.
Initial stop is 2.0×ATR(14) from the entry, floored by the broker's stops-level and freeze-level via AdjustForStops(). A one-shot break-even adjustment snaps the stop to entry+2pt once price reaches 1R, and a 2.5×ATR forward-only trailing stop takes over from there.
Take-profit is 1.5× the stop distance, set as a broker-side TP at send time. A 50% partial close runs in-EA at open+1.5R, so the residual half is freed from a profit-locked position. The 2.5×ATR trail then governs the remainder until the opposite-signal close fires.
Suited to a $100 minimum deposit on XAUUSD M5 with an ECN or raw-spread account. The 1-23 server-time session is intentionally broad, so a low-spread broker that handles the full London-New York-Asia rotation is the most practical choice. The 3% daily loss limit, the $50 capital floor, and the InpKillSwitch make it usable on prop-firm challenge accounts as well as standard retail, provided the broker honours the trailing logic on a 0.01-lot minimum.
Strategy Logic
Pipsgrowth EX18034 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218034
Version: 2.00
BRIEF:
Multi-filter trend consensus (Trend EMA + inlined Hull-MA slope + SuperTrend side + Heikin-Ashi color) gated by ADX + ATR-percentile + BB-width regime. Entry fires on last closed bar; CONFIRM requires HTF EMA + ADX strength + candle-close + R/R. ATR SL/TP, break-even at R, partial 50%, ATR trail, momentum-decay, opposite-signal, max-bars exits. Capital allocation cap governs all risk. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
RegimeGet()HullValue()HullSlope()SuperTrendSide()HeikinAshiColor()TrendSignal()HtfTrendUp()HtfTrendDown()NoTradeReason()EffectiveCapital()TodayMagicRealizedPnL()NormalizeVolume()- ...and 14 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (23 total across 5 groups):
- [=== Regime Gate ===]
InpAdxTrendMin=20.0// MinADXforStrongTrend(units) - [=== Regime Gate ===]
InpAtrLookback= 100 //ATRpercentile lookback (bars) - [=== Regime Gate ===]
InpBBPeriod= 20 // Bollinger width period (bars) - [===
Signal(Trend Consensus) ===]InpHullPeriod= 20 // Hull MA period (bars) - [===
Signal(Trend Consensus) ===]InpSTPeriod= 22 //SuperTrendATRperiod (bars) - [===
Signal(Trend Consensus) ===]InpSTMult=3.0//SuperTrendATRmultiplier (xATR) - [===
Signal(Trend Consensus) ===]InpTrendEmaPeriod= 50 // TrendEMAperiod (bars) - [=== Risk & Sizing ===]
InpRiskPercent=0.5// Per-trade risk (% of eff. capital) - [=== Risk & Sizing ===]
InpDailyLossPct=3.0// Daily loss limit (% of eff. capital) - [=== Risk & Sizing ===]
InpMaxOpen= 5 // Max concurrent positions (count) - [=== Risk & Sizing ===]
InpPyramidEnabled=false// Pyramid add-ons (defaultOFF) - [=== Risk & Sizing ===]
InpCapAmount=0.0// Capital cap amount ($ equity) - [=== Risk & Sizing ===]
InpCapFloor=50.0// Capital cap floor ($ equity) - [=== Risk & Sizing ===]
InpDryRun=true// Dry-run mode (no live orders) - [=== Risk & Sizing ===]
InpKillSwitch=false// Global kill switch (bool) - [=== Exit & Trail ===]
InpAtrSLMult=2.0// SL distance (xATR) - [=== Exit & Trail ===]
InpRR=1.5// Reward:Risk forTP(R multiple) - [=== Exit & Trail ===]
InpTrailAtrMult=2.5//ATRtrailing distance (xATR) - [=== Exit & Trail ===]
InpBEActivationR=1.0// Break-even trigger (R multiple) - [=== Session & ID ===]
InpSessionStart= 1 // Session start hour (broker time, 0-23) - [=== Session & ID ===]
InpSessionEnd= 23 // Session end hour (broker time, 0-23) - [=== Session & ID ===]
InpMagic=22218034// Magic number (id) - [=== Session & ID ===]
InpTradeComment= "Psgrowth.com Expert_18034" // Order comment
// Pipsgrowth EX18034 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Multi-filter trend consensus (Trend EMA + inlined Hull-MA slope + SuperTrend side + Heikin-Ashi color) gated by ADX + ATR-percentile + BB-width regime. Entry fires on last closed bar; CONFIRM requires HTF EMA + ADX strength + candle-close + R/R. ATR SL/TP, break-even at R, partial 50%, ATR trail, momentum-decay, opposite-signal, max-bars exits. Capital allocation cap governs all risk. 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
How to Install This EA on MT5
- 1Download the .mq5 file using the button above
- 2Open MetaTrader 5 on your computer
- 3Click File → Open Data Folder in the top menu
- 4Navigate to MQL5 → Experts and paste the .mq5 file there
- 5In MT5, right-click Expert Advisors in the Navigator panel → Refresh
- 6Drag the EA onto an H4 or Daily chart for best results
- 7Configure EMA periods, ADX threshold, and lot size in the dialog
- 8Enable Allow Algo Trading and click OK
EA Parameters
| Parameter | Default | Description |
|---|---|---|
| InpAdxTrendMin | 20.0 | Min ADX for StrongTrend (units) |
| InpAtrLookback | 100 | ATR percentile lookback (bars) |
| InpBBPeriod | 20 | Bollinger width period (bars) |
| InpHullPeriod | 20 | Hull MA period (bars) |
| InpSTPeriod | 22 | SuperTrend ATR period (bars) |
| InpSTMult | 3.0 | SuperTrend ATR multiplier (xATR) |
| InpTrendEmaPeriod | 50 | Trend EMA period (bars) |
| InpRiskPercent | 0.5 | Per-trade risk (% of eff. capital) |
| InpDailyLossPct | 3.0 | Daily loss limit (% of eff. capital) |
| InpMaxOpen | 5 | Max concurrent positions (count) |
| InpPyramidEnabled | false | Pyramid add-ons (default OFF) |
| InpCapAmount | 0.0 | Capital cap amount ($ equity) |
| InpCapFloor | 50.0 | Capital cap floor ($ equity) |
| InpDryRun | true | Dry-run mode (no live orders) |
| InpKillSwitch | false | Global kill switch (bool) |
| InpAtrSLMult | 2.0 | SL distance (xATR) |
| InpRR | 1.5 | Reward:Risk for TP (R multiple) |
| InpTrailAtrMult | 2.5 | ATR trailing distance (xATR) |
| InpBEActivationR | 1.0 | Break-even trigger (R multiple) |
| InpSessionStart | 1 | Session start hour (broker time, 0-23) |
| InpSessionEnd | 23 | Session end hour (broker time, 0-23) |
| InpMagic | 22218034 | Magic number (id) |
| InpTradeComment | "Psgrowth.com Expert_18034" | Order comment |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18034 EX30 — multi-filter trend consensus (Hull+SuperTrend+HA+EMA) with regime gate and capital cap."
#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) ==========================
input group "=== Regime Gate ==="
input double InpAdxTrendMin = 20.0; // Min ADX for StrongTrend (units)
input int InpAtrLookback = 100; // ATR percentile lookback (bars)
input int InpBBPeriod = 20; // Bollinger width period (bars)
input group "=== Signal (Trend Consensus) ==="
input int InpHullPeriod = 20; // Hull MA period (bars)
input int InpSTPeriod = 22; // SuperTrend ATR period (bars)
input double InpSTMult = 3.0; // SuperTrend ATR multiplier (xATR)
input int InpTrendEmaPeriod = 50; // Trend EMA period (bars)
input group "=== Risk & Sizing ==="
input double InpRiskPercent = 0.5; // Per-trade risk (% of eff. capital)
input double InpDailyLossPct = 3.0; // Daily loss limit (% of eff. capital)
input int InpMaxOpen = 5; // Max concurrent positions (count)
input bool InpPyramidEnabled = false; // Pyramid add-ons (default OFF)
// InpCapEnabled removed — use InpCapAmount=0 to disable // Capital cap active (bool)
input double InpCapAmount = 0.0; // Capital cap amount ($ equity)
input double InpCapFloor = 50.0; // Capital cap floor ($ equity)
input bool InpDryRun = true; // Dry-run mode (no live orders)
input bool InpKillSwitch = false; // Global kill switch (bool)
input group "=== Exit & Trail ==="
input double InpAtrSLMult = 2.0; // SL distance (xATR)
input double InpRR = 1.5; // Reward:Risk for TP (R multiple)
input double InpTrailAtrMult = 2.5; // ATR trailing distance (xATR)
input double InpBEActivationR = 1.0; // Break-even trigger (R multiple)
input group "=== Session & ID ==="
input int InpSessionStart = 1; // Session start hour (broker time, 0-23)
input int InpSessionEnd = 23; // Session end hour (broker time, 0-23)
input int InpMagic = 22218034; // Magic number (id)
input string InpTradeComment = "Psgrowth.com Expert_18034"; // Order comment
//====================== END INPUTS =================================
//====================== GLOBALS ====================================
CTrade trade;
CPositionInfo posInfo;
CSymbolInfo sym;
CAccountInfo acc;
COrderInfo ordInfo;
CDealInfo dealInfo;
// Handles (created in OnInit, freed in OnDeinit)
int h_atr = INVALID_HANDLE; // ATR(current)
int h_atr_htf = INVALID_HANDLE; // ATR(HTF) - reused for trailFull source code available on download
Educational purposes only. Do NOT use with real money. Test on demo accounts only.
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
Markets.com
Exness
IC Markets
Similar Expert Advisors
View All Expert AdvisorsMore Trend Following strategy EAs from our library
Pipsgrowth EX16080 Trend
Pipsgrowth.com EX16080 EURUSDTrendFollower — triple-EMA H4 trend follower, full 12-layer stack.
Pipsgrowth EX16081 Trend
Pipsgrowth.com EX16081 GoldTrendEA — XAUUSD H4 EMA cross with Fib targets, full 12-layer stack.
Pipsgrowth EX16033 Trend
Pipsgrowth.com EX16033 EA_Price_Action — price-action grid scalper, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.