Pipsgrowth EX18032 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5
Pipsgrowth.com EX18032 GB10 — EMA-cross trend EA with 12-layer spec, capital cap, ATR exits.
Overview
Pipsgrowth EX18032 is a v2.00 trend-following EA built around a single classical core — a fast/slow EMA crossover on the last closed bar — wrapped in an unusually strict five-filter confirmation gate. Where many trend EAs vote between two or three momentum conditions, EX18032 demands that every confirm agree before a position opens. The cross itself is the standard 12/26 EMA pair (InpFastEMA=12, InpSlowEMA=26) evaluated on bar[1] against bar[2] inside ComputeSignal(), so the engine only sees fully closed bars and never trades on a forming candle. That alone removes the most common entry-timing complaint in M5 EAs: signals that fire on the open and then reverse before the close.
The first confirm is the trend EMA(50) — InpTrendEMA on the same chart. A long cross is only valid if the fast EMA(12) is above the trend EMA(50) on bar[1]; a short cross is only valid below. This blocks the classic EMA-cross failure pattern where the fast line jumps above a still-downtrending slow band and immediately snaps back.
The second confirm is an inlined Heikin-Ashi color check on bar[1]: haC1 = (O+H+L+C)/4 of the closed bar versus haO1 = (O[2]+C[2])/2 of the previous raw candle. Bullish HA color (haC1 > haO1) is required to take a long; bearish HA color is required to take a short. This is the single-bar HA form, not a multi-bar walk, so it gives a fast momentum pulse rather than a smoothed trend verdict.
The third confirm is an inlined SuperTrend side computed on the same chart with a 3.0x ATR(14) multiplier. SuperTrendSide() walks back through H/L/C and the ATR buffer, maintains final-up and final-down levels, and returns +1 (price closed above the upper band) or -1 (price closed below the lower band) on bar[1]. A long needs SuperTrendSide >= 0; a short needs SuperTrendSide <= 0. Because it is rebuilt from iATR plus CopyHigh/CopyLow rather than loaded as iCustom, it leaves no extra handle behind and works on any broker that supplies clean OHLC.
The fourth confirm is the higher-timeframe agreement test. The engine computes a single EMA(50) on a user-selected HTF (InpHTF=8 falls through MapTimeframeInt's switch and resolves to PERIOD_H1, the documented fallback). The previous HTF close is compared to that EMA: long trades require the HTF close above the H1 EMA(50), shorts below. This pulls the M5 entry into line with the hourly bias without forcing a multi-timeframe indicator stack.
The fifth layer is a seven-state regime classifier inside ComputeRegime(). It reads ADX(14), ATR(14) over a 100-bar percentile rank, and Bollinger Bands(20, 2.0) width as a percentage of price. The states are STRONG_TREND (ADX >= InpADXMinTrend=20 and ATR-percentile >= 60), WEAK_TREND (ADX >= 14, the 0.7x scaled floor), EXPAND (ATR-percentile >= 85), BREAKOUT (ATR-percentile >= 70 with BB-width% > 0.0015), COMPRESS (ATR-percentile <= 20), RANGE (ATR-percentile <= 40), and CHOPPY (the residual bucket). CHOPPY is hard-blocked in OkToTrade(); RANGE and CHOPPY together knock 25 points off the confidence score. STRONG_TREND adds 15; WEAK_TREND adds 5. The base score is 70 and it never exceeds 100.
The position manager runs every tick. ManagePositions() walks PositionsTotal() from the most recent position backward, filtering by magic 22218032 and the chart symbol. For each open position it checks four exit conditions in order: opposing EMA cross (close at bid/ask with reason 'OPP_SIG'), regime collapse to CHOPPY, or bars-in-trade hitting CONST_MaxBars=288 (roughly 24 hours on M5). When none of those fire, the manager runs the standard ratchet: at +1R (InpBEtriggerR=1.0) the stop is pulled to break-even on entry plus the broker stops-level offset; at the same +1R trigger 50% of the position is closed at the +1R mark (CONST_PartialFrac=0.5) if the residual still meets the symbol's minimum lot and step; thereafter an ATR trail with InpTrailAtrMult=2.5 advances the stop behind the bid or ask but never retreats below the break-even level.
The no-trade gate in OkToTrade() is dense. It rejects when the live spread exceeds InpMaxSpreadPt=50 points, when the time falls outside the 08:00-20:00 server window defined by InpSessionStart and InpSessionEnd, when the per-magic cooldown is active, when the live open count has reached InpMaxOpen=3, when EffectiveCapital() drops below the $50 floor (InpCapFloor), or when the realized daily loss has hit -3% of effective capital or the realized weekly loss has hit -6%. EffectiveCapital() returns min(InpCapAmount, equity) plus today's realized PnL when the cap is enabled, or pure equity when InpCapAmount=0 (the default-off state). The cooldown is engaged by UpdateRealizedPnL() when it counts three or more losses in the current day — CONST_CooldownLoss=3 — and holds for CONST_CooldownHours=4 hours, after which RollDayIfNeeded() clears the streak on the next day rollover.
Sizing comes from a clean lot formula: lots = (cap * InpRiskPercent/100) / (slDist * tickValue/tickSize * point). The default risk per trade is 0.5% (InpRiskPercent=0.5), the SL distance is 1.8x ATR(14) (InpSLatrMult=1.8), and the TP is 3.6x ATR(14) (InpTPatrMult=3.6) — a 1:2 reward-to-risk that passes the CONST_RRmin=1.5 pre-trade gate. Lots are clamped to the symbol's min/max volume and rounded to the volume step. Margin is pre-checked with OrderCalcMargin before the order is sent, and TryEntry retries once on a REQUOTE or TIMEOUT retcode. Close and modify helpers TryClose_EX18032, TryClosePartial_EX18032, and TryModify_EX18032 each run up to three attempts with 200ms or 100ms sleeps on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED before giving up.
The EA defaults to InpDryRun=true, which prints intended entries and exits to the journal without sending any orders — flip it to false in the inputs panel before going live. The InpKillSwitch input halts all OnTick processing immediately. The MT5 strategy tester hook OnTester() returns (netProfit * profitFactor) / (1 + balanceDrawdownPercent) as a single composite fitness value, with a hard floor of 30 trades before the score is computed; that is the value Strategy Tester will use when running a genetic optimization pass.
The design choice that defines EX18032 is the strictness of the gate. Most M5 trend EAs of this family use either a vote threshold (three-of-four, five-of-five at 60%) or a softer confirm list. EX18032 takes the opposite approach: every one of the five confirmations must align, the regime must not be CHOPPY, the spread must be inside 50 points, and the session must be open. The expected behavior in backtest is therefore a low trade frequency with a higher per-trade quality — extended sequences of dry bars interrupted by clean directional moves. On XAUUSD M5 with a $100 minimum account, that profile suits a trader who would rather watch a few well-filtered signals per week than churn through ten mediocre ones per day.
What to expect when running it: a $100 account with the default 0.5% risk loses at most $3 on a worst day before the EA pauses itself for the rest of the session, and at most $6 across a full week. The capital cap is off by default, so EffectiveCapital() returns the full account equity; turn InpCapAmount on (e.g. set it to 300) if you want the EA to size positions against a fixed allocation rather than your full balance. A standard XAUUSD ECN or raw-spread account is required — the 50-point spread filter is too loose for wide ECN accounts on quiet sessions, and a sub-20-point spread environment is necessary for the partial-TP-at-1R mechanic to fill cleanly.
Strategy Deep Dive
Every tick OnTick rolls the day and week counters, calls ComputeRegime() to bucket the current market into one of seven states using ADX(14), the ATR(14) percentile over the last 100 bars, and Bollinger-band width as a percent of price, then runs ComputeSignal() to look for a closed-bar EMA(12)/EMA(26) cross. When a cross fires, the same function rebuilds the Heikin-Ashi color of bar[1] from raw OHLC, calls SuperTrendSide() to compute the inlined 3x ATR SuperTrend verdict on bar[1], checks the trend EMA(50) side, and reads the H1 close against the H1 EMA(50) for higher-timeframe agreement — all five must align before a +1/-1 signal is emitted and the EA attempts TryEntry. ManagePositions() runs ahead of the no-trade gate on every tick, applying the +1R break-even, the 50% partial, and the 2.5x ATR trail to each open position, and closing on opposing cross, regime collapse to CHOPPY, or the 288-bar time limit. OkToTrade() then vetoes the entry if the live spread is above 50 points, the time is outside 08:00-20:00 server, the open-count cap of three is full, EffectiveCapital() is below the $50 floor, the daily 3% or weekly 6% loss limit has been hit, or the 4-hour loss-streak cooldown is still active. When all checks pass, TryEntry sizes the lot from a 0.5% risk budget against the 1.8x ATR stop, pre-checks the margin, retries once on REQUOTE or TIMEOUT, and writes a [DRYRUN] line to the journal or sends a real order depending on the InpDryRun flag.
A long entry fires on a closed-bar EMA(12) crossing above EMA(26) when the fast EMA(12) is also above the trend EMA(50) on bar[1], the inlined Heikin-Ashi color is bullish (haC1 > haO1), the inlined SuperTrend side is >= 0, and the H1 close is above the H1 EMA(50). A short entry is the symmetric mirror. The regime must not be CHOPPY, the live spread must be at or below 50 points, the time must be inside 08:00-20:00 server, and the open-count cap of three must have headroom.
Positions are closed by any of three triggers: an opposing EMA cross (OPP_SIG), a regime collapse to CHOPPY, or a time exit at 288 bars in trade (roughly 24 hours on M5). After entry the manager runs a one-shot break-even ratchet at +1R, a 50% partial close at the +1R mark, and a 2.5x ATR(14) trail that advances behind the bid or ask but never retreats below the break-even stop.
Per-trade stop-loss is set to 1.8x ATR(14) at entry (InpSLatrMult=1.8) and honored by the broker with a minimum-distance floor at the symbol's stops level. A portfolio-level daily loss cap of 3% of effective capital and a weekly cap of 6% shut off all new entries when tripped, and a 3-loss day engages a 4-hour cooldown on the EA itself.
Initial take-profit is set to 3.6x ATR(14) at entry (InpTPatrMult=3.6) for a 1:2 reward-to-risk against the 1.8x ATR stop. Half the position is closed at the +1R mark (CONST_PartialFrac=0.5), and the residual is left to the 2.5x ATR trail with the 1.8x ATR stop as the initial anchor.
EX18032 is built for the XAUUSD M5 trader with a $100 minimum account who is comfortable with a low trade frequency and wants the trade count capped at three concurrent positions. Run it on an ECN or raw-spread XAUUSD account where the live spread is reliably under 20 points so the 50-point spread filter and the 1R partial mechanic fill cleanly, and trade during the 08:00-20:00 server window — this maps onto the London and New York sessions on most brokers and is when gold's intraday volatility is deepest. The MEDIUM risk rating reflects the 0.5% per-trade risk, the 1:2 reward-to-risk profile, and the daily 3% / weekly 6% loss caps that shut the EA off before a single bad day becomes a drawdown event.
Strategy Logic
Pipsgrowth EX18032 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218032
Version: 2.00
BRIEF:
Fast/slow EMA cross on last closed bar with trend-EMA(50) agreement. ADX + ATR-percentile + Bollinger-width regime gate; inlined HeikinAshi color + SuperTrend as optional confirm. ATR-based SL, one-shot break-even at R, 50% partial at TP1, ATR trail, regime-change and opposite-signal exits, session window. 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:
ComputeRegime()ComputeSignal()SuperTrendSide()OkToTrade()TryEntry()ManagePositions()CloseAt()TryModify()EffectiveCapital()ClampLot()CountMyOpen()InSession()- ...and 8 more
INTERNAL CONSTANTS (1 total):
- CONST_MaxBars = 288 // ==================
GLOBALS=========================================
INPUT PARAMETERS (22 total across 5 groups):
- [=== Identity & Execution ===]
InpMagic=22218032// Magic number (-) - [=== Identity & Execution ===]
InpTradeComment= "Psgrowth.com Expert_18032" // Order comment (-) - [=== Identity & Execution ===]
InpDeviation= 20 // Slippage cap (points) - [=== Identity & Execution ===]
InpMaxSpreadPt=50.0// Max spread (points) - [=== Identity & Execution ===]
InpDryRun=true// Dry-run (no real sends) - [=== Identity & Execution ===]
InpKillSwitch=false// Kill switch (disablesEA) - [=== Capital Cap & Risk ===]
InpCapAmount=0.0// Real-money cap (account $) - [=== Capital Cap & Risk ===]
InpCapFloor=50.0// Min floor to trade (account $) - [=== Capital Cap & Risk ===]
InpRiskPercent=0.5// Risk per trade (% eff.cap) - [=== Capital Cap & Risk ===]
InpDailyLossPct=3.0// Daily loss limit (% eff.cap) - [=== Capital Cap & Risk ===]
InpMaxOpen= 3 // Max concurrent trades (-) - [=== Core
Signal(EMAcross) ===]InpFastEMA= 12 // FastEMAperiod (bars) - [=== Core
Signal(EMAcross) ===]InpSlowEMA= 26 // SlowEMAperiod (bars) - [=== Core
Signal(EMAcross) ===]InpTrendEMA= 50 // TrendEMAperiod (bars) - [=== Core
Signal(EMAcross) ===]InpHTF= 8 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) //HTFtrend tf (-) - [=== Regime & Exits ===]
InpADXMinTrend=20.0// MinADXforStrongTrend(-) - [=== Regime & Exits ===]
InpSLatrMult=1.8// SL distance (xATR) - [=== Regime & Exits ===]
InpTPatrMult=3.6// TP distance (xATR) - [=== Regime & Exits ===]
InpBEtriggerR=1.0// Break-even trigger (R) - [=== Regime & Exits ===]
InpTrailAtrMult=2.5//ATRtrail multiplier (-) - [=== Session ===]
InpSessionStart= "08:00" // Session start (HH:MM server) - [=== Session ===]
InpSessionEnd= "20:00" // Session end (HH:MM server)
// Pipsgrowth EX18032 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Fast/slow EMA cross on last closed bar with trend-EMA(50) agreement. ADX + ATR-percentile + Bollinger-width regime gate; inlined HeikinAshi color + SuperTrend as optional confirm. ATR-based SL, one-shot break-even at R, 50% partial at TP1, ATR trail, regime-change and opposite-signal exits, session window. 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 |
|---|---|---|
| InpMagic | 22218032 | Magic number (-) |
| InpTradeComment | "Psgrowth.com Expert_18032" | Order comment (-) |
| InpDeviation | 20 | Slippage cap (points) |
| InpMaxSpreadPt | 50.0 | Max spread (points) |
| InpDryRun | true | Dry-run (no real sends) |
| InpKillSwitch | false | Kill switch (disables EA) |
| InpCapAmount | 0.0 | Real-money cap (account $) |
| InpCapFloor | 50.0 | Min floor to trade (account $) |
| InpRiskPercent | 0.5 | Risk per trade (% eff.cap) |
| InpDailyLossPct | 3.0 | Daily loss limit (% eff.cap) |
| InpMaxOpen | 3 | Max concurrent trades (-) |
| InpFastEMA | 12 | Fast EMA period (bars) |
| InpSlowEMA | 26 | Slow EMA period (bars) |
| InpTrendEMA | 50 | Trend EMA period (bars) |
| InpHTF | 8 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF trend tf (-) |
| InpADXMinTrend | 20.0 | Min ADX for StrongTrend (-) |
| InpSLatrMult | 1.8 | SL distance (x ATR) |
| InpTPatrMult | 3.6 | TP distance (x ATR) |
| InpBEtriggerR | 1.0 | Break-even trigger (R) |
| InpTrailAtrMult | 2.5 | ATR trail multiplier (-) |
| InpSessionStart | "08:00" | Session start (HH:MM server) |
| InpSessionEnd | "20:00" | Session end (HH:MM server) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18032 GB10 — EMA-cross trend EA with 12-layer spec, capital cap, ATR exits."
#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 ==========================================
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 "=== Identity & Execution ==="
input int InpMagic = 22218032; // Magic number (-)
input string InpTradeComment = "Psgrowth.com Expert_18032"; // Order comment (-)
input int InpDeviation = 20; // Slippage cap (points)
input double InpMaxSpreadPt = 50.0; // Max spread (points)
input bool InpDryRun = true; // Dry-run (no real sends)
input bool InpKillSwitch = false; // Kill switch (disables EA)
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;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.