Pipsgrowth EX18045 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5
Pipsgrowth.com EX18045 HA2 Simple -- minimal HeikinAshi color-flip trend EA, full 12-layer stack.
Overview
Pipsgrowth EX18045 (TrendFollow v2.00, magic 22218045) is built around a stripped-down HeikinAshi colour-flip engine. It does not pull a HeikinAshi buffer from any built-in indicator; instead, the OnTick handler rebuilds the entire HA candle stack bar by bar from the raw MQL5 time-series calls (CopyOpen / CopyHigh / CopyLow / CopyClose), then watches the colour transition between the second-to-last closed HA candle and the most recently closed HA candle. A red candle that becomes green returns sig = +1, a green candle that becomes red returns sig = -1, and a same-colour pair returns 0. The base confidence stamp is 55, then the function computes body-to-range ratio on the closed signal bar (MathAbs(haClose[1] - haOpen[1]) divided by the highest-high minus lowest-low of that same bar) and adds that ratio scaled by 45, so a strong full-body candle pushes confidence to 100 and a doji-like candle leaves it at 55. No moving average, oscillator, or volatility measurement is read for the signal itself — colour flip plus body strength is the entire entry thesis.
That simplicity is then buried under a thick regime filter. DetectRegime() reads ADX(14), ATR(14) and Bollinger Bands(20, 2.0) and classifies the market into seven possible labels. StrongTrend requires ADX >= 25 and ATR-percentile above 0.7 (the percentile is computed against the most recent 50 ATR values, not a fixed threshold); WeakTrend is the same ADX gate without the volatility confirm. Compress triggers when the percentile drops below 0.25 and Bollinger width is positive; Expand is the symmetric mirror above 0.75. Breakout requires ATR-percentile above 0.6 plus ADX above 18, Choppy triggers when ADX drops below 15, and everything else is Range. OnTick only accepts entries when the regime is StrongTrend, WeakTrend or Breakout — and even in those regimes the call still has to clear two confirm gates inside ConfirmSignal() before any size is calculated. The first gate checks that the current Bid is on the correct side of the H1 EMA(50) for the proposed direction (long needs price above, short needs price below); the second gate checks that the actual M5 candle closed in the right direction (close > open for long, close < open for short). A failed confirm prints the reason — 'HTF trend not up', 'signal bar not bullish close' — and the cycle ends without a position.
The no-trade gate in CanTrade() is unusually busy. It checks the kill-switch flag, walks the realised-today/realised-week PnL history for this magic against the daily 3% and weekly 9% loss caps, enforces the 30-minute cooldown that OnTradeTransaction arms after three consecutive losses, refuses trades when the broker's current spread exceeds InpMaxSpreadPoints = 50 points, refuses when total positions for the EA have reached 5, refuses when symbol exposure has reached 3, blocks Saturdays, Sundays and Friday after 22:00 server time, blocks a 15-minute news window around 12:30 server time, a 10-minute window around 13:55, and a 5-minute window after 14:00, and finally blocks the 23:00 to 01:00 server-time window for low liquidity. The news-window and low-liquidity blocks are unusual inside this family — most siblings let the broker hours do the filtering.
Position math is conventional for the family. SL distance is 1.5×ATR(14), TP distance is 3.0×ATR(14), giving a fixed 1:2 reward-to-risk ratio that ComputeLevels() also validates against InpRRMin = 1.5. Lot sizing in ComputeLotSize() takes 0.5% of the EffectiveCapital (which is min(account equity, InpCapitalCapAmount) when the cap is on, otherwise raw equity, with a $50 floor below which no new entries are allowed), divides it by the per-lot loss implied by the SL distance in points, and clamps the result to the broker's volume step / min / max and the InpMaxLotSize = 10 ceiling. OpenTrade() calls OrderCalcMargin to pre-check that the account's free margin covers the new order, then sends with m_trade.Buy / m_trade.Sell using the auto-detected filling policy and a 20-point deviation. There is a single retry on requote, timeout or price-off, refreshing the symbol rates first.
ManageOpenPositions() runs every tick and walks the positions owned by this magic. The first check is the 60-bar time stop (InpMaxBarsInTrade = 60 is much shorter than the 200- to 288-bar exits seen on siblings in the same family). The second check force-closes if the regime has rolled into Choppy or Range. The third check is a volatility-spike exit that closes the trade if the current ATR is more than 2.5× the ATR observed at entry — a stop-loss on a runaway volatility event, distinct from the standard opposite-signal exit. After those gates, the function evaluates the live R-multiple; when rMultiple >= InpBreakevenAtR = 1.0 it ratchets the stop to the entry price (one-shot, no further BE adjustments). At the half-distance to the full TP, the partial close fires: it attempts to close InpPartialTPPct = 50% of the position, but only if the remaining volume stays above the broker's minimum lot. Finally, the ATR trail at 2.5×ATR(14) is applied forward-only — for longs, the new stop is the current bid minus the trail distance, and it only replaces the existing stop if it is higher than the current stop and above the entry price. The function never lowers a stop in either direction.
A few design choices deserve to be called out for traders sizing this up. First, the signal is intentionally minimal — a single HeikinAshi flip — so the EA will take entries in a StrongTrend or Breakout regime that other EAs in the family would not have entered because they require three or four voting indicators to align. Expect more trades, smaller individual edge. Second, the vol-spike exit means the position can close in loss during a fast spike even if the stop is not yet hit, because the entry-time ATR is the reference — a sudden 2.5× volatility event is treated as a structural break, not as a stop-hunt. Third, the 30-minute cooldown after three consecutive losses is much shorter than the 4-hour lockout some siblings use, so the EA is more willing to re-engage after a drawdown streak. Fourth, the 9% weekly loss cap is one of the looser caps in the family — it accepts a larger drawdown envelope in exchange for not blocking the strategy during its recovery. Finally, the default InpDryRun is true, so the EA logs every entry, partial, modify and close as a DRYRUN line to the journal until the user flips the flag to false. The user has to consciously go live.
Strategy Deep Dive
On every tick ManageOpenPositions() walks the EA's open positions on the current symbol and applies the 60-bar time stop, the Choppy/Range regime close, the 2.5×ATR-entry volatility-spike close and the opposite-HeikinAshi-signal close before any trailing work. On a new bar the OnTick path calls DetectRegime() to gate the entry, then GetHeikinAshiSignal() to read the inline HA colour flip plus its body-strength confidence, then ConfirmSignal() to verify the H1 EMA(50) trend agreement and the M5 candle-close direction. ComputeLevels() and ComputeLotSize() derive 1.5×ATR SL, 3.0×ATR TP and the 0.5%-of-effective-capital lots, after which OpenTrade() pre-checks margin via OrderCalcMargin and sends with the auto-detected filling policy and a 20-point deviation. During the trade, the 1R break-even, the 50% partial at the TP mid-distance and the 2.5×ATR forward trail progressively tighten the stop; CanTrade() blocks new entries whenever the daily 3% or weekly 9% loss caps, the 30-minute cooldown, the 50-point spread cap, the news windows, the Friday-22 close, the weekend, or the 23:00-01:00 low-liquidity window fires. A 9% weekly cap is the looser side of the family, but the regime filter and dual confirm still keep entries selective.
Entries fire on a HeikinAshi colour-flip on the last closed M5 bar, computed inline from raw OHLC (red → green returns +1, green → red returns -1, with base confidence 55 boosted up to 100 by the closed-bar body-to-range ratio). The signal is only acted on when DetectRegime() returns StrongTrend, WeakTrend or Breakout, and only after ConfirmSignal() validates the higher-timeframe H1 EMA(50) trend agreement and the M5 signal-bar close direction. No new entries can fire on a bar that has already triggered an entry in this session (duplicate-entry guard keyed by closed-bar time).
Exits combine a 60-bar time stop, a Choppy/Range regime-change forced close, a volatility-spike close when the current ATR is more than 2.5× the entry-time ATR, and an opposite-HeikinAshi-signal close. A 50% partial close fires when price reaches the mid-distance to the full TP, provided the remaining volume stays above the broker minimum lot. A 1R break-even one-shot ratchets the stop to the entry price, and a forward-only 2.5×ATR(14) trail ratchets the stop on every tick after that.
Per-trade stop is 1.5×ATR(14) in price terms, placed at the entry ask for longs (minus SL distance) and the entry bid for shorts (plus SL distance). ComputeLevels() also enforces a minimum-distance floor from the broker's stops-level and a 1.5 R:R minimum against TP, so entries that would violate either are rejected before the order is sent.
Per-trade take-profit is 3.0×ATR(14), giving a fixed 1:2 reward-to-risk ratio against the 1.5×ATR stop. TP is set at the entry ask (plus TP distance) for longs and the entry bid (minus TP distance) for shorts, with the partial-close leg firing at the half-distance to that target.
Pairs best with XAUUSD on M5 with a $100 minimum account, sized at the 0.5% per-trade risk that the EA uses for its lot math. The 50-point spread cap and the 12:30 / 14:00 server-time news windows mean a low-spread ECN or RAW broker with sub-50ms latency is required. Trades are effectively confined to the active hours between 01:00 and 23:00 server time, with hard blocks on Friday after 22:00, the weekend, the 23:00-01:00 low-liquidity window and the three news-blackout bands; this is built for the London and New York cash sessions, not for Asian range scalping. The MEDIUM risk rating reflects the 0.5% per-trade risk and 3% daily / 9% weekly loss caps, with a 30-minute cooldown after 3 consecutive losses rather than a multi-hour lockout.
Strategy Logic
Pipsgrowth EX18045 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218045
Version: 2.00
BRIEF:
Minimal HeikinAshi color on the last CLOSED bar is the core signal, inlined from CopyOpen/High/Low/Close. Entries gated by ADX+ATR-pct+Bollinger-width regime filter (only StrongTrend/WeakTrend/Breakout permitted), 2-confirm requirement (HTF trend + candle-close direction), full no-trade gate, ATR-based hard SL/TP, break-even, 50% partial TP, ATR trailing, max-bars exit, regime-change exit, opposite-signal exit. Capital Allocation Cap drives all risk math. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
ADXATRBB- MA
MAHTF
KEY FUNCTIONS:
EffectiveCapital()UpdateDayBookkeeping()DailyLossDollars()WeeklyLossDollars()AboveDailyLossLimit()AboveWeeklyLossLimit()CanTrade()DetectRegime()GetHeikinAshiSignal()ConfirmSignal()ComputeLevels()ComputeLotSize()- ...and 11 more
INTERNAL CONSTANTS (1 total):
ADX_STRONG_TREND=25.0// ==============================INPUTS==============================
INPUT PARAMETERS (24 total across 7 groups):
- [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_18045" // Trade comment - [=== System ===]
InpDryRun=true// Dry-run mode (no real sends) - [=== System ===]
InpKillSwitch=false// Global kill switch - [=== Capital Allocation
Cap(§4.6) ===]InpCapitalCapAmount=0.0// Cap amount ($, real money equity) - [=== Capital Allocation
Cap(§4.6) ===]InpCapitalCapFloor=50.0// Floor below which no new entries ($) - [=== Risk & Sizing ===]
InpRiskPercent=0.5// Risk per trade (% of effective capital) - [=== Risk & Sizing ===]
InpDailyLossLimitPercent=3.0// Daily loss limit (% of effective capital) - [=== Risk & Sizing ===]
InpWeeklyLossLimitPercent=9.0// Weekly loss limit (% of effective capital) - [=== Risk & Sizing ===]
InpMaxLotSize=10.0// Max lot size (lots) - [=== Risk & Sizing ===]
InpMaxConcurrentTrades= 5 // Max concurrent trades (count) - [=== Risk & Sizing ===]
InpMaxSymbolExposure= 3 // Max open trades on this symbol (count) - [=== Risk & Sizing ===]
InpMaxSpreadPoints= 50 // Max allowed spread (points) - [=== Risk & Sizing ===]
InpCooldownLosses= 3 // Cooldown after N consecutive losses - [=== Signal & Entry ===]
InpHALookback= 100 //HeikinAshicalc lookback (bars) - [=== SL / TP / Manage ===]
InpSLATRMult=1.5// SL distance (xATR) - [=== SL / TP / Manage ===]
InpTPATRMult=3.0// TP distance (xATR) - [=== SL / TP / Manage ===]
InpRRMin=1.5// Min reward:risk to enter - [=== SL / TP / Manage ===]
InpBreakevenAtR=1.0// Move to break-even at R multiple - [=== SL / TP / Manage ===]
InpPartialTPPct= 50 // Partial TP percent (%) - [=== SL / TP / Manage ===]
InpTrailATRMult=2.5//ATRtrailing multiplier (xATR) - [=== SL / TP / Manage ===]
InpMaxBarsInTrade= 60 // Max bars in trade (bars) - [=== Regime ===]
InpADXPeriod= 14 //ADXperiod (bars) - [=== Regime ===]
InpATRPeriod= 14 //ATRperiod (bars) - [=== Regime ===]
InpBBPeriod= 20 // Bollinger Bands period (bars)
// Pipsgrowth EX18045 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Minimal HeikinAshi color on the last CLOSED bar is the core signal, inlined from CopyOpen/High/Low/Close. Entries gated by ADX+ATR-pct+Bollinger-width regime filter (only StrongTrend/WeakTrend/Breakout permitted), 2-confirm requirement (HTF trend + candle-close direction), full no-trade gate, ATR-based hard SL/TP, break-even, 50% partial TP, ATR trailing, max-bars exit, regime-change exit, opposite-signal exit. Capital Allocation Cap drives all risk math. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
ON_INIT:
Create indicator handles: ADX, ATR, BB, MA, MAHTF
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 |
|---|---|---|
| InpTradeComment | "Psgrowth.com Expert_18045" | Trade comment |
| InpDryRun | true | Dry-run mode (no real sends) |
| InpKillSwitch | false | Global kill switch |
| InpCapitalCapAmount | 0.0 | Cap amount ($, real money equity) |
| InpCapitalCapFloor | 50.0 | Floor below which no new entries ($) |
| InpRiskPercent | 0.5 | Risk per trade (% of effective capital) |
| InpDailyLossLimitPercent | 3.0 | Daily loss limit (% of effective capital) |
| InpWeeklyLossLimitPercent | 9.0 | Weekly loss limit (% of effective capital) |
| InpMaxLotSize | 10.0 | Max lot size (lots) |
| InpMaxConcurrentTrades | 5 | Max concurrent trades (count) |
| InpMaxSymbolExposure | 3 | Max open trades on this symbol (count) |
| InpMaxSpreadPoints | 50 | Max allowed spread (points) |
| InpCooldownLosses | 3 | Cooldown after N consecutive losses |
| InpHALookback | 100 | HeikinAshi calc lookback (bars) |
| InpSLATRMult | 1.5 | SL distance (x ATR) |
| InpTPATRMult | 3.0 | TP distance (x ATR) |
| InpRRMin | 1.5 | Min reward:risk to enter |
| InpBreakevenAtR | 1.0 | Move to break-even at R multiple |
| InpPartialTPPct | 50 | Partial TP percent (%) |
| InpTrailATRMult | 2.5 | ATR trailing multiplier (x ATR) |
| InpMaxBarsInTrade | 60 | Max bars in trade (bars) |
| InpADXPeriod | 14 | ADX period (bars) |
| InpATRPeriod | 14 | ATR period (bars) |
| InpBBPeriod | 20 | Bollinger Bands period (bars) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18045 HA2 Simple -- minimal HeikinAshi color-flip trend EA, 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>
#define EA_MAGIC 22218045
#define EA_VERSION "2.00"
#define EA_FAMILY "TrendFollow"
#define ADX_STRONG_TREND 25.0
//============================== INPUTS ==============================
input group "=== Identity ==="
input string InpTradeComment = "Psgrowth.com Expert_18045"; // Trade comment
input group "=== System ==="
input bool InpDryRun = true; // Dry-run mode (no real sends)
input bool InpKillSwitch = false; // Global kill switch
input group "=== Capital Allocation Cap (§4.6) ==="
// InpCapitalCapEnabled removed — use InpCapitalCapAmount=0 to disable // Enable capital cap
input double InpCapitalCapAmount = 0.0; // Cap amount ($, real money equity)
input double InpCapitalCapFloor = 50.0; // Floor below which no new entries ($)
input group "=== Risk & Sizing ==="
input double InpRiskPercent = 0.5; // Risk per trade (% of effective capital)
input double InpDailyLossLimitPercent = 3.0; // Daily loss limit (% of effective capital)
input double InpWeeklyLossLimitPercent= 9.0; // Weekly loss limit (% of effective capital)
input double InpMaxLotSize = 10.0; // Max lot size (lots)
input int InpMaxConcurrentTrades = 5; // Max concurrent trades (count)
input int InpMaxSymbolExposure = 3; // Max open trades on this symbol (count)
input int InpMaxSpreadPoints = 50; // Max allowed spread (points)
input int InpCooldownLosses = 3; // Cooldown after N consecutive losses
input group "=== Signal & Entry ==="
input int InpHALookback = 100; // HeikinAshi calc lookback (bars)
input group "=== SL / TP / Manage ==="
input double InpSLATRMult = 1.5; // SL distance (x ATR)
input double InpTPATRMult = 3.0; // TP distance (x ATR)
input double InpRRMin = 1.5; // Min reward:risk to enter
input double InpBreakevenAtR = 1.0; // Move to break-even at R multiple
input int InpPartialTPPct = 50; // Partial TP percent (%)
input double InpTrailATRMult = 2.5; // ATR trailing multiplier (x ATR)
input int InpMaxBarsInTrade = 60; // Max bars in trade (bars)
input group "=== Regime ==="
input int InpADXPeriod = 14; // ADX period (bars)
input int InpATRPeriod = 14; // ATR period (bars)
input int InpBBPeriod = 20; // Bollinger Bands period (bars)
//============================== GLOBALS =============================
CTrade m_trade;
CPositionInfo m_position;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.