P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18047 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX18047 HeikAshi Adaptive Scalper Pro -- HA N-color continuation, full 12-layer stack.

Overview

EX18047 TrendFollow reads a sequence of inline-computed Heikin-Ashi candles on the M5 chart and only acts when the last N closed HA bars all print the same color. The default InpHABars is 3, meaning the EA waits for three consecutive bullish HA bars to consider a long, or three consecutive bearish HA bars to consider a short. The Heikin-Ashi transformation is built from scratch in ComputeSignal() — it walks InpHABars+2 raw OHLC bars, seeds the oldest bar with a (O+C)/2 open and a 4-price close, then propagates each subsequent HA candle with haC = (O+H+L+C)/4 and haO = (haO_prev + haC_prev)/2, clipping haH to MathMax(rawH, haO, haC) and haL to MathMin(rawL, haO, haC). The HA color is therefore a smoothed consensus of the underlying OHLC bodies and is far less twitchy than raw price action. Bullish continuation requires haC > haO on every one of the last InpHABars closed bars; bearish continuation requires haC < haO on every one of them. A neutral result (mixed colors) yields sig = 0 and the bar is skipped.

Before the HA vote can arm a trade, EX18047 demands agreement from a 4-condition confirmation panel. Condition 1 is MACD momentum: for a long, the closed-bar main line (fast EMA 12, slow EMA 26, signal 9 on close) must be above the signal line AND above its own prior value (macdM1 > macdS1 && macdM1 > macdM2); for a short, the main line must be below the signal line AND below its own prior value. Condition 2 is an RSI band: longs need RSI(14) between 45 and 75, shorts need RSI between 25 and 55 — the bands are deliberately asymmetric to keep momentum trades away from exhaustion zones. Condition 3 is HTF agreement: the H1 EMA(50) (hHTFEMA on PERIOD_H1) is compared to the Ask price for longs or the Bid for shorts, and price must be on the correct side of the hourly EMA. Condition 4 is a basic ADX floor of 15 to ensure the move is directional. The EA requires at least 3 of these 4 to vote yes; the count is exposed as a 0–100 confidence value (votes × 25) but is informational only — entries fire on the 3-vote threshold.

Above the signal layer, DetectRegime() classifies each closed bar into one of seven regimes by combining ADX(14), an ATR-percentile rank (InpATRPctLookback = 50 bars), and a Bollinger-Bands width ratio on a (20, 2.0) BB. The seven labels are REG_STRONG_TREND (ADX ≥ 20 AND percentile ≥ 0.6), REG_WEAK_TREND (ADX ≥ 14), REG_EXPAND (percentile ≥ 0.8 AND width ratio ≥ 1.1), REG_BREAKOUT (percentile ≥ 0.7), REG_COMPRESS (percentile ≤ 0.25 AND width ratio ≤ 0.7), REG_RANGE (ADX < 15), and REG_CHOPPY (the catch-all). Only the first four regimes permit entries — a HA vote inside REG_COMPRESS, REG_RANGE, or REG_CHOPPY is vetoed by BlockedByNoTrade().

Risk and trade management follow a fixed R:R structure. SL distance is InpATRSlMult × ATR(14) = 2.0 × ATR by default; TP distance is InpATRTpMult × ATR(14) = 3.0 × ATR, which is a hardcoded 1:1.5 risk/reward. Position sizing in SizeByRisk() converts the InpRiskPercent = 0.5% risk budget into a lot count via tick value and tick size, then clamps it to the broker's LotsMin/LotsMax/LotsStep, and finally checks OrderCalcMargin against 90% of free margin to avoid margin-short rejections. A 4-hour cooldown is engaged after InpCooldownLosses = 3 consecutive closed losses; the timer is enforced inside OnTick by checking TimeCurrent() against g_cooldownUntil. A daily 3% loss limit and a weekly 6% limit (computed as 2 × daily inside BlockedByLossLimits) shut entries off for the remainder of the period, with both PnL sums walked from the DEAL_MAGIC-filtered history.

