P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18044 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX18044 HA2 -- Heikin-Ashi color flip trend EA, full 12-layer stack.

Overview

Pipsgrowth EX18044 HA2 reads trend direction off smoothed Heikin-Ashi candle flips on a five-minute chart, then runs each candidate signal through three independent confirmation filters and a seven-state regime classifier before a single order is fired. The whole point of building on Heikin-Ashi rather than raw candles is noise reduction: the smoothed open and close compress the inside-bar and doji clutter that would otherwise trigger a flood of false flips on metals. The EA rebuilds the Heikin-Ashi series in place via ComputeHeikinAshi() over 300 bars (HA_BARS_USED) using the standard recursive formula: HA-close is the average of the four OHLC values, HA-open is the average of the previous HA-open and HA-close. The signal logic in SignalHA() only watches the last two closed bars (g_haClose[1] > g_haOpen[1] versus g_haClose[2] > g_haOpen[2]) and emits a +1 long or -1 short when the colour flips from one bar to the next, returning a fixed confidence of 55 (the EA treats the HA flip as a baseline-strength signal, not a graded score).

Before a flip is allowed to become an order it must clear three independent trend filters. First, the inline Hull Moving Average built by HullValue() from weighted moving averages of half-period 11 and full-period 21 — the slope between the current and previous closed bar is read by HullSlopeDir(), and a long is rejected if the Hull slope is pointing down, a short if pointing up. Second, the EMA(50) bias is read in EMATrendDir() from the close of the closed bar against the M5 EMA: a long requires close above EMA(50), a short requires close below. Third, when InpUseMACDConfirm is true (default), MACDHistDir() reads the MACD(12,26,9) histogram on the closed bar and refuses any long when the histogram is negative or any short when it is positive. All three filters are required — a partial pass exits the tick with a SKIP log line and no order.

The HTF confirmation is bolted on as a fourth hard gate inside NoTradeReason(). When InpRequireHTF is on, HTFDir() reads the EMA(50) on H1 (EMA_HTF_TIMEFRAME = PERIOD_H1) and the H1 close: a long is rejected if the H1 EMA is above the H1 close, and a short is rejected if the H1 EMA is below it. This is the only HTF check in the EA; everything else runs on M5.

A seven-state regime classifier runs every tick before signal processing. ClassifyRegime() sorts the last 200 ATR(14) values and the last 200 Bollinger-band-width values into percentile ranks (ATR_PCT_LOOKBACK = 200, BB_PERIOD = 20, BB_DEVIATION = 2.0). The seven states are STRONG_TREND (ADX≥28 and ATR-percentile≥0.70), WEAK_TREND (ADX≥20), EXPAND (BB-width-percentile≥0.75), BREAKOUT (BB-width-percentile≥0.45), COMPRESS (BB-width-percentile≤0.30), CHOPPY (ADX<10), and RANGE. STRONG_TREND and WEAK_TREND permit entries; CHOPPY and COMPRESS force-close open positions in ManagePositions(); the other states are admitted but watched.

Risk and order handling live in DoEntry(). Stop distance is 1.8× the ATR(14) of the closed bar (SL_ATR_MULT = 1.8), take-profit distance is 2.0× that, giving a fixed 1:2.22 R:R envelope that exceeds the EA's MIN_RR_RATIO floor of 1.3. Both distances are clamped to at least 1.05× the broker's stops-level price so the order never gets rejected for being too close. ComputeLot() sizes the position so the dollar risk equals InpRiskPercent (0.5% of effective capital) divided by the per-lot risk at the chosen SL distance, normalised to the symbol's volume step. OrderCalcMargin() runs before the send, and the order is aborted with INSUFFICIENT MARGIN if the required margin exceeds free margin. The whole send path is wrapped by SendOpen() which retries twice on TRADE_RETCODE_REQUOTE, TRADE_RETCODE_TIMEOUT, and TRADE_RETCODE_PRICE_OFF, sleeping 150ms between attempts before falling back to a OPEN FAIL log line.

