Pipsgrowth EX18002 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX18002 Ichi_ATR_EA — Ichimoku + ATR trend-following EA, full 12-layer stack.
Overview
EX18002 Ichi_ATR_EA is a single-position trend-following system that reads the Ichimoku Kinko Hyo cloud on the working timeframe and confirms every signal with a higher-timeframe EMA, a multi-input regime classifier, and an ATR-derived risk envelope. The strategy is not a generic 'open on cross' rule. The entry code in ComputeSignal() rejects a Tenkan/Kijun crossover unless the closed bar's close price sits on the correct side of the projected kumo (Senkou Span A vs Senkou Span B at the closed bar). A bullish cross that prints inside or below the cloud returns no signal; a bearish cross above the cloud is ignored. When both conditions align, the entry confidence is 75; a cross against the cloud still produces a direction but at 50, so the engine prefers cloud-aligned setups when it can.
The regime layer in ComputeRegime() classifies the market into seven states (STRONG_TREND, WEAK_TREND, RANGE, BREAKOUT, COMPRESS, EXPAND, CHOPPY) using three signals read from the ADX(14), ATR(14), and Bollinger Bands(20, 2.0): the absolute ADX level, the current ATR's percentile rank over the prior 100 bars, and whether the Bollinger band width is expanding. STRONG_TREND fires when ADX crosses 30; WEAK_TREND uses the configurable InpADXThreshold (20.0 default). COMPRESS triggers when Bollinger width falls below 4% of midline and is not expanding. BREAKOUT and EXPAND fire when ATR-percentile is above 60% and bands are widening. CHOPPY locks entries out entirely when ADX drops below 15. Only four regime states allow new entries: STRONG_TREND, WEAK_TREND, BREAKOUT, and EXPAND — the others short-circuit TryEntry().
The confirm step in CheckConfirm() reads a higher-timeframe EMA(50) on the InpHTF timeframe (default index 8, mapping to H1) and refuses any entry where the higher-TF close is on the wrong side of that EMA. The same function enforces a minimum reward-to-risk ratio through InpMinRR (1.5 default): the engine computes the SL distance as ATR × 1.5 and the TP distance as ATR × 2.5, and if the resulting RR falls below 1.5 the signal is discarded. The position-size call in CalcLots() then sizes the trade off effective_capital, not raw equity: when InpCapAmount is set above zero, effective capital is the lesser of the configured cap and the live account equity. Below InpCapFloor (50.0) the engine refuses to open anything at all.
The no-trade gate in CheckNoTrade() runs before every entry. It enforces a weekend block (Saturday/Sunday), a 7-to-21 server-time window (the London-through-NY active session), a rolling-spread filter that compares the current spread to a 50-bar mean and rejects it once the multiple exceeds 3.0×, a daily-loss cap of 3% of effective capital, a weekly-loss cap of 6%, the InpMaxConcurrent ceiling (1 default), a kill switch, and a hard broker check (SYMBOL_TRADE_MODE_DISABLED). OnTradeTransaction() tracks consecutive losses; once g_consecLosses reaches InpCooldownLosses (3 default) it sets a 10-bar cooldown timer and clears the counter.
Management runs on every tick, not just on a new bar. ManageOpenPositions() runs five exit paths in sequence. Exit 1 closes the trade when the current signal flips to the opposite direction. Exit 2 closes after 200 bars in trade (MAX_BARS_IN_TRADE). Exit 3 takes a 50% partial close at +1R profit, leaving the remainder to trail. Exit 4 moves the stop to breakeven — slightly above entry on buys, slightly below on sells — once price travels +1R. Exit 5 then engages a pure ATR trail: as price moves in profit, the stop follows at ATR × InpTrailATRFactor (2.0 default), and only ratchets forward (never backward). The order-execution path in SendOrder() does a margin pre-check, respects the broker's stops-level and freeze-level distances, and retries once on TRADE_RETCODE_REQUOTE, TRADE_RETCODE_TIMEOUT, or TRADE_RETCODE_PRICE_CHANGED after a 200ms sleep. Modify, close, and partial-close helpers (TryModify_EX18002, TryClose_EX18002, TryClosePartial_EX18002) each do up to three attempts on requote/timeout before giving up.
The risk model is fixed-fractional at 0.5% of effective capital per trade by default (InpRiskPercent). With a 1.5×ATR stop on XAUUSD M5, that risk budget maps to a small lot fraction on a $1,000 account. The combined effect of the 3% daily loss cap, 6% weekly cap, 200-bar time exit, and BE+trail on the open side keeps the worst-case per-trade damage bounded: a single adverse position is closed either by stop, by time, or by an opposite signal before it can compound into a larger drawdown. The OnTester() formula is (netProfit × profitFactor) / (1 + equityDDPct), and it requires at least 30 trades before it returns a nonzero score, so the optimizer will not reward a backtest that produced too few fills to be meaningful.
Because the strategy holds one position at a time and respects a hard 7-to-21 session window, the typical exposure profile is a small handful of trades per week on the M5 default and slightly more on M15. InpDryRun is true by default, so the EA logs intended orders to the journal without sending them — flip it to false once the live account, magic, and capital cap are configured for the symbol you intend to trade.
Strategy Deep Dive
On every tick, OnTick() refreshes the symbol info, calls ComputeSignal() to read the Ichimoku TK cross and kumo-side bias, and hands the result to ManageOpenPositions() so the existing position can be trailed, partially closed, or flipped out before any new-bar logic runs. New-bar work calls ComputeRegime() to bucket the market into one of seven states, reads effective capital, and then runs CheckNoTrade() to enforce session, spread, daily, weekly, capital-cap, and cooldown rules. The 7-state regime gate is the central filter: only STRONG_TREND, WEAK_TREND, BREAKOUT, and EXPAND advance past it. ComputeSignal() then re-evaluates the Ichimoku cross on the closed bar with the cloud-side check layered on top; CheckConfirm() pulls the higher-timeframe EMA(50) and validates the ATR-derived RR; CalcLots() sizes the order to 0.5% of effective capital (subject to the cap/floor) and SendOrder() does the margin pre-check and posts the order with a 200ms retry on requote/timeout.
Entry fires only on a new bar of the working timeframe. ComputeSignal() waits for a Tenkan/Kijun cross on the closed bar that agrees with the projected Ichimoku kumo side (close above the cloud top for longs, below the cloud bottom for shorts). The cross must coexist with a regime in {STRONG_TREND, WEAK_TREND, BREAKOUT, EXPAND}, an HTF-EMA(50) alignment in the trade direction, and a reward-to-risk ratio of at least InpMinRR (1.5 default) given the ATR(14)-based SL/TP distances. Daily, weekly, session, spread, capital-cap, and cooldown gates in CheckNoTrade() all run before the order is sent.
ManageOpenPositions() runs on every tick and applies five exit paths. Exit 1 closes on an opposite-direction signal from ComputeSignal(). Exit 2 force-closes after MAX_BARS_IN_TRADE (200 bars). Exit 3 closes 50% of the position at +1R (PARTIAL_TP_R × PARTIAL_TP_PCT) and lets the remainder run. Exit 4 moves the stop to breakeven at +1R. Exit 5 then trails the stop at ATR(14) × InpTrailATRFactor (2.0 default), ratcheting forward only.
Initial stop = ATR(14) × InpATRSLFactor (1.5 default). On a buy, SL = entry - 1.5×ATR; on a sell, SL = entry + 1.5×ATR. The broker's SYMBOL_TRADE_STOPS_LEVEL and SYMBOL_TRADE_FREEZE_LEVEL are respected — if the SL would sit inside the stops-distance it is clamped outward. Once price reaches +1R, ManageOpenPositions() lifts the stop to breakeven (entry + max(stopsLevel, 2 points) on buys, entry - the same on sells), and the ATR trail takes over from there.
Initial take-profit = ATR(14) × InpATRTPFactor (2.5 default), giving ~1.67:1 RR by construction given the 1.5×ATR stop. CheckConfirm() refuses the entry outright if tpDist / slDist drops below InpMinRR (1.5). There is no basket-level TP — the TP is a per-trade limit on the order itself. A 50% partial close at +1R is layered on top of the static TP through ManageOpenPositions() Exit 3, so winners usually realize before the full TP is reached.
Minimum recommended balance: $100 (the EA's default capital cap floor is 50 USD and 0.5% risk per trade produces a fractional lot on a small book). Designed for XAUUSD on M5–H1; the default HTF filter at H1 makes the strategy well-suited to traders who want intraday Ichimoku bias with a higher-timeframe agreement check. Risk level is MEDIUM by design — 0.5% per trade, 3% daily cap, 6% weekly cap, single concurrent position, and a 200-bar hard time exit. Run on an ECN or RAW-spread account during the 7-to-21 server-time window so the spread and stops-level filters do not over-block entries. InpDryRun is true by default, which means the EA prints intended orders to the journal without sending them; set it to false before going live.
Strategy Logic
Pipsgrowth EX18002 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218002
Version: 2.00
BRIEF:
Tenkan/Kijun cross on CLOSED bar + Ichimoku kumo-side bias + ADX/ATR-percentile/BB-width regime gate + HTF-EMA agreement + session/spread/no-trade filters + ATR-based SL/TP + break-even/partial-TP/ATR-trail + opposite-signal/regime/ time exits. All sizing off effective_capital (Capital Cap). 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
ATR- Ichi
ADXBBHTFEMA
KEY FUNCTIONS:
NormalizePrice()EffectiveCapital()ClampVolume()StopsLevelPrice()FreezeLevelPrice()NewBar()CopyBufSafe()DailyRealizedPnL()WeeklyRealizedPnL()CalcLots()CountOpenPositions()ComputeRegime()- ...and 8 more
INTERNAL CONSTANTS (16 total):
ATR_PERIOD= 14 //ATRperiod (price-distance SL/TP/trail)ADX_PERIOD= 14 //ADXperiod for regimeBB_PERIOD= 20 // Bollinger period (BBwidth regime)BB_DEVIATION=2.0// Bollinger deviationATRPCT_LOOKBACK= 100 //ATR-percentile lookbackHTF_EMA_PERIOD= 50 //HTFtrendEMAperiodBE_AT_R=1.0// Break-even trigger at 1R profitPARTIAL_TP_R=1.0// PartialTP(50%) at 1RPARTIAL_TP_PCT= 50 // Partial close percentageMAX_BARS_IN_TRADE= 200 // Hard time exit (bars)SPREAD_ROLL_AVG_BARS= 50 // Rolling spread average windowSPREAD_MAX_MULT=3.0// Max spread multiple vs rolling avgCOOLDOWN_BARS= 10 // Bars to cool down after N lossesSLIPPAGE_POINTS= 30 // Order slippage in pointsSESSION_START_HOUR= 7 // London/NY active session start (server time)- ...and 1 more
INPUT PARAMETERS (20 total across 6 groups):
- [=== Identity ===]
InpMagic=22218002// Magic number - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_18002" // Trade comment - [=== Identity ===]
InpDryRun=true// Dry-run (no live orders) - [=== Identity ===]
InpKillSwitch=false// Kill switch (block all) - [=== Risk & Sizing ===]
InpRiskPercent=0.5// Risk per trade (% ofeffective_capital) - [=== Risk & Sizing ===]
InpDailyLossLimit=3.0// Max daily loss (% ofeffective_capital) - [=== Risk & Sizing ===]
InpWeeklyLossLimit=6.0// Max weekly loss (% ofeffective_capital) - [=== Risk & Sizing ===]
InpMaxConcurrent= 1 // Max concurrent trades (this magic/symbol) - [=== Risk & Sizing ===]
InpCooldownLosses= 3 // Cooldown after N consecutive losses - [=== Capital Cap ===]
InpCapAmount=0.0// Cap amount (real money $) - [=== Capital Cap ===]
InpCapFloor=50.0// Floor below which entries block - [===
Signal(Ichimoku) ===]InpTenkan= 9 // Tenkan-sen period - [===
Signal(Ichimoku) ===]InpKijun= 21 // Kijun-sen period - [===
Signal(Ichimoku) ===]InpSenkouB= 52 // Senkou Span B period - [=== Regime / Confirm ===]
InpADXThreshold=20.0//ADXthreshold (trend strength) - [=== Regime / Confirm ===]
InpHTF= 8 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) //HTFfor trend agreement - [=== Regime / Confirm ===]
InpMinRR=1.5// Min reward:risk ratio - [=== Exit / Manage ===]
InpATRSLFactor=1.5//ATRfactor for SL distance - [=== Exit / Manage ===]
InpATRTPFactor=2.5//ATRfactor for TP distance - [=== Exit / Manage ===]
InpTrailATRFactor=2.0//ATRtrailing distance factor
// Pipsgrowth EX18002 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Tenkan/Kijun cross on CLOSED bar + Ichimoku kumo-side bias + ADX/ATR-percentile/BB-width regime gate + HTF-EMA agreement + session/spread/no-trade filters + ATR-based SL/TP + break-even/partial-TP/ATR-trail + opposite-signal/regime/ time exits. All sizing off effective_capital (Capital Cap). 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
ON_INIT:
Create indicator handles: ATR, Ichi, ADX, BB, HTFEMA
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 | 22218002 | Magic number |
| InpTradeComment | "Psgrowth.com Expert_18002" | Trade comment |
| InpDryRun | true | Dry-run (no live orders) |
| InpKillSwitch | false | Kill switch (block all) |
| InpRiskPercent | 0.5 | Risk per trade (% of effective_capital) |
| InpDailyLossLimit | 3.0 | Max daily loss (% of effective_capital) |
| InpWeeklyLossLimit | 6.0 | Max weekly loss (% of effective_capital) |
| InpMaxConcurrent | 1 | Max concurrent trades (this magic/symbol) |
| InpCooldownLosses | 3 | Cooldown after N consecutive losses |
| InpCapAmount | 0.0 | Cap amount (real money $) |
| InpCapFloor | 50.0 | Floor below which entries block |
| InpTenkan | 9 | Tenkan-sen period |
| InpKijun | 21 | Kijun-sen period |
| InpSenkouB | 52 | Senkou Span B period |
| InpADXThreshold | 20.0 | ADX threshold (trend strength) |
| InpHTF | 8 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF for trend agreement |
| InpMinRR | 1.5 | Min reward:risk ratio |
| InpATRSLFactor | 1.5 | ATR factor for SL distance |
| InpATRTPFactor | 2.5 | ATR factor for TP distance |
| InpTrailATRFactor | 2.0 | ATR trailing distance factor |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18002 Ichi_ATR_EA — Ichimoku + ATR trend-following 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>
//--- non-input tunables (kept out of input surface to respect 12-22 cap)
#define ATR_PERIOD 14 // ATR period (price-distance SL/TP/trail)
#define ADX_PERIOD 14 // ADX period for regime
#define BB_PERIOD 20 // Bollinger period (BB width regime)
#define BB_DEVIATION 2.0 // Bollinger deviation
#define ATRPCT_LOOKBACK 100 // ATR-percentile lookback
#define HTF_EMA_PERIOD 50 // HTF trend EMA period
#define BE_AT_R 1.0 // Break-even trigger at 1R profit
#define PARTIAL_TP_R 1.0 // Partial TP (50%) at 1R
#define PARTIAL_TP_PCT 50 // Partial close percentage
#define MAX_BARS_IN_TRADE 200 // Hard time exit (bars)
#define SPREAD_ROLL_AVG_BARS 50 // Rolling spread average window
#define SPREAD_MAX_MULT 3.0 // Max spread multiple vs rolling avg
#define COOLDOWN_BARS 10 // Bars to cool down after N losses
#define SLIPPAGE_POINTS 30 // Order slippage in points
#define SESSION_START_HOUR 7 // London/NY active session start (server time)
#define SESSION_END_HOUR 21 // London/NY active session end (server time)
//+------------------------------------------------------------------+
//| INPUTS (21 total, grouped) |
//+------------------------------------------------------------------+
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;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.