Active trade management is performed on every tick in ManagePositions(). When a position reaches 1R of profit (InpBETriggerR = 1.0), a one-shot break-even adjustment moves SL to open ± minDist, where minDist is the broker's StopsLevel in points. At the same 1R threshold, a 50% partial close (InpPartialRatio = 0.5) is executed once per ticket — the partial is gated by a per-position 'PT1' flag held in a 64-slot in-memory array because MT5 has no native per-position tag. After the BE trigger fires, an ATR trail activates: newSL = price - max(atrCur × InpTrailStepR, minDist) for longs, mirrored for shorts, with advancement-only logic so the stop never moves backwards. Three hard exits also run from ManagePositions(): a 200-bar time stop (barsHeld ≥ 200, hardcoded inside the function with no input), an opposite-signal exit (ComputeSignal returns the opposite direction), and a regime-flip exit that closes the position if RegimeNow() returns REG_CHOPPY on the current closed bar.

The no-trade gate also enforces practical trading hygiene: the spread is measured in pips via PipSize() (which multiplies the broker point by 10 on 3- or 5-digit symbols) and rejected above InpMaxSpreadPips = 3.0; server-side hour gates block trading from 22:00 to 00:59, on Saturday and Sunday, and on Friday after 22:00; and SYMBOL_TRADE_MODE_FULL, TERMINAL_TRADE_ALLOWED, and MQL_TRADE_ALLOWED are all required to be true. InpDryRun defaults to true — orders print to the journal as 'DRY-RUN BUY/SELL' with the would-be price, SL and TP, but no tickets are sent. InpKillSwitch is a hard panic: when flipped to true, OnTick short-circuits to HandleKillSwitch(), which iterates the magic/symbol-matched positions and force-closes them.

The version 2.00 source contains a small but worth-knowing quirk: the OnInit() block references an input named InpCapEnabled (lines 210–212), but the input group only declares InpCapAmount and InpCapFloor — the InpCapEnabled row was removed from the input block. The compiler accepts the result because the symbol resolves through MQL's tolerant handling, but the capital-allocation-cap feature is effectively dead in the runtime. EffectiveCapital() therefore always returns raw account equity, and the $50 InpCapFloor is still enforced. For backtests, OnTester uses a 90-day window with a 30-trade floor and returns (netProfit × profitFactor) / (1 + relativeBalanceDD%) as the fitness value. The trade comment is hardcoded to 'Psgrowth.com Expert_18047' and execution retries each trade, partial close, and SL/TP modification up to 3 times with a 200ms (close) or 100ms (modify) sleep between attempts on requote/timeout/price-change responses.

In practical use, EX18047 is a M5 single-position XAUUSD scalper aimed at medium-volatility sessions, with the HA smoothing acting as the de facto noise filter and the 7-state regime acting as the de facto trend filter. Because MAX_OPEN_TRADES = 1 and the cooldown timer is 4 hours, the EA will not revenge-trade through a chop session — once three losers land in a row, the EA is parked until the cooldown expires. The 200-bar ceiling on time-in-trade (about 16.5 hours on M5) bounds the worst case for a position that drifts, and the 50% partial at 1R means a winning trade has at least banked its risk budget before the ATR trail takes over.

Strategy Deep Dive

Each closed M5 bar, EX18047 rebuilds the Heikin-Ashi series from raw OHLC inside ComputeSignal() and counts how many of the last InpHABars (default 3) HA bars are bullish or bearish. A unanimous run is the raw signal. The signal then has to clear two gates: DetectRegime() must return one of four tradeable labels (StrongTrend, WeakTrend, Breakout, Expand) using ADX(14) + 50-bar ATR percentile + a Bollinger-width ratio on BB(20,2); and the 4-condition confirm panel (MACD momentum, RSI 14 in 45-75/25-55, H1 EMA(50) price-side agreement, ADX ≥ 15) must score at least 3 of 4. ManagePositions() then runs on every tick, applying a 1R break-even, a 50% partial at 1R, an ATR forward-only trail after the BE trigger, plus three hard exits — 200-bar ceiling, opposite-signal flip, and CHOPPY-regime regime-change. The capital-cap input row was removed in v2.00, so InpCapFloor ($50) is the only hard capital gate, and InpDryRun is true by default.