Once a position is open, ManagePositions() does the work on every tick. Break-even is one-shot at 1.0R (BE_TRIGGER_R_MULT = 1.0) — the stop is moved to open ± max(stopsLevel, 0.05×ATR), but only if the new stop is actually above the current stop and the distance to current price still exceeds the stops level. The first partial close fires at 1.0R as well (PARTIAL_TP_R_MULT = 1.0) and books 50% of the position (PARTIAL_TP_PERCENT = 50), but only when the remaining volume would still be at least 2× the symbol's volume minimum. After the partial, an ATR-trailing stop (TRAIL_ATR_MULT = 3.0) is updated forward-only on every tick. The trailing distance is also clamped to 1.05× the stops level. Three exit paths close the position entirely: an opposite Heikin-Ashi flip (read again from SignalHA()), a time exit at 240 bars (MAX_HOLD_BARS = 240), and a regime-change exit when g_regime flips to CHOPPY or COMPRESS. Each exit path is invoked through CloseTicket(), which retries three times on requote or timeout before giving up.

Portfolio-level caps are checked both at entry and during management. The daily loss limit (InpDailyLossLimitPct = 3.0) and weekly loss limit (InpWeeklyLossLimitPct = 6.0) are measured against the realised PnL of this magic number, walked from the deal history by MagicRealizedPnLToday() and MagicRealizedPnLThisWeek(). A capital cap row remains in the inputs (InpCapitalCapAmount defaulted to 0, InpCapitalCapFloor = 50), but the original enable flag was removed in v2.00 — the cap is effectively off, and the $50 floor still blocks new entries below it. InpMaxConcurrent = 1 and InpMaxSymbolExposure = 1 mean the EA never stacks a second ticket on the same symbol. Cooldown (InpCooldownAfterLoss = 3) is bar-aware: UpdateLossTracking() watches closed deals at 30-second intervals, increments g_consecLosses on each realised loss, resets to zero on the first win, and InCooldown() returns true until at least one new bar opens after the third loss.

The session and event gates are simple. InSession() blocks Saturdays and Sundays entirely and only allows entries between 7:00 and 20:00 broker-server time. InNewsWindow() calls CalendarValueHistory() for the ±15-minute window around the current time and blocks entries when at least one event with CALENDAR_IMPORTANCE_HIGH is present — this is the MQL5 native economic-calendar path, not a hard-coded time list. SpreadPoints() rejects any tick where the live spread exceeds 30 points (SPREAD_MAX_POINTS = 30). The kill switch (InpKillSwitch) sits at the top of NoTradeReason() and disables every new entry without touching the open-position management path. InpDryRun defaults to true and routes every order and every modify through the PrintFormat("[DRYRUN] ...") path so the EA can be validated in the strategy tester without any live exposure.

The indicator stack runs at six handles: ADX(14), ATR(14), EMA(50) on the M5 timeframe, EMA(50) on the H1 timeframe, MACD(12,26,9) on close, and Bollinger Bands(20,2) on close. The OnTester() criterion is the family standard (net * profitFactor) / (1 + balance_dd_percent) with a 30-trade floor below which the optimisation pass returns 0. TryClose_EX18044(), TryClosePartial_EX18044(), and TryModify_EX18044() each run three retries on requote, timeout, price-off, and price-changed with 200ms / 200ms / 100ms sleeps respectively. The order comment is hard-coded to Psgrowth.com Expert_18044, and every position is tagged with the magic 22218044 so multiple instances of the EA on the same account can be told apart in the deal history. EX18044 is built for the same environment as the rest of the TrendFollow line — XAUUSD M5 on a low-spread ECN — but the indicator set is small enough that it also runs on FX majors without code changes.

Strategy Deep Dive

