Pipsgrowth EX18038 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX18038 Ichimoku — TK cross + Kumo cloud trend EA, full 12-layer stack.
Overview
Pipsgrowth EX18038 TrendFollow is an Ichimoku-driven pullback-and-trend EA built for XAUUSD on M5–H1 charts, with the 9/26/52 Tenkan/Kijun/Senkou-B triple native iIchimoku as its only signal source. Where the rest of the TrendFollow family uses inline EMA crosses, Hull, SuperTrend, KAMA, AMA, or Alligator primitives, EX18038 leaves the Ichimoku calculation to MetaTrader's compiled iIchimoku(_Symbol, _Period, InpTenkan, InpKijun, InpSenkou) handle and reads back the four buffers — Tenkan-sen (buffer 0), Kijun-sen (buffer 1), Senkou Span A (buffer 2), Senkou Span B (buffer 3) — once per new bar. That is the first design decision visible in the code: keep the indicator math where MetaTrader can vectorise it, then do the cross detection in IchimokuSignal() against last-closed-bar values only (shift 1) so no repaint ever leaks into the live book.
The IchimokuSignal() function returns +1 for long, −1 for short, 0 for no trade. A long requires tk[1] > kj[1] while tk[2] <= kj[2] (Tenkan crossing up through Kijun on the closed bar) AND close[1] > max(sA[1], sB[1]) (price closing above the top of the Kumo cloud). The short is the mirror: tk[1] < kj[1] while tk[2] >= kj[2] and close[1] < min(sA[1], sB[1]). The Kumo filter is what separates EX18038 from a plain moving-average cross — both lines have to agree on a freshly flipped cross AND price has to be on the correct side of the cloud at the close. The function also stamps a confidence of 80 in REG_STRONG_TREND and 60 in REG_WEAK_TREND, but that confidence is informational only and does not gate the entry — the regime block is enforced elsewhere.
Regime classification lives in ComputeRegime(). It reads ADX(14), ATR(14), and Bollinger Bands(20, 2.0) and combines them into six buckets: REG_STRONG_TREND when ADX ≥ 30, REG_WEAK_TREND when 20 ≤ ADX < 30, REG_COMPRESS when the Bollinger band-width ratio bwPct = (bbU[1] - bbL[1]) / bbM[1] falls below 0.015 (1.5%), REG_EXPAND when bwPct exceeds 0.045 (4.5%), REG_RANGE for the 1.5%–4.5% middle band, and REG_CHOPPY as a final override when ADX < 15. RegimeAllowsTrading() only returns true for STRONG_TREND and WEAK_TREND — EX18038 explicitly refuses to take entries in compress, range, expansion, or choppy conditions, and ManagePositions() force-closes any open position the moment the regime flips out of the two trend buckets. That is a meaningful design choice: the EA will exit a position that is still in profit if ADX drops back below 20, treating regime degradation as a higher-priority signal than the trailing stop.
Confirmation before entry runs through HTFTrend(), which reads the EMA from the higher-timeframe handle g_hHTFma = iMA(_Symbol, g_InpHTFTimeframe, InpHTF_EMA, 0, MODE_EMA, PRICE_CLOSE). The input InpHTFTimeframe defaults to 8 — that falls outside the 1–7 mapping in MapTimeframeInt() (1=M1, 2=M5, 3=M15, 4=M30, 5=H1, 6=H4, 7=D1), so the resolver falls into the default arm and the EA effectively pins itself to H1 in code, with EMA period 50. A long signal is killed if H1 close is below the H1 EMA, and a short is killed if H1 close is above it. The NoTradeReason() chain rejects on opposing HTF trend with the string HTF_TREND_OPPOSES.
The SL and TP are both ATR(14) multiples. InpSLATRMult = 2.0 puts the stop at twice ATR, and the TP is computed inline as slDist * 1.5, giving a 1:1.5 R:R structure. Both are clamped to (g_stopsLevel + 2) * g_point to respect the broker's minimum stop distance, and NormPrice() rounds to the symbol's digits.
Once a position is open, ManagePositions() runs on every tick and layers three protective mechanisms on top of the SL/TP. The break-even is a one-shot: when the floating R multiple reaches InpBETriggerR = 1.0, the stop is ratcheted to openPrice + stopsLevel*point (for longs) and never revisited. The ATR trail uses InpTrailATRMult = 2.5 — a long's new stop is bid - 2.5*atr; the trail only moves forward, never backward. The partial TP fires at InpPartialTP_R = 1.5R, closing exactly half the volume (NormVol(volume * 0.5)) provided half is at least the broker's g_volMin and strictly less than the full position, leaving the other half to run under the trailing stop. There is also a hard time exit at InpMaxBarsInTrade = 120 bars — ten hours of M5 bars — which closes the full position regardless of profit. On top of that, the opposite Ichimoku signal triggers a full close via ClosePartial() with the OPPOSITE_SIGNAL reason tag.
Risk and exposure controls run before entry. CalcLot() reads the effective capital — which is min(account_equity, InpCapitalCapAmount) if a capital cap is configured, otherwise just AccountInfoDouble(ACCOUNT_EQUITY) — and applies InpRiskPercent = 0.5% to size the position. Sizing uses the formula lot = (effCap * riskPct / 100) / (slDistance * tickValue/tickSize), then a pre-check against free margin via OrderCalcMargin(). If InpCapitalCapAmount is left at 0, the cap is disabled; if effective capital drops below InpCapitalCapFloor = 50, the EA blocks entries with the CAPITAL_BELOW_FLOOR reason. The daily loss guard is enforced by RollDayIfNeeded() — once realised P&L for the EA's magic number falls 3% of effective capital for the day, g_tradingDisabledToday is set and the next-bar signal is dropped with the DAILY_LOSS_LIMIT_HIT reason. There is no separate weekly cap; the cooldown is triggered after InpConsecLossTrigger = 3 consecutive losing closes, blocking new entries for InpCooldownMinutes = 30. InpMaxOpenTrades = 1 is unusually tight for the family — EX18038 runs a single-position book, and pyramid adds are compiled but switched off at the input level (InpPyramidMaxLevels = 0).
The no-trade filter chain in NoTradeReason() is one of the longer ones in the family and walks the same twelve checks as its siblings: kill switch, broker trade mode, capital floor, daily loss, cooldown, server-time session window (7–20 by default), manual news blackout (read from the global variable NEWS_BLOCK_UNTIL_<symbol> for InpNewsBlackoutMin minutes), Friday flat window (last 60 minutes before the weekly close), spread > 50 points, regime disallow, opposing HTF trend, stale quote (current bar time zero), stale bars (current bar more than 5× the period old), and CountMyPositions() >= InpMaxOpenTrades. Each rejection logs the specific reason tag to the journal, so a backtest can be post-mortemed by grepping the journal for BLOCKED lines.
Execution wraps the standard CTrade API with two retry layers. SendMarket() retries once on TRADE_RETCODE_REQUOTE, TRADE_RETCODE_PRICE_OFF, or TRADE_RETCODE_TIMEOUT after a g_sym.RefreshRates(). TryClose_EX18038, TryClosePartial_EX18038, and TryModify_EX18038 all run a 3-attempt loop with Sleep(200) (or 100 ms for modifies) between attempts, only retrying on requote/timeout/price-off/price-changed retcodes. Filling mode is auto-detected from the broker's SYMBOL_FILLING_MODE flag — FOK first, then IOC, then RETURN as the universal fallback — and the trade object's SetDeviationInPoints(20) allows 20 points of slippage on entry.
For the MetaTrader optimiser, OnTester() returns (net / maxDD) * profitFactor with a 10-trade floor. That criterion explicitly rewards strategies that produce profit per unit of drawdown, scaled by how well gross profit covers gross loss — a backtest that is net positive but has a brutal drawdown will score lower than a smoother equity curve with a similar net. Run any optimisation on XAUUSD M5 with at least one calendar quarter of data before reading the result as meaningful.
Two things to expect in live trading: first, EX18038 is a low-frequency EA. The Ichimoku TK cross on a single timeframe is not a frequent event, and the Kumo-cloud side filter plus the regime gate mean that on most days there will be zero entries, sometimes zero entries across an entire trading week. Second, because the trail only steps forward and break-even is a one-shot at exactly 1R, positions will sometimes sit through a 2–3R retracement before the trail catches up — that is the design, not a bug. If the operator needs faster exits, the right knob is InpTrailATRMult (lower = tighter trail), not the SL multiplier.
Strategy Deep Dive
On every new bar the EA calls ComputeRegime() first, which reads ADX(14), ATR(14), and Bollinger Bands(20, 2.0) and stamps the chart as STRONG_TREND, WEAK_TREND, COMPRESS, EXPAND, RANGE, or CHOPPY. Only STRONG_TREND and WEAK_TREND clear the trading gate. IchimokuSignal() then reads the four Ichimoku buffers from the native iIchimoku handle and fires +1 or -1 only on a freshly flipped TK cross with the close on the correct side of the Kumo cloud. HTFTrend() reads the H1 EMA(50) handle and blocks any signal that disagrees with the H1 trend direction. If the signal survives NoTradeReason() — which walks the kill switch, capital floor, daily loss limit, cooldown, server-time session window 7-20, manual news blackout, Friday flat window, 50-point spread cap, regime allow, HTF opposition, stale quotes, and max open trades — CalcLot() sizes the position at 0.5% of effective capital. ManagePositions() then runs on every tick: break-even at +1.0R, 50% partial at +1.5R, 2.5×ATR forward-only trail, opposite-signal full close, regime-flip full close, and 120-bar time exit.
EX18038 enters long when the Ichimoku Tenkan-sen crosses above the Kijun-sen on the last closed bar AND the close is above the top of the Kumo cloud (max of Senkou Span A and B). Short is the mirror: Tenkan crosses below Kijun with close below the bottom of the cloud. The signal is gated by a six-state regime classifier (only ADX ≥ 20 in STRONG or WEAK trend is allowed) and confirmed by H1 close price relative to the 50-period EMA on the H1 handle (which the EA resolves from an input default of 8 that falls through the timeframe mapper to H1).
EX18038 closes the full position on an opposite Ichimoku TK cross signal (with the OPPOSITE_SIGNAL tag), on a regime flip out of STRONG/WEAK trend (REGIME_FLIP tag), on a 120-bar time exit measured against InpMaxBarsInTrade, and on the kill switch. It also closes half the position at +1.5R as a partial TP, after which the remaining half runs under the trailing stop and break-even. The break-even is a one-shot at exactly +1.0R and the trail runs at 2.5×ATR(14), stepping forward only.
Initial stop loss = 2.0 × ATR(14) from entry, clamped to (broker stops level + 2) × point to respect minimum stop distance. The stop is then ratcheted to break-even at +1.0R (one-shot, never revisited) and trailed forward at 2.5 × ATR(14) once price is in the trailing zone.
Initial take-profit = 3.0 × ATR(14) (1.5× the SL distance for a 1:1.5 R:R), with a 50% partial close executed at +1.5R. The remaining half is left to run under the trailing stop, the regime-flip exit, the opposite-signal exit, and the 120-bar time exit. There is no fixed basket TP — the trail and the regime gate together define the effective take-profit.
EX18038 fits traders running XAUUSD on M5 or H1 who want a low-frequency, single-position Ichimoku trend follower. The $100 minimum deposit and 0.5% per-trade risk make it usable on a small retail account, but the Ichimoku TK cross + Kumo cloud + regime gate combination produces very few signals — expect several days between entries. Run on a broker with the InpMaxSpreadPoints (50) cap respected at all sessions, and trade on a server-time 7-20 schedule (set InpSessionStartHour/InpSessionEndHour to your broker's offset for London and the first half of New York). The dry-run flag is on by default — set InpDryRun=false before live deployment.
Strategy Logic
Pipsgrowth EX18038 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218038
Version: 2.00
BRIEF:
Ichimoku Tenkan/Kijun cross confirmed by price vs Kumo cloud (native iIchimoku). Entry triggers on bar close of the cross candle. ADX+ATR-pct+Bollinger-width regime classifies market; HTF EMA agreement + spread confirm; no-trade filters for spread/session/news/blackout/Friday-flat/stale-quote; fixed-fractional risk off effective capital (capital allocation cap); break-even, ATR trailing, partial TP; regime-flip, opposite-signal, time-based exits; capped pyramid OFF by default. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Ichi
ATRADXBB- HTFma
KEY FUNCTIONS:
RefreshSymbolSpecs()ResolveFillMode()NormPrice()NormVol()EffectiveCapital()TodayRealizedPnLForMagic()CountMyPositions()MyPositionVolume()ComputeRegime()RegimeAllowsTrading()IchimokuSignal()HTFTrend()- ...and 12 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (28 total across 8 groups):
- [=== Identity ===]
InpMagic=22218038// Magic number (EAisolation) - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_18038" // Order comment - [=== Risk & Sizing ===]
InpCapitalCapAmount=0.0// Cap: maxREAL-MONEY$ thisEAcommands (account ccy, not leveraged) - [=== Risk & Sizing ===]
InpCapitalCapFloor=50.0// Min effective capital required to trade at all ($) - [=== Risk & Sizing ===]
InpRiskPercent=0.5// Risk per trade (% ofEFFECTIVEcapital) - [=== Risk & Sizing ===]
InpDailyLossLimitPct=3.0// Daily loss limit (% ofEFFECTIVEcapital) -> stop for day - [=== Risk & Sizing ===]
InpMaxOpenTrades= 1 // Max concurrent open trades (this magic) - [=== Risk & Sizing ===]
InpCooldownMinutes= 30 //Cooldown(min) after consecutive losses - [=== Risk & Sizing ===]
InpConsecLossTrigger= 3 // Consecutive losses to trigger cooldown - [===
Signal(Ichimoku) ===]InpTenkan= 9 // Tenkan-sen period - [===
Signal(Ichimoku) ===]InpKijun= 26 // Kijun-sen period - [===
Signal(Ichimoku) ===]InpSenkou= 52 // Senkou Span B period - [=== Entry / Confirmation ===]
InpHTFTimeframe= 8 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Higher TF for trend agreement - [=== Entry / Confirmation ===]
InpHTF_EMA= 50 //HTFEMAperiod for trend filter - [=== No-Trade Filters ===]
InpMaxSpreadPoints= 50 // Max allowed spread (points, broker-scaled) - [=== No-Trade Filters ===]
InpNewsBlackoutMin= 0 // Manual news blackout window (min each side, 0=off) - [=== No-Trade Filters ===]
InpFridayFlatMin= 60 // Flatten Friday before close (min, 0=off) - [=== No-Trade Filters ===]
InpSessionStartHour= 7 // Session start hour (server time) - [=== No-Trade Filters ===]
InpSessionEndHour= 20 // Session end hour (server time) - [=== Trade Management & Exits ===]
InpATRPeriod= 14 //ATRperiod (SL + trailing) - [=== Trade Management & Exits ===]
InpSLATRMult=2.0// Initial SL =ATR* mult - [=== Trade Management & Exits ===]
InpBETriggerR=1.0// Move to break-even after +R multiple - [=== Trade Management & Exits ===]
InpTrailATRMult=2.5//ATRtrailing distance (mult) - [=== Trade Management & Exits ===]
InpPartialTP_R=1.5// Partial close at +R(0=off); runner trails - [=== Trade Management & Exits ===]
InpMaxBarsInTrade= 120 // Max bars in trade (time exit, 0=off) - [=== Scaling Policy ===]
InpPyramidMaxLevels= 0 // Max pyramid adds (0=OFF). Only into profit. - [=== Dry-Run / Kill ===]
InpDryRun=true// Dry-run: log only, NO orders (setfalsefor live) - [=== Dry-Run / Kill ===]
InpKillSwitch=false//KILL: flatten all (this magic) and stop
// Pipsgrowth EX18038 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Ichimoku Tenkan/Kijun cross confirmed by price vs Kumo cloud (native iIchimoku). Entry triggers on bar close of the cross candle. ADX+ATR-pct+Bollinger-width regime classifies market; HTF EMA agreement + spread confirm; no-trade filters for spread/session/news/blackout/Friday-flat/stale-quote; fixed-fractional risk off effective capital (capital allocation cap); break-even, ATR trailing, partial TP; regime-flip, opposite-signal, time-based exits; capped 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: Ichi, ATR, ADX, BB, HTFma
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 | 22218038 | Magic number (EA isolation) |
| InpTradeComment | "Psgrowth.com Expert_18038" | Order comment |
| InpCapitalCapAmount | 0.0 | Cap: max REAL-MONEY $ this EA commands (account ccy, not leveraged) |
| InpCapitalCapFloor | 50.0 | Min effective capital required to trade at all ($) |
| InpRiskPercent | 0.5 | Risk per trade (% of EFFECTIVE capital) |
| InpDailyLossLimitPct | 3.0 | Daily loss limit (% of EFFECTIVE capital) -> stop for day |
| InpMaxOpenTrades | 1 | Max concurrent open trades (this magic) |
| InpCooldownMinutes | 30 | Cooldown (min) after consecutive losses |
| InpConsecLossTrigger | 3 | Consecutive losses to trigger cooldown |
| InpTenkan | 9 | Tenkan-sen period |
| InpKijun | 26 | Kijun-sen period |
| InpSenkou | 52 | Senkou Span B period |
| InpHTFTimeframe | 8 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Higher TF for trend agreement |
| InpHTF_EMA | 50 | HTF EMA period for trend filter |
| InpMaxSpreadPoints | 50 | Max allowed spread (points, broker-scaled) |
| InpNewsBlackoutMin | 0 | Manual news blackout window (min each side, 0=off) |
| InpFridayFlatMin | 60 | Flatten Friday before close (min, 0=off) |
| InpSessionStartHour | 7 | Session start hour (server time) |
| InpSessionEndHour | 20 | Session end hour (server time) |
| InpATRPeriod | 14 | ATR period (SL + trailing) |
| InpSLATRMult | 2.0 | Initial SL = ATR * mult |
| InpBETriggerR | 1.0 | Move to break-even after +R multiple |
| InpTrailATRMult | 2.5 | ATR trailing distance (mult) |
| InpPartialTP_R | 1.5 | Partial close at +R (0=off); runner trails |
| InpMaxBarsInTrade | 120 | Max bars in trade (time exit, 0=off) |
| InpPyramidMaxLevels | 0 | Max pyramid adds (0=OFF). Only into profit. |
| InpDryRun | true | Dry-run: log only, NO orders (set false for live) |
| InpKillSwitch | false | KILL: flatten all (this magic) and stop |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18038 Ichimoku — TK cross + Kumo cloud 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>
//==================================================================
// INPUTS (22 inputs, grouped per §3.4)
//==================================================================
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_InpHTFTimeframe = PERIOD_H1;
input group "=== Identity ==="
input int InpMagic = 22218038; // Magic number (EA isolation)
input string InpTradeComment = "Psgrowth.com Expert_18038"; // Order 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.