Entry Signal

Buy when ComputeSignal() detects InpHABars (default 3) consecutive bullish Heikin-Ashi closed bars AND the 4-vote confirm panel returns at least 3 votes (MACD main above signal and rising, RSI(14) in 45-75, Ask above H1 EMA(50), ADX ≥ 15) AND DetectRegime() returns REG_STRONG_TREND, REG_WEAK_TREND, REG_BREAKOUT, or REG_EXPAND. Short on the symmetric mirror. Entry fires on the new closed bar only, keyed off g_lastBarTime to prevent duplicates.

Exit Signal

Three hard exits run from ManagePositions(): 200-bar time stop (hardcoded, ~16.5h on M5), opposite-signal exit when ComputeSignal flips direction, and regime-flip exit when RegimeNow() returns REG_CHOPPY. Before those, a 50% partial close at 1R books risk-free profit, and an ATR trail (0.5×ATR, forward-only) takes over once the break-even trigger at 1R has fired.

Stop Loss

Initial SL is InpATRSlMult × ATR(14) = 2.0 × ATR, clamped up to the broker's StopsLevel in points. Once price reaches 1R, a one-shot break-even moves the stop to open ± minDist, and a 0.5×ATR forward-only trail takes over from there.

Take Profit

Fixed TP at InpATRTpMult × ATR(14) = 3.0 × ATR for a hardcoded 1:1.5 R:R. After 1R, a 50% partial (InpPartialRatio = 0.5) books the risk budget, and the remaining half rides the ATR trail. The 200-bar time stop and opposite-signal exit override the TP if either fires first.

Best For

XAUUSD M5 with a $100 minimum recommended balance. Best on brokers with low typical spread on gold (well under 3 pips) and tight StopsLevel, since the 1R break-even and 0.5×ATR trail need to step inside the minimum stop distance. The 1:00–22:00 server-side hour window covers the Asian morning, the European session, and the early US session, so the EA is suited for traders who want continuous coverage of gold's main active hours without overnight or weekend exposure.

Strategy Logic

Pipsgrowth EX18047 TrendFollow — Strategy Logic Analysis (from .mq5 source)

Family: TrendFollow Magic: 22218047 Version: 2.00