On every tick, ClassifyRegime() sorts the last 200 ATR(14) values and 200 Bollinger-band-width values into percentile ranks to assign one of seven regime states (STRONG_TREND / WEAK_TREND / EXPAND / BREAKOUT / COMPRESS / CHOPPY / RANGE). On a new bar, ComputeHeikinAshi() rebuilds 300 bars of smoothed HA candles and SignalHA() watches the last two closed bars for a colour flip, returning ±1 with a fixed confidence of 55. A flip is only sent to DoEntry() after the inline Hull-MA(21) slope (HullSlopeDir()), the M5 EMA(50) bias (EMATrendDir()), and the MACD(12,26,9) histogram direction (MACDHistDir(), gated by InpUseMACDConfirm) all agree, and the H1 EMA(50) agrees when InpRequireHTF is on. DoEntry() sizes via 0.5% risk over a 1.8×ATR(14) stop, sets the TP at 2.0× the SL distance, verifies free margin through OrderCalcMargin(), and routes the send through SendOpen() which retries twice on requote / timeout / price-off with a 150ms sleep. ManagePositions() runs a one-shot break-even at 1.0R, a 50% partial close at 1.0R (volume permitting), a forward-only 3.0×ATR(14) trailing stop, and three full-exit paths: opposite HA flip, 240-bar time exit, and a regime flip to CHOPPY or COMPRESS.

Entry Signal

Long entry triggers when the Heikin-Ashi smoothed candle flips from bearish to bullish on the closed M5 bar (close > open on bar 1, close < open on bar 2), with the inline Hull-MA(21) slope pointing up, M5 close above EMA(50), and the MACD(12,26,9) histogram positive (when MACD confirmation is enabled). The H1 EMA(50) must also agree when InpRequireHTF is on. Short entries mirror the same flip on the bearish side. Confidence is set to 55 by SignalHA() — a flat baseline, not a graded vote.

Exit Signal

Exits run in ManagePositions(): an opposite Heikin-Ashi flip closes the position immediately via CloseTicket(); a 240-bar time exit (MAX_HOLD_BARS = 240) forces a close on any position held past the limit; and a regime-change to CHOPPY or COMPRESS (per ClassifyRegime()) force-closes every open ticket. Partial and break-even logic fire before the full exit.

Stop Loss

Stop loss is fixed at 1.8× the ATR(14) of the closed bar, clamped to at least 1.05× the broker's stops-level price so the SL never gets rejected as too close. The break-even layer ratchets the stop to open ± max(stopsLevel, 0.05×ATR) on a one-shot basis once price reaches 1.0R, and a forward-only ATR trail of 3.0×ATR(14) takes over after that.

Take Profit

Take-profit is 2.0× the SL distance, giving a 1:2.22 R:R envelope that exceeds the MIN_RR_RATIO floor of 1.3. A 50% partial close at 1.0R (PARTIAL_TP_R_MULT = 1.0, PARTIAL_TP_PERCENT = 50) books half the position before the full TP is hit, but only when the remaining volume would still be at least 2× the symbol's volume minimum.

Best For

