P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18048 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX18048 HeikAshi XAUUSD M5 -- HA color + MACD + RSI + ADX trend gate, full 12-layer stack.

Overview

Pipsgrowth EX18048 is a Heikin-Ashi reversal strategy tuned for XAUUSD on the 5-minute chart. The decision engine is anchored on a single, observable event: a Heikin-Ashi candle flips from red to green (long bias) or from green to red (short bias) on the last closed bar. The HA series is reconstructed in-line inside the EA rather than fetched from a custom indicator — ComputeHA() walks InpHA_Lookback (50) raw OHLC bars, seeds the oldest bar with the simple (O+C)/2 open and 4-price close, then propagates the standard HA recursion haC = (O+H+L+C)/4 and haO = (prevOpen+prevClose)/2 forward. Two adjacent closed HA bars are sampled; a state transition between them is the raw signal. The EA then demands that this candle flip be corroborated by two oscillators before any order is staged: MACD(12,26,9) must show main>signal for a long (main<signal for a short), and RSI(14) must be below 75 for a long or above 25 for a short. A confidence score is computed as 0.6min(100, ADX2.5) + 0.4*min(50, |RSI-50|*2) and trades are gated to confidence ≥ 25.

A seven-state regime classifier in DetectRegime() controls whether the signal is even considered. The classifier reads ADX(14), an ATR(14) percentile computed over the last 50 bars, and a Bollinger Bands(20,2.0) width ratio. When ADX ≥ InpADX_MinTrend (22) and the ATR-percentile ≥ 70 the regime is STRONG_TREND; the same ADX with lower percentile is WEAK_TREND. A very high ATR-percentile (≥ 80) without trend strength is EXPAND, a BB width ratio > 0.03 is BREAKOUT, ADX < 15 is CHOPPY, and the residual is RANGE. COMPRESS is detected when the BB width ratio collapses below 0.01. RegimeAllowsEntry() returns true for STRONG_TREND, WEAK_TREND, EXPAND and BREAKOUT — the four states where a HA color flip has the highest probability of starting a sustained move.

Beyond regime, a higher-timeframe trend agreement is required. HTFTrendAgrees() copies the close and an EMA(50) from the configured higher timeframe (H1 by default — InpHTF_TF is mapped to a PERIOD_* via MapTimeframeInt()) and demands that the H1 close sit above the H1 EMA for a long and below it for a short. This filter alone is responsible for most of the EA's directional discipline — counter-trend HA flips during a strong H1 downtrend will not stage an order regardless of M5 confirmation.

Entries are constructed on the close of a bar, not on intra-bar ticks. TryEntry() is invoked from OnTick() only when CoreSignal() returns non-zero and confidence ≥ 25; it then enforces a per-bar duplicate guard via g_lastEntryBarTime so that a single HA flip can spawn at most one order per bar. The no-trade gate — NoTradeReason() — runs the full rejection stack: kill switch, spread > InpMaxSpreadPoints (50 points), broker-server time outside InpSessionStartH/InpSessionEndH (07:00-20:00), NewsBlocked() (a reserved hook that currently always returns false), bad regime, HTF disagreement, effective capital below the InpCapFloor ($50) when a capital cap is configured, realized daily loss ≤ -3% of effective capital, realized weekly loss ≤ -6%, an active 4-hour cooldown after InpCooldownLosses (3) consecutive losses, and InpMaxConcurrent (3) positions already open. Any single rejection string short-circuits the entry and is logged via PrintFormat("[NOTRADE] sig=%d reason=%s", ...).

Position sizing is a fixed-fractional model on effective capital. ComputeLots() divides InpRiskPercent (0.5%) of effective capital by the per-lot risk implied by the ATR(14) * InpATR_SL_Mult (2.0) stop distance and the symbol's tick value/tick size, then passes the result through ClampVolume() which respects the broker's min/max/step and applies InpMaxLot (5.0 lots) as a hard cap. Before the order is sent, OrderCalcMargin() is called to estimate the required margin and the entry is rejected if it exceeds free margin. The InpDryRun switch defaults to true, so a fresh install will only print [DRYRUN] blocks with the would-be price, lots, SL and TP until the operator explicitly enables live execution.