BRIEF: Inline Heikin-Ashi N-color continuation is the core signal; entries gated by REGIME (ADX + ATR-percentile + Bollinger width), confirmed by MACD momentum + RSI band + HTF-EMA agreement; NO-TRADE filters block spread/news/choppy/ weekend; CAPITAL ALLOCATION CAP clamps risk off MIN(cap,equity); ATR trailing + break-even + partial TP + opposite-signal / regime-change exits. Default DRY-RUN. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • NormalizePrice()
  • ClampVolume()
  • StopsLevelPoints()
  • PipSize()
  • MagicRealizedPnL()
  • MagicClosedTradesSince()
  • EffectiveCapital()
  • ComputeSignal()
  • BlockedByNoTrade()
  • MaintainStamps()
  • BlockedByLossLimits()
  • SizeByRisk()
  • ...and 12 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (22 total across 7 groups):

  • [=== Signal / Heikin-Ashi ===] InpHABars = 3 // Min same-color HA candles (count)
  • [=== Signal / Heikin-Ashi ===] InpRSIPeriod = 14 // RSI period (bars)
  • [=== Signal / Heikin-Ashi ===] InpMACDSlow = 26 // MACD slow EMA, fast=12/sig=9 fixed (bars)
  • [=== Regime / HTF ===] InpHTFEMA = 50 // HTF EMA period on PERIOD_H1 (bars)
  • [=== Regime / HTF ===] InpADXMinTrend = 20.0 // ADX min for StrongTrend (adx)
  • [=== Regime / HTF ===] InpATRPctLookback = 50 // ATR-percentile lookback (bars)
  • [=== Risk & Sizing ===] InpDryRun = true // Dry-run: skip live order sends (bool)
  • [=== Risk & Sizing ===] InpKillSwitch = false // KILL SWITCH — closes all & halts (bool)
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (% of effective_capital)
  • [=== Risk & Sizing ===] InpDailyLossPct = 3.0 // Daily loss limit (weekly=2x daily) (%)
  • [=== Risk & Sizing ===] InpMaxConcurrent = 1 // Max concurrent positions (count)
  • [=== Risk & Sizing ===] InpCooldownLosses = 3 // Cooldown after N consecutive losses (count)
  • [=== Capital Allocation Cap4.6) ===] InpCapAmount = 0.0 // Capital cap amount (account $)
  • [=== Capital Allocation Cap4.6) ===] InpCapFloor = 50.0 // Capital floor — block entries below ($)
  • [=== SL / TP / Trailing ===] InpATRSlMult = 2.0 // SL = ATR * mult (mult)
  • [=== SL / TP / Trailing ===] InpATRTpMult = 3.0 // TP = ATR * mult (mult)
  • [=== SL / TP / Trailing ===] InpBETriggerR = 1.0 // Break-even trigger at R multiple (R)
  • [=== SL / TP / Trailing ===] InpTrailStepR = 0.5 // Trail step distance (R)
  • [=== SL / TP / Trailing ===] InpPartialRatio = 0.5 // Partial TP close ratio at R (0=off) (ratio)
  • [=== Identity ===] InpMagic = 22218047 // Magic number (id)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18047" // Trade comment
  • [=== Exec ===] InpMaxSpreadPips = 3.0 // Max spread (pips, 0=auto)
Pseudocode
// Pipsgrowth EX18047 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Inline Heikin-Ashi N-color continuation is the core signal; entries gated by REGIME (ADX + ATR-percentile + Bollinger width), confirmed by MACD momentum + RSI band + HTF-EMA agreement; NO-TRADE filters block spread/news/choppy/ weekend; CAPITAL ALLOCATION CAP clamps risk off MIN(cap,equity); ATR trailing + break-even + partial TP + opposite-signal / regime-change exits. Default DRY-RUN. 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

Optimized Brokers:
ExnessIC Markets
Optimized Symbols:
XAUUSD
Optimized Timeframes:
M5

How to Install This EA on MT5

  1. 1Download the .mq5 file using the button above
  2. 2Open MetaTrader 5 on your computer
  3. 3Click File → Open Data Folder in the top menu
  4. 4Navigate to MQL5 → Experts and paste the .mq5 file there
  5. 5In MT5, right-click Expert Advisors in the Navigator panel → Refresh
  6. 6Drag the EA onto an H4 or Daily chart for best results
  7. 7Configure EMA periods, ADX threshold, and lot size in the dialog
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
InpHABars3Min same-color HA candles (count)
InpRSIPeriod14RSI period (bars)
InpMACDSlow26MACD slow EMA, fast=12/sig=9 fixed (bars)
InpHTFEMA50HTF EMA period on PERIOD_H1 (bars)
InpADXMinTrend20.0ADX min for StrongTrend (adx)
InpATRPctLookback50ATR-percentile lookback (bars)
InpDryRuntrueDry-run: skip live order sends (bool)
InpKillSwitchfalseKILL SWITCH — closes all & halts (bool)
InpRiskPercent0.5Risk per trade (% of effective_capital)
InpDailyLossPct3.0Daily loss limit (weekly=2x daily) (%)
InpMaxConcurrent1Max concurrent positions (count)
InpCooldownLosses3Cooldown after N consecutive losses (count)
InpCapAmount0.0Capital cap amount (account $)
InpCapFloor50.0Capital floor — block entries below ($)
InpATRSlMult2.0SL = ATR * mult (mult)
InpATRTpMult3.0TP = ATR * mult (mult)
InpBETriggerR1.0Break-even trigger at R multiple (R)
InpTrailStepR0.5Trail step distance (R)
InpPartialRatio0.5Partial TP close ratio at R (0=off) (ratio)
InpMagic22218047Magic number (id)
InpTradeComment"Psgrowth.com Expert_18047"Trade comment
InpMaxSpreadPips3.0Max spread (pips, 0=auto)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18047.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18047 HeikAshi Adaptive Scalper Pro -- HA N-color continuation, full 12-layer stack."
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>

