Pipsgrowth EX18033 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5
Pipsgrowth.com EX18033 EX210 — EMA cross + HA/SuperTrend, ADX/ATRpct/BB-width regime, capital cap, full in-trade management.
Overview
Pipsgrowth EX18033 TrendFollow waits for a fast/slow EMA crossover on the closed bar and then layers three independent bias checks on top of it before any order is sized. The core signal is a 8-period EMA crossing a 21-period EMA on the just-closed candle — long when the fast line is above the slow line at the close of bar 1 and was at or below it on bar 2, short on the mirror image. The crossover alone is not enough. A second 89-period EMA provides a trend-slope bias: if the trend EMA is sloping down over the last two closes, a long crossover is admitted with a confidence score of 20 (the trade is still permitted but the engine is flagging that the bigger timeframe is not aligned). If the trend slope agrees with the signal direction, the engine then runs an inlined Heikin-Ashi color check (input InpUseHeikenFilter, default true) that rebuilds ha_open and ha_close from the previous two bars' open/high/low/close, and rejects the signal when the synthetic candle is the wrong color — that drops confidence to 25. Finally a stateless inlined SuperTrend band (input InpUseSuperTrend, default true, multiplier 2.2 — the 22 in InpSuperTrendMult_x10 is divided by 10 at runtime) is computed as median(high,low) ± 2.2 × ATR(14) on bar 1; if the close is outside the band on the wrong side, the confidence drops to 30. When all three checks clear, the CoreSignal() function returns the original ±1 with confidence set to 70 and the trade is allowed to flow into the confirmation layer.
That confirmation layer is governed by ClassifyRegime() and ConfirmEntry(). The regime classifier reads ADX(14), ATR(14), and the 20-period Bollinger band on the same chart. It compares today's band width to the previous bar's width with a 5 percent expansion / 5 percent compression threshold, and computes an ATR percentile by ranking the current ATR against the prior 50 bars. With ADX ≥ 18 the engine returns REG_EXPAND if the bands are widening, REG_STRONG_TREND if the ATR sits in the top 30 percent of its 50-bar distribution, and REG_WEAK_TREND otherwise. With ADX below 18 it returns REG_COMPRESS, REG_BREAKOUT, REG_RANGE, or REG_CHOPPY depending on the band action and ATR rank. The NoTradeReason() function then flat-blocks the choppy and compress regimes (REG_CHOPPY and REG_COMPRESS_NO_BREAKOUT) before any other gate runs, and ConfirmEntry() demands that the surviving regime be one of REG_STRONG_TREND, REG_WEAK_TREND, REG_BREAKOUT, or REG_EXPAND. The same confirm pass also re-reads the 89-EMA slope over the last 5 bars and verifies the close of bar 1 finished on the correct side of bar 2's close, so a crossover that has already been invalidated by a fast one-bar pullback never reaches the order ticket.
The risk layer is built around a 0.5 percent risk-per-trade figure (InpRiskPercent = 0.5) applied to an effective capital that is normally the full account equity. The cap is technically wired to InpCapitalCapEnabled in the OnTick sizing path, but that flag was removed from the inputs — the comment in the source tells the user to set InpCapitalCapAmount = 0 to disable, and the floor guard in NoTradeReason() still refuses to trade when equity falls below INP_CAP_FLOOR_DOLLARS = 50. The daily loss limit is 3 percent of effective capital, the weekly loss limit is 6 percent (INP_WEEKLY_LOSS_PCT), and a 3-loss counter arms a session-wide cooldown. Lot sizing is the standard pip-distance method: riskMoney / (slDistance / tickSize × tickValue), floored to the lot step, clipped to the lot minimum, and capped at 5.00 lots. Margin is checked with a 1.2× free-margin safety before any send.
Stop loss and take profit are both anchored to the entry price through ATR(14). The SL is placed at 2.0 × ATR (InpATRSLmult) below a buy or above a sell, and the TP is placed at 1:2 reward-to-risk (InpRRtarget = 2.0), so the TP is 4.0 × ATR from entry. The ExecuteEntry() function also forces a minimum broker stop distance using SYMBOL_TRADE_STOPS_LEVEL, and the order is sent as a market order with deviation 20 points through the standard CTrade wrapper, with one retry on REQUOTE / TIMEOUT / PRICE_OFF.
The in-trade management block is identical in structure to other TrendFollow v2.00 EAs but uses a different exit profile. A position that reaches +1R has its stop moved to break-even (open price + stopsPts × point, a one-shot move), and a position that reaches +1.5R has half of the position closed at market (vol/2 normalized to the lot step, only when the residual stays above the broker minimum). After break-even, an ATR trailing stop at 2.5 × ATR(14) (InpATRTrailMult) takes over and only ever ratchets forward — it will not retreat when price pulls back, and it will not step below the original entry price once break-even has armed. A 240-bar time stop (InpMaxBarsInTrade, twenty hours of M5 bars) closes any position that has not produced a profit-locking move. PYRAMID is compiled in but defaulted to off (INP_USE_PYRAMID = false); flipping the constant would allow up to 3 scaled-in entries spaced 1.5 × ATR apart, all of which have to be in profit before another add is allowed. The MAX_OPEN_TRADES cap is 3 (InpMaxConcurrent).
Execution is filtered by a 50-point spread cap (InpMaxSpreadPoints = 50, so 5 pips on a 5-digit XAUUSD quote), a 1-23 server-hour session (INP_SESSION_START_HOUR / INP_SESSION_END_HOUR), weekend and Friday-after-22:00 blocks, and the standard kill switch / dry-run defaults. InpDryRun ships as true, so the EA prints intended orders to the journal but does not send them to the broker until the user turns live execution on. The order comment is "Psgrowth.com Expert_18033" and the magic number is 22218033. The OnTester() function scores the backtest as netProfit × profitFactor / (1 + balance drawdown) with a 30-trade minimum, which is the same family-wide objective used across the TrendFollow v2.00 series.
What to expect in practice: on a clean XAUUSD M5 trend day the EMA cross fires once or twice and the engine rides with the 89-EMA bias, exiting at 1:2R or being trailed out by the 2.5×ATR stop. On a range day the regime classifier drops into REG_RANGE or REG_CHOPPY and NoTradeReason() blocks entries, so the EA sits on its hands until the bands start expanding again. The Magic 22218033 prefix means every position this EA opens is identifiable in the trade history with that exact number, which is the lever to use when reconciling backtest reports against the broker statement.
Strategy Deep Dive
Each tick refreshes symbol rates, recalculates effective capital, rolls the daily date forward if needed, calls RefreshRealized() to aggregate today/week realized P&L, and exits early if the 3 percent daily loss cap is already tripped. ClassifyRegime() then reads ADX(14), ATR(14), and the 20-period Bollinger band, computes an ATR percentile against the prior 50 bars, and returns one of seven regimes; the no-trade gate blocks CHOPPY and COMPRESS before any signal work. CoreSignal() pulls the EMA(8), EMA(21), and EMA(89) values for the last two to three closed bars, detects a fresh crossover, and then sequentially demotes confidence through trend-slope, inlined Heikin-Ashi, and inlined SuperTrend checks until the surviving bias state is known. ConfirmEntry() re-reads the 89-EMA slope over five bars, demands the regime is one of the four trend-eligible states, and verifies the bar-1 close is on the correct side of bar-0. Only after all of that does ExecuteEntry() size the lot from the 0.5 percent risk figure, run CheckMargin(), and send the order with a single retry on requote/timeout. ManageExits() runs on every tick and applies time-stop, break-even, partial-TP, and the 2.5×ATR(14) forward-only trail in that order, while CloseOpposite() flattens positions on the wrong side of a fresh signal before the new entry is sized.
A long entry triggers when the 8-period EMA closes above the 21-period EMA on bar 1 with a prior cross, the 89-period EMA slope is non-negative, the inlined Heikin-Ashi color agrees, and the close sits inside the long side of the 2.2×ATR(14) SuperTrend band. Short entries mirror those conditions. Confidence reaches 70 only when all three bias checks (trend slope, HA color, SuperTrend side) clear, and the regime must be STRONG_TREND, WEAK_TREND, BREAKOUT, or EXPAND.
Positions exit on the 240-bar M5 time stop, on stop-loss hit, on the 1:2R take-profit, on a break-even-armed 2.5×ATR(14) trailing stop, on the 50 percent partial close at +1.5R followed by the residual being trailed, or on an opposite-signal close that first flattens the other side via CloseOpposite() before re-evaluating entry.
Initial stop is 2.0×ATR(14) from the entry price, clamped above the broker SYMBOL_TRADE_STOPS_LEVEL minimum. After the position reaches +1R the stop is moved to break-even (entry plus one stops-level point), and from there the 2.5×ATR(14) trail takes over and only ratchets forward.
Take profit is 1:2 reward-to-risk (TP = 4.0×ATR(14) from entry, since SL = 2.0×ATR). A 50 percent partial close fires at +1.5R before the full TP, after which the residual is managed by the ATR trail.
Best run on XAUUSD M5 with a minimum starting balance of $100, on a low-spread ECN or RAW broker where the 50-point spread cap (5 pips on a 5-digit quote) is rarely tripped. The 1-23 server-hour session window covers essentially the full trading day so a GMT+2 or GMT+3 broker aligns cleanly with the London and New York sessions, and the weekly 6 percent loss cap plus the 3-loss cooldown make this a sensible choice for traders who want a single-pair trend EA with explicit per-trade risk and a hard ceiling on drawdown.
Strategy Logic
Pipsgrowth EX18033 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218033
Version: 2.00
BRIEF:
EMA(8/21) cross on closed bar biased by EMA(89) trend slope, inlined HeikinAshi color and SuperTrend side. ADX/ATR- percentile/Bollinger-width regime gates entries, sizing, and ATR trail. Full 12-layer stack with capital allocation cap. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
CopyBufSafe()HourOf()DateStart()ClassifyRegime()CoreSignal()NoTradeReason()ConfirmEntry()ComputeLot()CheckMargin()RefreshRealized()CountMyPositions()CountMyPositionsByType()- ...and 9 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (22 total across 5 groups):
- [=== Strategy ===]
InpFastEMA= 8 // FastEMAperiod (bars) - [=== Strategy ===]
InpSlowEMA= 21 // SlowEMAperiod (bars) - [=== Strategy ===]
InpTrendEMA= 89 // TrendEMAperiod (bars) - [=== Strategy ===]
InpSuperTrendMult_x10= 22 //SuperTrendATRmult x10 (22=2.2) - [=== Strategy ===]
InpUseHeikenFilter=true//HeikinAshicolor filter - [=== Strategy ===]
InpUseSuperTrend=true//SuperTrendside filter - [=== Regime ===]
InpADXPeriod= 14 //ADXperiod (bars) - [=== Regime ===]
InpMinADX=18.0// MinADXfor trend (units) - [=== Regime ===]
InpATRPeriod= 14 //ATRperiod (bars) - [=== Regime ===]
InpBBPeriod= 20 // Bollinger period (bars) - [=== Risk & Sizing ===]
InpCapitalCapAmount=0.0// Capital cap amount ($ equity) - [=== Risk & Sizing ===]
InpRiskPercent=0.5// Risk per trade (% eff. capital) - [=== Risk & Sizing ===]
InpDailyLossLimitPct=3.0// Daily loss limit (% eff. capital) - [=== Risk & Sizing ===]
InpATRSLmult=2.0// SL =ATRx mult (units) - [=== Risk & Sizing ===]
InpRRtarget=2.0// Reward:Risk TP ratio (units) - [=== In-Trade Management ===]
InpATRTrailMult=2.5//ATRtrailing multiplier (units) - [=== In-Trade Management ===]
InpMaxBarsInTrade= 240 // Max bars in trade (bars) - [=== Execution ===]
InpDryRun=true// Dry-run (no live sends) - [=== Execution ===]
InpKillSwitch=false// Emergency kill switch - [=== Execution ===]
InpMaxSpreadPoints= 50 // Max spread (points) - [=== Execution ===]
InpMaxConcurrent= 3 // Max concurrent trades (units) - [=== Execution ===]
InpTradeComment= "Psgrowth.com Expert_18033" // Order comment
// Pipsgrowth EX18033 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// EMA(8/21) cross on closed bar biased by EMA(89) trend slope, inlined HeikinAshi color and SuperTrend side. ADX/ATR- percentile/Bollinger-width regime gates entries, sizing, and ATR trail. Full 12-layer stack with capital allocation cap. 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 |
|---|---|---|
| InpFastEMA | 8 | Fast EMA period (bars) |
| InpSlowEMA | 21 | Slow EMA period (bars) |
| InpTrendEMA | 89 | Trend EMA period (bars) |
| InpSuperTrendMult_x10 | 22 | SuperTrend ATR mult x10 (22=2.2) |
| InpUseHeikenFilter | true | HeikinAshi color filter |
| InpUseSuperTrend | true | SuperTrend side filter |
| InpADXPeriod | 14 | ADX period (bars) |
| InpMinADX | 18.0 | Min ADX for trend (units) |
| InpATRPeriod | 14 | ATR period (bars) |
| InpBBPeriod | 20 | Bollinger period (bars) |
| InpCapitalCapAmount | 0.0 | Capital cap amount ($ equity) |
| InpRiskPercent | 0.5 | Risk per trade (% eff. capital) |
| InpDailyLossLimitPct | 3.0 | Daily loss limit (% eff. capital) |
| InpATRSLmult | 2.0 | SL = ATR x mult (units) |
| InpRRtarget | 2.0 | Reward:Risk TP ratio (units) |
| InpATRTrailMult | 2.5 | ATR trailing multiplier (units) |
| InpMaxBarsInTrade | 240 | Max bars in trade (bars) |
| InpDryRun | true | Dry-run (no live sends) |
| InpKillSwitch | false | Emergency kill switch |
| InpMaxSpreadPoints | 50 | Max spread (points) |
| InpMaxConcurrent | 3 | Max concurrent trades (units) |
| InpTradeComment | "Psgrowth.com Expert_18033" | Order comment |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18033 EX210 — EMA cross + HA/SuperTrend, ADX/ATRpct/BB-width regime, capital cap, full in-trade management."
#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) |
//+------------------------------------------------------------------+
input group "=== Strategy ==="
input int InpFastEMA = 8; // Fast EMA period (bars)
input int InpSlowEMA = 21; // Slow EMA period (bars)
input int InpTrendEMA = 89; // Trend EMA period (bars)
input int InpSuperTrendMult_x10 = 22; // SuperTrend ATR mult x10 (22=2.2)
input bool InpUseHeikenFilter = true; // HeikinAshi color filter
input bool InpUseSuperTrend = true; // SuperTrend side filter
input group "=== Regime ==="
input int InpADXPeriod = 14; // ADX period (bars)
input double InpMinADX = 18.0; // Min ADX for trend (units)
input int InpATRPeriod = 14; // ATR period (bars)
input int InpBBPeriod = 20; // Bollinger period (bars)
input group "=== Risk & Sizing ==="
// InpCapitalCapEnabled removed — use InpCapitalCapAmount=0 to disable // Capital allocation cap ON
input double InpCapitalCapAmount = 0.0; // Capital cap amount ($ equity)
input double InpRiskPercent = 0.5; // Risk per trade (% eff. capital)
input double InpDailyLossLimitPct = 3.0; // Daily loss limit (% eff. capital)
input double InpATRSLmult = 2.0; // SL = ATR x mult (units)
input double InpRRtarget = 2.0; // Reward:Risk TP ratio (units)
input group "=== In-Trade Management ==="
input double InpATRTrailMult = 2.5; // ATR trailing multiplier (units)
input int InpMaxBarsInTrade = 240; // Max bars in trade (bars)
input group "=== Execution ==="
input bool InpDryRun = true; // Dry-run (no live sends)
input bool InpKillSwitch = false; // Emergency kill switch
input int InpMaxSpreadPoints = 50; // Max spread (points)
input int InpMaxConcurrent = 3; // Max concurrent trades (units)
// 22 inputs above. Optional extras below use sensible defaults inside code.
//+------------------------------------------------------------------+
//| Globals |
//+------------------------------------------------------------------+
CTrade trade;
CPositionInfo posInfo;
CSymbolInfo symbolInfo;
CAccountInfo accountInfo;
COrderInfo orderInfo;
CDealInfo dealInfo;
int h_fastEMA, h_slowEMA, h_trendEMA, h_adx, h_atr, h_bb;Full 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.