Once in a position, the management loop in ManagePositions() is invoked every tick. The exits it can trigger, in order, are: a kill-switch close (when InpKillSwitch is true), a max-bars time stop at InpMaxBars (240 M5 bars = 20 hours), an opposite-signal close when a new HA flip opposes the current position, a regime-change close when the regime becomes CHOPPY or RANGE — but only if the trade is still unrealized at or below zero, so a profitable trade is never closed by a benign regime shift. The break-even logic moves the stop to open ± the broker's minimum stop distance once price has moved 1R in favor (unrealized ≥ ATR(14) * 1.0); the BE move is a one-shot and is not repeated. After BE is engaged the ATR(14) * InpATR_SL_Mult (2.0) trailing logic ratchets the stop on each tick where the new level would improve the existing stop by at least the freeze/stops-level distance. The TP is fixed at the entry price ± SL distance * InpRR_Min (1.5), giving a 1.5:1 reward/risk target.

The capital cap stack in this build is partially vestigial: the InpCapEnabled flag is referenced inside EffectiveCapital() but the corresponding input row was removed in v2.00, so setting InpCapAmount (default 0.0) is the only way to engage the cap and a non-zero cap is also the only condition under which InpCapFloor (50 USD) is enforced. The cooldown arming in TrackLossForCooldown() inspects the most recent closing deal filtered by InpMagic and _Symbol; after three losses in a row g_cooldownUntil is set to now + 4*3600 and the consecutive-loss counter is reset, but a single winning trade also resets the counter. The week boundary in MaybeResetTrackers() is computed on a 7*86400-second rolling window rather than the broker's actual Monday open.

The OnTester criterion is (netProfit * profitFactor) / (1 + relativeMaxDD) over the last 365 days, gated to a minimum of 30 closed trades, which biases the strategy optimizer toward smooth equity curves with controlled drawdowns rather than headline net profit alone. The retry helpers TryClose_EX18048, TryClosePartial_EX18048 and TryModify_EX18048 each loop up to three times with 200 ms or 100 ms sleeps on requote/timeout/price-change codes before giving up. Filling mode is auto-detected via SetTypeFillingBySymbol so the EA can run on netting and hedging accounts without code changes. For live deployment on a small account the recommended starting configuration is the default set with InpDryRun flipped to false, a 50-point spread cap (which XAUUSD on a typical ECN should respect most of the day outside the New York open), and the 07:00-20:00 server-time window respected by the broker — note that on brokers where server time is GMT+2 or GMT+3, the effective active hours are the European morning through the close of the New York cash session.

Strategy Deep Dive

Each tick the EA re-detects the regime from ADX(14), an ATR(14) percentile over the last 50 bars, and a Bollinger Bands(20,2.0) width ratio, classifying the market as STRONG_TREND, WEAK_TREND, EXPAND, BREAKOUT, COMPRESS, RANGE, or CHOPPY. CoreSignal() then reconstructs the last two closed Heikin-Ashi bars from raw OHLC primitives, looks for a red→green or green→red color flip, and demands that MACD(12,26,9) sign and RSI(14) position agree. A confidence score from ADX strength and RSI distance from 50 is required to be ≥ 25, and the higher-timeframe close vs EMA(50) must agree with direction. The full no-trade gate runs next — kill switch, spread cap, session window, capital floor, daily/weekly loss limits, cooldown, and concurrent-position cap — before ComputeLots() sizes the order at 0.5% risk, OrderCalcMargin() verifies free margin, and the fill is sent with auto-detected filling mode. Existing positions are then managed for BE, trail, time stop, opposite-signal exit, and regime-change exit, with three-attempt 200 ms/100 ms retries on every close and modify.

Entry Signal

Entries fire on a closed-bar Heikin-Ashi color flip — red→green yields a long signal, green→red yields a short. The flip is required to clear three independent confirmations: regime must be one of STRONG_TREND, WEAK_TREND, EXPAND or BREAKOUT (gated by ADX(14) ≥ 22, ATR-percentile ≥ 70/80, or BB width > 0.03), MACD(12,26,9) sign must agree with direction, and RSI(14) must sit between 25 and 75. The H1 close vs H1 EMA(50) must agree with the direction, and the confidence score (0.6ADX part + 0.4|RSI-50| part, capped 100) must be at least 25. Order is then sent at the next tick after bar close with a per-bar duplicate guard.

Exit Signal

Exits are layered: a 240-bar (20-hour) M5 time stop, an opposite-signal close on the next HA flip against the position, and a regime-change close when ADX falls below 15 or the bars slip into RANGE — but the regime-change exit is suppressed for any trade that is already in profit. A break-even one-shot fires at 1R (unrealized ≥ ATR(14) * 1.0), moving the stop to open ± the broker's minimum stop distance. After BE engages, the EA ratchets the stop behind price on every tick where the new stop improves by more than the freeze/stops-level distance, with trail distance equal to ATR(14) * 2.0.

Stop Loss