//============================ INPUTS (22 total) =====================
input group "=== Signal / Heikin-Ashi ==="
input int      InpHABars         = 3;            // Min same-color HA candles (count)
input int      InpRSIPeriod      = 14;           // RSI period (bars)
input int      InpMACDSlow       = 26;           // MACD slow EMA, fast=12/sig=9 fixed (bars)

input group "=== Regime / HTF ==="
input int      InpHTFEMA         = 50;           // HTF EMA period on PERIOD_H1 (bars)
input double   InpADXMinTrend    = 20.0;         // ADX min for StrongTrend (adx)
input int      InpATRPctLookback = 50;           // ATR-percentile lookback (bars)

input group "=== Risk & Sizing ==="
input bool     InpDryRun         = true;         // Dry-run: skip live order sends (bool)
input bool     InpKillSwitch     = false;        // KILL SWITCH — closes all & halts (bool)
input double   InpRiskPercent    = 0.5;          // Risk per trade (% of effective_capital)
input double   InpDailyLossPct   = 3.0;          // Daily loss limit (weekly=2x daily) (%)
input int      InpMaxConcurrent  = 1;            // Max concurrent positions (count)
input int      InpCooldownLosses = 3;            // Cooldown after N consecutive losses (count)

input group "=== Capital Allocation Cap (§4.6) ==="
// InpCapEnabled removed — use InpCapAmount=0 to disable         // Capital cap enabled (bool)
input double   InpCapAmount      = 0.0;        // Capital cap amount (account $)
input double   InpCapFloor       = 50.0;         // Capital floor — block entries below ($)

input group "=== SL / TP / Trailing ==="
input double   InpATRSlMult      = 2.0;          // SL = ATR * mult (mult)
input double   InpATRTpMult      = 3.0;          // TP = ATR * mult (mult)
input double   InpBETriggerR     = 1.0;          // Break-even trigger at R multiple (R)
input double   InpTrailStepR     = 0.5;          // Trail step distance (R)
input double   InpPartialRatio   = 0.5;          // Partial TP close ratio at R (0=off) (ratio)

input group "=== Identity ==="
input int      InpMagic          = 22218047;     // Magic number (id)
input string   InpTradeComment   = "Psgrowth.com Expert_18047"; // Trade comment

input group "=== Exec ==="
input double   InpMaxSpreadPips  = 3.0;          // Max spread (pips, 0=auto)
// ====================================================================

//--- Indicators (handles)
int hADX=-1, hRSI=-1, hMACD=-1, hATR=-1, hBB=-1, hHTFEMA=-1, hATRSlow=-1;

//--- CTrade
CTrade        trade;
CSymbolInfo   si;
CPositionInfo pos;
CAccountInfo  acc;

//--- State
datetime g_lastBarTime = 0;     // duplicate-entry key (bar time)

Full source code available on download

Educational purposes only. Do NOT use with real money. Test on demo accounts only.

Tags:ex18047trendfollowpipsgrowthfreemt5xauusd

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

Community

Sign in to contributeSign In

Educational purposes only. Do NOT use with real money. Test on demo accounts only.

File NamePipsgrowth_com_EX18047.mq5
File Size33.5 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M5
Currency Pairs
XAUUSD
Min. Deposit$100