Pipsgrowth EX18031 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5
Pipsgrowth.com EX18031 EX20 — Trend-following breakout above ATR band around an EMA, full 12-layer stack.
Overview
Pipsgrowth EX18031 is built around a single, repeatable observation: on a fast chart, price spends most of its time clustered around its short-period EMA, and the moments when it actually leaves that cluster are the moments worth trading. The EA defines that cluster as a band of width InpBandMult * ATR(14) on either side of an EMA of length InpEMALength = 10 — a 10-bar Gaussian-style smoothed mean. A long signal triggers on the first closed bar whose close pushes above the upper band by at least InpBreakDistATR = 0.30 * ATR AND whose body is at least 60% of the bar's full range. The previous two closes must remain below the band so the breakout is fresh, not a late continuation, and the EMA itself must be sloping up. Shorts mirror the same condition against the lower band. ComputeSignal() returns ±1 and assigns a confidence score of 60 by default, with 15 extra points added when the current regime qualifies as a trend and a further 15 if that trend is rated strong.
Before any order is allowed, the EA runs the current bar's environment through a 7-state regime classifier in UpdateRegime(). ADX(14), ATR(14), and a Bollinger band of period 20, deviation 2.0, are all read on the closed bar. ATR in price units must clear InpATRMinPrice = 0.30 to keep the EA out of low-volatility gold sessions where spreads eat the move. If ADX reads ≥ InpADXMinTrend = 20.0 AND the Bollinger width is expanding (>5% wider than the prior bar), the regime is REG_STRONG_TREND. ADX ≥ 20 alone is REG_WEAK_TREND. Expanding width without ADX is REG_EXPAND. Compressing width is REG_COMPRESS. A width/ATR ratio above 3 is REG_BREAKOUT. Anything else is REG_RANGE, and the only hard-blocked state is REG_CHOPPY — set automatically when ATR falls below the floor. NoTradeReason() lists REGIME_CHOPPY explicitly, so a quiet market forces a flat posture.
A trade is only attempted when the no-trade gate is clean. The gate combines a maximum of InpMaxConcurrent = 3 open positions and EX_MAX_SYMBOL_POS = 3 per-symbol positions, an EX_SESSION_START-to-EX_SESSION_END server window of 08:00–22:00, the manual InpKillSwitch, the InpMaxSpreadPoints = 50 spread ceiling, the daily 3% loss cap relative to effective capital, and a one-hour cooldown triggered after EX_COOLDOWN_LOSSES = 3 consecutive losses. NewsBlock() adds two fixed blackout windows — 12:30 and 14:00 server time, each with EX_NEWS_BLOCK_MIN = 30 minutes of padding — which approximates the most common US macro release slots in a thin way that does not require an external feed. When a bar is being held (IsNewBar() returns false), the EA still updates trailing logic, but new entries are blocked — exactly one attempt per closed bar via the g_lastEntryBarTime guard.
Confirmation in Confirm() is short but disciplined. The higher-timeframe trend EMA (hHTF = iMA(InpTrendEMA = 50) on the timeframe chosen by InpHTF = 6 → PERIOD_H4) must agree with the signal direction: a BUY requires bid above the H4 EMA(50), a SELL requires bid below. The TP/SL multiple ratio InpATR_TP_Mult / InpATR_SL_Mult must be at least 1.0 (the defaults 1.5 / 1.2 = 1.25 naturally pass). The closed-bar ATR(14) must remain above the floor. If any check fails, Confirm() returns the reason string and the entry is skipped.
Position sizing is standard risk-percent: CalcLot() divides effective_capital * InpRiskPercent / 100 by the per-lot dollar loss at the entry ATR distance, then clamps to the symbol's volume step and limits. EffectiveCapital() is min(InpCapitalCapAmount, equity) when InpCapitalCapAmount > 0, else full equity; with the default 0.0 the cap is off and full equity is used. InpCapitalCapFloor = 50.0 still blocks new entries when equity is too small to size a sensible lot. MarginOK() pre-checks margin availability before trade.Buy() / trade.Sell() is dispatched. The trade helper retries once on requote/timeout.
Once in the trade, ManagePositions() runs every tick. Opposite-signal exit (EX_OPP_EXIT) closes the position immediately on a flip. Regime-change exit (EX_REGIME_EXIT) closes the position if the regime transitions into REG_RANGE or REG_CHOPPY — i.e. when the trend that justified the entry has died. Time exit fires at InpMaxBarsInTrade = 240 bars (20 hours on M5). Break-even triggers when price reaches 1R: stop is moved to entry plus the broker's stop-level in price. Partial TP closes half the position at 0.5 * InpATR_TP_Mult * ATR(14) from entry (so 0.75× ATR for the defaults). The trailing stop then ratchets at InpATRTrailMult = 2.0 × ATR, with broker stop-level respected. All modification calls go through TryModify_EX18031() with a 3-attempt loop sleeping 100 ms on requote/timeout. EX_PYRAMID_ON is hard-coded false, so adding to a winner is intentionally disabled — every entry is a fresh signal.
For tuning, the most important levers are the band multiplier (InpBandMult) and breakout distance (InpBreakDistATR). Cranking InpBandMult up to 1.2–1.5 reduces signals to the most extreme dislocations; dropping it to 0.5 increases frequency. The ADX floor (InpADXMinTrend) is the on/off switch for trend tolerance — leave it at 20 for gold's typical 18–28 ADX range, raise it to 25–30 to require a confirmed move before entries. The HTF choice (InpHTF = 6 = H4) is sensible for M5: an H1 EMA(50) tends to be too reactive on gold, while Daily works but generates signals on the daily boundary only. The TP/SL pair (InpATR_TP_Mult = 1.5, InpATR_SL_Mult = 1.2) gives a 1.25:1 R:R at the trade level, but the BE+partial+trail stack converts that to a much better realized ratio on winners. Expect a hit rate in the 35–50% range, with the partial + trail doing the heavy lifting on the win side.
A practical use case is the London–New York overlap on gold, where ATR clears 0.30 reliably and the breakout bands give 2–4 signals per session. The 08:00–22:00 server window in this EA typically aligns with that overlap depending on broker GMT offset, and the 12:30/14:00 blackouts help avoid being caught in a sudden spike on US data prints. This is not a low-spread-required system — the 50-point spread ceiling is generous — but on thin ECN accounts the spread filter can be tightened to 25–30 to avoid the after-hours widening that gold is notorious for.
Strategy Deep Dive
EX18031 measures the gap between the 10-bar EMA and the closed bar's close, then fires when that gap exceeds 0.85× ATR(14) with a strong-body candle and the prior two closes still inside the band. UpdateRegime() reads ADX(14), ATR(14), and Bollinger(20, 2.0) width on the same bar to pick one of seven states — STRONG_TREND, WEAK_TREND, RANGE, BREAKOUT, COMPRESS, EXPAND, or CHOPPY — and CHOPPY is the only state that hard-blocks entries. A daily 3% loss limit, a one-hour cooldown after three consecutive losses, the 08:00–22:00 server session, the 12:30/14:00 news blackout, the 50-point spread ceiling, and a maximum of 3 open positions on the symbol all gate the entry, with the H4 EMA(50) acting as the trend filter. In-trade management runs every tick: opposite-signal close, regime-change close on RANGE/CHOPPY, 240-bar time exit, 1R break-even, 50% partial at 0.75× ATR, and a 2.0× ATR forward-only trailing stop — all delivered through 3-attempt retry loops on requote and timeout.
Triggers on a closed bar whose close crosses the upper ATR band (EMA(10) ± 0.85 × ATR(14)) by at least 0.30 × ATR with a strong candle body (≥60% of bar range) and the previous two closes still inside the band. Shorts mirror the condition on the lower band. The high-timeframe EMA(50) on H4 must agree with the signal direction, and confidence is scored at 60 by default, +15 if the regime is a trend, +15 more if it's a strong trend.
Closes on three triggers running in parallel: opposite-signal exit when ComputeSignal() flips sign, regime-change exit when the classifier drops into REG_RANGE or REG_CHOPPY, and time exit at 240 bars on M5 (~20 hours). Partial TP closes half the position at 0.75× ATR(14) from entry, then a 2.0× ATR trailing stop ratchets forward-only above entry.
Initial stop is 1.2× ATR(14) below entry for longs / above for shorts, with a broker stop-level floor applied via StopsLevelPoints(). The stop is then moved to break-even (entry ± stop-level in price) once price reaches +1R, after which the 2.0× ATR trailing stop takes over. Pyramid is hard-coded off, so the stop only ever tightens on a single entry.
Initial take-profit is 1.5× ATR(14) from entry (1.25:1 R:R with the 1.2× ATR stop), but realized exits usually come from the half-close at 0.75× ATR combined with the 2.0× ATR trailing stop. A 1.25:1 nominal R:R is a low base — most winners will be 2–4× ATR once the trail engages, and losers cluster near the 1.2× ATR stop.
Best deployed on XAUUSD M5 with an ECN or low-spread broker (the 50-point spread ceiling is generous, but tightening it to 25–30 helps in the off-hours). The 08:00–22:00 server session targets the London–New York overlap and the morning of the New York session, with built-in 30-minute blackouts around 12:30 and 14:00 server time to dodge US macro prints. Minimum recommended balance: $100 (matches the strategy's $50 capital floor plus headroom for the 0.5% risk sizing). Risk level: MEDIUM — the 0.5% per-trade risk, daily 3% cap, and 9% weekly loss threshold keep a single bad day from running away, but the 1.25:1 base R:R means the EA needs ~45%+ hit rate to be net-positive, so the trailing stack is doing meaningful work on the winners.
Strategy Logic
Pipsgrowth EX18031 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218031
Version: 2.00
BRIEF:
Trend-following breakout above ATR band around a Gaussian EMA. ADX/ATR%/BB-width regime gates entries and sizing; signal fires on closed-bar close crossing the ATR band with strong body; HTF trend + candle strength + R/R confirm; ATR-based SL/TP with break-even, partial TP, ATR trail, regime-change and opposite-signal exits; capital allocation cap governs all risk; pyramid OFF by default. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
NormPrice()ClampVolume()StopsLevelPoints()EffectiveCapital()TodayRealizedPnL()CountMyPositions()CountSymbolPositions()IsNewBar()InSession()NewsBlock()SpreadPoints()UpdateRegime()- ...and 15 more
INTERNAL CONSTANTS (1 total):
EX_NEWS_BLOCK_MIN= 30 // +------------------------------------------------------------------+
INPUT PARAMETERS (21 total across 7 groups):
- [=== System ===]
InpDryRun=true// Dry-run mode (no live orders) - [=== System ===]
InpKillSwitch=false// Global kill switch - [=== System ===]
InpMagic=22218031// Magic number - [=== System ===]
InpTradeComment= "Psgrowth.com Expert_18031" // Trade comment - [===
Signal(Breakout-EMA) ===]InpEMALength= 10 // GaussianEMAlength (bars) - [===
Signal(Breakout-EMA) ===]InpBandMult=0.85//ATRband multiplier (ratio) - [===
Signal(Breakout-EMA) ===]InpTrendEMA= 50 //HTFtrendEMAperiod (bars) - [===
Signal(Breakout-EMA) ===]InpHTF= 6 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) //HTFtimeframe for trendEMA - [=== Regime Filter ===]
InpADXMinTrend=20.0// MinADXforStrongTrend(ratio) - [=== Regime Filter ===]
InpATRMinPrice=0.30// MinATRprice units (volatility floor) - [=== Regime Filter ===]
InpBreakDistATR=0.30// Min breakout distance (ATRmultiples) - [=== Risk & Sizing ===]
InpRiskPercent=0.5// Risk per trade (%effective_capital) - [=== Risk & Sizing ===]
InpATR_SL_Mult=1.2//ATRSL multiplier (ratio) - [=== Risk & Sizing ===]
InpATR_TP_Mult=1.5//ATRTP multiplier (ratio) - [=== Risk & Sizing ===]
InpMaxConcurrent= 3 // Max concurrent positions (int) - [=== Risk & Sizing ===]
InpDailyLossLimitPct=3.0// Daily loss limit (%effective_capital) - [=== Capital Allocation Cap ===]
InpCapitalCapAmount=0.0// Cap amount (REAL$, not notional) - [=== Capital Allocation Cap ===]
InpCapitalCapFloor=50.0// Floor below which no new entries - [=== Manage / Exit ===]
InpATRTrailMult=2.0//ATRtrailing multiplier (ratio) - [=== Manage / Exit ===]
InpMaxBarsInTrade= 240 // Max bars in trade (int, 0=off) - [=== Exec ===]
InpMaxSpreadPoints=50.0// Max allowed spread (points)
// Pipsgrowth EX18031 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Trend-following breakout above ATR band around a Gaussian EMA. ADX/ATR%/BB-width regime gates entries and sizing; signal fires on closed-bar close crossing the ATR band with strong body; HTF trend + candle strength + R/R confirm; ATR-based SL/TP with break-even, partial TP, ATR trail, regime-change and opposite-signal exits; capital allocation cap governs all risk; pyramid OFF by default. 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 |
|---|---|---|
| InpDryRun | true | Dry-run mode (no live orders) |
| InpKillSwitch | false | Global kill switch |
| InpMagic | 22218031 | Magic number |
| InpTradeComment | "Psgrowth.com Expert_18031" | Trade comment |
| InpEMALength | 10 | Gaussian EMA length (bars) |
| InpBandMult | 0.85 | ATR band multiplier (ratio) |
| InpTrendEMA | 50 | HTF trend EMA period (bars) |
| InpHTF | 6 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF timeframe for trend EMA |
| InpADXMinTrend | 20.0 | Min ADX for StrongTrend (ratio) |
| InpATRMinPrice | 0.30 | Min ATR price units (volatility floor) |
| InpBreakDistATR | 0.30 | Min breakout distance (ATR multiples) |
| InpRiskPercent | 0.5 | Risk per trade (% effective_capital) |
| InpATR_SL_Mult | 1.2 | ATR SL multiplier (ratio) |
| InpATR_TP_Mult | 1.5 | ATR TP multiplier (ratio) |
| InpMaxConcurrent | 3 | Max concurrent positions (int) |
| InpDailyLossLimitPct | 3.0 | Daily loss limit (% effective_capital) |
| InpCapitalCapAmount | 0.0 | Cap amount (REAL $, not notional) |
| InpCapitalCapFloor | 50.0 | Floor below which no new entries |
| InpATRTrailMult | 2.0 | ATR trailing multiplier (ratio) |
| InpMaxBarsInTrade | 240 | Max bars in trade (int, 0=off) |
| InpMaxSpreadPoints | 50.0 | Max allowed spread (points) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18031 EX20 — Trend-following breakout above ATR band around an EMA, 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 (TOTAL = 22) ============================================
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_InpHTF = PERIOD_H1;
input group "=== System ==="
input bool InpDryRun = true; // Dry-run mode (no live orders)
input bool InpKillSwitch = false; // Global kill switch
input long InpMagic = 22218031; // Magic number
input string InpTradeComment = "Psgrowth.com Expert_18031"; // 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;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.