The initial stop is ATR(14) * InpATR_SL_Mult (2.0 × ATR) on entry, normalized to respect the broker's stops-level and freeze-level. The stop is then managed by the break-even one-shot at 1R and the 2.0×ATR forward trail; a global kill switch (InpKillSwitch) immediately closes every open position and blocks new entries.

Take Profit

The take-profit is hardcoded to 1.5 × the initial SL distance (InpRR_Min = 1.5), giving a fixed 1.5:1 reward/risk target on every entry. TP is set on the order at submission and is not trailed, so the position either closes at the original target, the trailing stop, the time stop, the opposite-signal close, or the regime-change close — whichever fires first.

Best For

Minimum recommended balance: $100 (the InpCapFloor of $50 is the hard floor when a capital cap is configured). The EA is designed for XAUUSD on M5 with a 07:00-20:00 broker-server-time window that maps to European morning through the end of the New York cash session on a GMT+2/GMT+3 broker. With InpMaxConcurrent set to 3 and InpRiskPercent at 0.5%, an ECN account with sub-50-point typical XAUUSD spreads and fast order execution is the right venue — a market-maker with requote-heavy fills will eat into the 1.5:1 reward/risk on every trade. MEDIUM risk classification reflects the ADX + ATR-percentile regime gate, the daily/weekly loss caps at 3% / 6%, and the 4-hour cooldown after three consecutive losses.

Strategy Logic

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

Family: TrendFollow Magic: 22218048 Version: 2.00

BRIEF: Heikin-Ashi color change (inlined) confirmed by MACD sign and RSI position is the core signal. REGIME gates entries via ADX + ATR-percentile + BB-width. ENTRY on bar close (shift=1) only, duplicate-entry keyed per bar time. CONFIRM requires HTF MA agreement + session + min R/R. NO-TRADE rejects on bad spread/session/choppy/news-window/max-loss. CAPITAL-ALLOCATION- CAP isolates per-magic effective_capital. RISK = % per trade, ATR SL, daily/weekly loss caps, cooldown, kill-switch. EXIT: break-even, ATR trail, partial TP, regime change, opposite signal, max-bars. SCALING off by default, capped. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • EffectiveCapital()
  • RealizedPnLToday()
  • RealizedPnLThisWeek()
  • CountOpenPositions()
  • NormalizedStops()
  • ClampVolume()
  • SpreadPoints()
  • InSession()
  • NewsBlocked()
  • CopyBuf()
  • RegimeAllowsEntry()
  • ComputeHA()
  • ...and 12 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (29 total across 5 groups):

  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18048" // Trade comment
  • [=== Capital Allocation Cap ===] InpCapAmount = 0.0 // Capital cap amount ($)
  • [=== Capital Allocation Cap ===] InpCapFloor = 50.0 // Capital floor — block entries below ($)
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (% of effective capital)
  • [=== Risk & Sizing ===] InpDailyLossLimit = 3.0 // Daily loss limit (% of effective capital)
  • [=== Risk & Sizing ===] InpWeeklyLossLimit = 6.0 // Weekly loss limit (% of effective capital)
  • [=== Risk & Sizing ===] InpMaxConcurrent = 3 // Max concurrent positions (int)
  • [=== Risk & Sizing ===] InpCooldownLosses = 3 // Cooldown after N consecutive losses (int)
  • [=== Risk & Sizing ===] InpATR_SL_Mult = 2.0 // ATR stop-loss multiplier (x ATR)
  • [=== Risk & Sizing ===] InpRR_Min = 1.5 // Minimum reward:risk ratio (x)
  • [=== Risk & Sizing ===] InpMaxLot = 5.0 // Max lot cap (lots)
  • [=== Signal: HA/MACD/RSI/ADX ===] InpADX_Period = 14 // ADX period (bars)
  • [=== Signal: HA/MACD/RSI/ADX ===] InpADX_MinTrend = 22 // ADX min for StrongTrend (value)
  • [=== Signal: HA/MACD/RSI/ADX ===] InpATR_Period = 14 // ATR period (bars)
  • [=== Signal: HA/MACD/RSI/ADX ===] InpBB_Period = 20 // Bollinger period (bars)
  • [=== Signal: HA/MACD/RSI/ADX ===] InpBB_Dev = 2.0 // Bollinger deviation (std-dev)
  • [=== Signal: HA/MACD/RSI/ADX ===] InpMACD_Fast = 12 // MACD fast EMA (bars)
  • [=== Signal: HA/MACD/RSI/ADX ===] InpMACD_Slow = 26 // MACD slow EMA (bars)
  • [=== Signal: HA/MACD/RSI/ADX ===] InpMACD_Signal = 9 // MACD signal EMA (bars)
  • [=== Signal: HA/MACD/RSI/ADX ===] InpRSI_Period = 14 // RSI period (bars)
  • [=== Signal: HA/MACD/RSI/ADX ===] InpHA_Lookback = 50 // Heikin-Ashi lookback (bars)
  • [=== Signal: HA/MACD/RSI/ADX ===] InpHTF_TF = 8 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF timeframe for trend agreement
  • [=== Trade Filters & Execution ===] InpMaxSpreadPoints = 50 // Max spread (points) — 0 disables
  • [=== Trade Filters & Execution ===] InpSessionStartH = 7 // Session start hour (broker server time)
  • [=== Trade Filters & Execution ===] InpSessionEndH = 20 // Session end hour (broker server time)
  • [=== Trade Filters & Execution ===] InpMaxBars = 240 // Max bars in trade (M5 bars)
  • [=== Trade Filters & Execution ===] InpMagic = 22218048 // Magic number (int)
  • [=== Trade Filters & Execution ===] InpDryRun = true // Dry-run: signals/management only, no new sends
  • [=== Trade Filters & Execution ===] InpKillSwitch = false // Kill switch — flatten & block (true/false)