Best deployed on XAUUSD M5 with a starting balance of $100 (the EA's minDeposit floor) on a low-spread ECN broker that allows the Heikin-Ashi, MACD, and H1 EMA(50) to feed tick-level data without throttling. The 30-point spread cap and 7–20 server-time session window mean the EA concentrates on the European and US cash sessions; the MQL5-calendar news filter blocks entries around high-impact events, so the operator does not need a separate news-supply licence. Risk level is MEDIUM: position sizing is fixed at 0.5% per trade with a 1:2.22 R:R target and a 3% / 6% daily / weekly loss cap, which is conservative for a Heikin-Ashi trend system on metals but aggressive enough to need a clean execution venue.

Strategy Logic

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

Family: TrendFollow Magic: 22218044 Version: 2.00

BRIEF: Heikin-Ashi smoothed candle color flip (HA2 variant). Color change on last CLOSED bar is the core signal; confirmed by inline Hull-MA slope, MACD histogram direction agreement, and EMA(50) bias. Entries gated by ADX + ATR-percentile + Bollinger-width regime classifier. Full capital-allocation-cap risk, ATR-based SL, BE/partial-TP/ATR-trail, opposite-signal/ time/regime-change exits, broker-portable symbol/margin handling. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • ADX
  • ATR
  • EMA
  • EMA_HTF
  • MACD
  • BB

KEY FUNCTIONS:

  • ComputeHeikinAshi()
  • WMACalc()
  • HullValue()
  • SafeCopy()
  • ATRPercentile()
  • ClassifyRegime()
  • IsNewBar()
  • EffectiveCapital()
  • MagicRealizedPnLToday()
  • MagicRealizedPnLThisWeek()
  • StopsLevelPrice()
  • FreezeLevelPrice()
  • ...and 25 more

INTERNAL CONSTANTS (19 total):

  • HA_BARS_USED = 300 // bars of HA history to compute
  • HULL_PERIOD = 21 // Hull MA period
  • HULL_HALF_PERIOD = 11 // floor(HULL_PERIOD/2)
  • HULL_SQRT_PERIOD = 5 // floor(sqrt(HULL_PERIOD))
  • EMA_TREND_PERIOD = 50 // EMA(50) trend bias
  • EMA_HTF_PERIOD = 50 // HTF EMA period
  • MACD_FAST = 12 // MACD fast EMA
  • MACD_SLOW = 26 // MACD slow EMA
  • MACD_SIGNAL = 9 // MACD signal SMA
  • ATR_PCT_LOOKBACK = 200 // lookback for ATR percentile
  • ATR_PCT_STRONG_MIN = 0.7 // ratio vs median ATR (strong)
  • ATR_PCT_CHOP_MAX = 0.5 // ratio vs median ATR (choppy)
  • BB_WIDTH_COMPRESS_Q = 0.30 // BB width percentile (compress)
  • BB_WIDTH_EXPAND_Q = 0.75 // BB width percentile (expand)
  • SESSION_START_HOUR = 7 // server-time hour
  • ...and 4 more

INPUT PARAMETERS (19 total across 7 groups):

  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18044" // Trade comment
  • [=== Identity ===] InpMagic = MAGIC // Magic number
  • [=== Identity ===] InpSlippagePts = SLIPPAGE_POINTS // Slippage cap (points)
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (% of effective capital)
  • [=== Risk & Sizing ===] InpDailyLossLimitPct = 3.0 // Daily loss limit (% of effective capital)
  • [=== Risk & Sizing ===] InpWeeklyLossLimitPct = 6.0 // Weekly loss limit (% of effective capital)
  • [=== Risk & Sizing ===] InpMaxConcurrent = 1 // Max concurrent positions (this EA/symbol)
  • [=== Risk & Sizing ===] InpMaxSymbolExposure = 1 // Max positions per symbol (all magics)
  • [=== Risk & Sizing ===] InpCooldownAfterLoss = 3 // Cooldown bars after N consecutive losses
  • [=== Capital Cap ===] InpCapitalCapAmount = 0.0 // Cap amount (real money $)
  • [=== Capital Cap ===] InpCapitalCapFloor = 50.0 // Floor below which no new entries
  • [=== Signal ===] InpHABarsLookback = 2 // HA bars to confirm flip (>=2)
  • [=== Regime / Confirm ===] InpRequireHTF = true // Require HTF EMA agreement
  • [=== Regime / Confirm ===] InpUseMACDConfirm = true // Require MACD histogram agreement
  • [=== Exit / Manage ===] InpUseATRTrail = true // ATR trailing stop
  • [=== Exit / Manage ===] InpUseBE = true // One-shot break-even
  • [=== Exit / Manage ===] InpUsePartialTP = true // Partial TP at TP1
  • [=== DryRun / Kill ===] InpDryRun = true // Dry-run (no actual sends)
  • [=== DryRun / Kill ===] InpKillSwitch = false // Master kill switch
Pseudocode
// Pipsgrowth EX18044 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Heikin-Ashi smoothed candle color flip (HA2 variant). Color change on last CLOSED bar is the core signal; confirmed by inline Hull-MA slope, MACD histogram direction agreement, and EMA(50) bias. Entries gated by ADX + ATR-percentile + Bollinger-width regime classifier. Full capital-allocation-cap risk, ATR-based SL, BE/partial-TP/ATR-trail, opposite-signal/ time/regime-change exits, broker-portable symbol/margin handling. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

ON_INIT:
    Create indicator handles: ADX, ATR, EMA, EMA_HTF, MACD, BB
    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_18044"Trade comment
InpMagicMAGICMagic number
InpSlippagePtsSLIPPAGE_POINTSSlippage cap (points)
InpRiskPercent0.5Risk per trade (% of effective capital)
InpDailyLossLimitPct3.0Daily loss limit (% of effective capital)
InpWeeklyLossLimitPct6.0Weekly loss limit (% of effective capital)
InpMaxConcurrent1Max concurrent positions (this EA/symbol)
InpMaxSymbolExposure1Max positions per symbol (all magics)
InpCooldownAfterLoss3Cooldown bars after N consecutive losses
InpCapitalCapAmount0.0Cap amount (real money $)
InpCapitalCapFloor50.0Floor below which no new entries
InpHABarsLookback2HA bars to confirm flip (>=2)
InpRequireHTFtrueRequire HTF EMA agreement
InpUseMACDConfirmtrueRequire MACD histogram agreement
InpUseATRTrailtrueATR trailing stop
InpUseBEtrueOne-shot break-even
InpUsePartialTPtruePartial TP at TP1
InpDryRuntrueDry-run (no actual sends)
InpKillSwitchfalseMaster kill switch
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18044.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18044 HA2 -- Heikin-Ashi 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>

CTrade           g_trade;
CSymbolInfo      g_sym;
CPositionInfo    g_pos;
CAccountInfo     g_acc;

//============================ DEFINES ==============================
#define HA_BARS_USED          300     // bars of HA history to compute
#define HULL_PERIOD           21      // Hull MA period
#define HULL_HALF_PERIOD      11      // floor(HULL_PERIOD/2)
#define HULL_SQRT_PERIOD      5       // floor(sqrt(HULL_PERIOD))
#define EMA_TREND_PERIOD      50      // EMA(50) trend bias
#define EMA_HTF_PERIOD        50      // HTF EMA period
#define EMA_HTF_TIMEFRAME     PERIOD_H1
#define MACD_FAST             12      // MACD fast EMA
#define MACD_SLOW             26      // MACD slow EMA
#define MACD_SIGNAL           9       // MACD signal SMA
#define ATR_PERIOD            14
#define ATR_PCT_LOOKBACK      200     // lookback for ATR percentile
#define BB_PERIOD             20
#define BB_DEVIATION          2.0
#define ADX_PERIOD            14
#define ADX_TREND_MIN         20.0
#define ADX_STRONG_MIN        28.0
#define ATR_PCT_STRONG_MIN    0.7     // ratio vs median ATR (strong)
#define ATR_PCT_CHOP_MAX      0.5     // ratio vs median ATR (choppy)
#define BB_WIDTH_COMPRESS_Q   0.30    // BB width percentile (compress)
#define BB_WIDTH_EXPAND_Q     0.75    // BB width percentile (expand)
#define MIN_RR_RATIO          1.3
#define MAX_DAILY_TRADES      10
#define SESSION_START_HOUR    7       // server-time hour
#define SESSION_END_HOUR      20
#define NEWS_WINDOW_BARS      2       // skip trades this many bars around news
#define MAX_HOLD_BARS         240     // time-based exit
#define TRAIL_ATR_MULT        3.0
#define BE_TRIGGER_R_MULT     1.0
#define PARTIAL_TP_R_MULT     1.0
#define PARTIAL_TP_PERCENT    50
#define SL_ATR_MULT           1.8
#define TP_R_MULT             2.0
#define SPREAD_MAX_POINTS     30      // hard cap on spread (points)
#define PYRAMID_MAX_LEVELS    3
#define PYRAMID_ATR_SPACING   1.5
#define PYRAMID_LOT_CAP_MULT  1.0
#define SLIPPAGE_POINTS       10
#define MAGIC                 22218044

//============================ INPUTS ===============================
input group "=== Identity ==="

Full source code available on download

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

Tags:ex18044trendfollowpipsgrowthfreemt5xauusd

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