Pseudocode
// Pipsgrowth EX18048 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Heikin-Ashi color change (inlined) confirmed by MACD sign and RSI position is the core signal. REGIME gates entries via ADX + ATR-percentile + BB-width. ENTRY on bar close (shift=1) only, duplicate-entry keyed per bar time. CONFIRM requires HTF MA agreement + session + min R/R. NO-TRADE rejects on bad spread/session/choppy/news-window/max-loss. CAPITAL-ALLOCATION- CAP isolates per-magic effective_capital. RISK = % per trade, ATR SL, daily/weekly loss caps, cooldown, kill-switch. EXIT: break-even, ATR trail, partial TP, regime change, opposite signal, max-bars. SCALING off by default, capped. 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
InpTradeComment"Psgrowth.com Expert_18048"Trade comment
InpCapAmount0.0Capital cap amount ($)
InpCapFloor50.0Capital floor — block entries below ($)
InpRiskPercent0.5Risk per trade (% of effective capital)
InpDailyLossLimit3.0Daily loss limit (% of effective capital)
InpWeeklyLossLimit6.0Weekly loss limit (% of effective capital)
InpMaxConcurrent3Max concurrent positions (int)
InpCooldownLosses3Cooldown after N consecutive losses (int)
InpATR_SL_Mult2.0ATR stop-loss multiplier (x ATR)
InpRR_Min1.5Minimum reward:risk ratio (x)
InpMaxLot5.0Max lot cap (lots)
InpADX_Period14ADX period (bars)
InpADX_MinTrend22ADX min for StrongTrend (value)
InpATR_Period14ATR period (bars)
InpBB_Period20Bollinger period (bars)
InpBB_Dev2.0Bollinger deviation (std-dev)
InpMACD_Fast12MACD fast EMA (bars)
InpMACD_Slow26MACD slow EMA (bars)
InpMACD_Signal9MACD signal EMA (bars)
InpRSI_Period14RSI period (bars)
InpHA_Lookback50Heikin-Ashi lookback (bars)
InpHTF_TF8Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF timeframe for trend agreement
InpMaxSpreadPoints50Max spread (points) — 0 disables
InpSessionStartH7Session start hour (broker server time)
InpSessionEndH20Session end hour (broker server time)
InpMaxBars240Max bars in trade (M5 bars)
InpMagic22218048Magic number (int)
InpDryRuntrueDry-run: signals/management only, no new sends
InpKillSwitchfalseKill switch — flatten & block (true/false)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18048.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18048 HeikAshi XAUUSD M5 -- HA color + MACD + RSI + ADX trend gate, 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>

CTrade         m_trade;
CPositionInfo  m_position;
CSymbolInfo    m_symbol;
CAccountInfo   m_account;
COrderInfo     m_order;
CDealInfo      m_deal;

//================================================================
// INPUTS  (20 total — within 12..22)
//================================================================
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_TF = PERIOD_H1;
input group "=== Identity ==="
input string   InpTradeComment     = "Psgrowth.com Expert_18048"; // Trade comment

ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
   switch(tf)
   {
      case 1: return PERIOD_M1;

Full source code available on download

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

Tags:ex18048trendfollowpipsgrowthfreemt5xauusd

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_EX18048.mq5
File Size36.4 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M5
Currency Pairs
XAUUSD
Min. Deposit$100