P
PipsGrowth
OtherOpen Source – Free

Pipsgrowth EX12053 MultiIndicatorConfluence

MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1

Pipsgrowth.com EX12053 EX21 — TrendCatcher EA with Heikin-Ashi, EMA regime and MACD cross, full 12-layer stack.

Overview

Pipsgrowth EX12053 is a lean Heikin-Ashi-led trend-catcher for MetaTrader 5, built around a deliberate choice: keep the indicator stack small, keep the rules readable, let price action do most of the work. Where most MultiIndicatorConfluence variants in the same family pull in six to ten native indicator handles, EX12053 stands up exactly three — an EMA(21) for short-term trend, an EMA(50) for the structural backstop, and a MACD(12,26,9) for momentum confirmation — and pairs them with Heikin-Ashi direction computed inline from raw price data. The whole trade thesis is: only take a position when smoothed-price direction (HA), trend-structure direction (EMA cross), and momentum direction (MACD main vs signal, with a sign-bounded filter) all agree, and the fast EMA has actually been climbing or falling for at least the last few closed bars.

The signal chain lives in GenerateSignal(). On each new bar the EA pulls the last two closed-bar values of every handle via ReadIndicatorsOnClosedBar(), calls GetHeikinAshiOnBar(1, ...) to compute Heikin-Ashi on the most recent closed bar from a 200-bar CopyRates window, and runs the four sub-conditions for a long entry in this order: HA must be bullish (HA close above HA open, where HA close is the average of the four OHLC prices and HA open is the midpoint of the previous HA bar), the fast EMA(21) must print above the slow EMA(50), the MACD main must be above its signal line AND above zero (so it's not just a bullish cross inside a bearish regime — it has to be a positive-side bullish cross), and EMASlopeOK(true) must return true, meaning at least MinEMASlopeBars-1 of the last MinEMASlopeBars slope checks show the fast EMA rising. The short side is the perfect mirror: HA bearish, fast EMA below slow, MACD main below signal AND below zero, fast EMA falling on the slope check. If even one of the four sub-conditions fails, no signal fires. This is the design choice that defines EX12053 — it will not enter on a "decent" trend, only on a trend that every smoothed layer agrees on at the same instant.

Heikin-Ashi is computed from scratch on every signal bar in GetHeikinAshiOnBar(). The function allocates dynamic arrays sized to a 200-bar copy of MqlRates, seeds the first HA bar with the real open and the OHLC/4 average, then iterates forward using the canonical recursive formulas (HA close = OHLC/4; HA open = (prev HA open + prev HA close) / 2). The EA does not use an external Heikin-Ashi indicator — it does the math itself, which means the calculation is fully transparent and the only cost is the 200-bar rate copy. The HA bar is then compared to its own open to derive a directional bias (haBull / haBear), and that single boolean is the first gate in the signal chain. In a sideways market where raw candles alternate red and green, smoothed HA tends to flatten or flip back and forth, and the first gate alone blocks most of the chop.

The MACD sign-bounded filter (macdUp = (mMain > mSig) && (mMain > 0.0)) is the second defining choice. A plain MACD cross can fire anywhere on the indicator, including inside a deep bearish pullback of an otherwise bullish trend, which historically produces a lot of false signals on gold. By requiring the MACD main to also be on the correct side of zero, the EA restricts entries to cross events that occur in the "right half" of the histogram — the half where momentum is actually supporting the trend, not just turning inside a dead zone. Combined with the EMA cross and the slope check, this means the MACD line has to be moving in the trade direction, on the correct side of zero, while the fast EMA is sloping in the trade direction, while HA is bullish or bearish. Three independent momentum/trend layers stacked in series is a much higher bar than any one of them alone.

Entry execution goes through PlaceEntry(), which is gated by PreflightAllowsEntry(). The pre-flight check evaluates four conditions in order: the EA must not be stopped (terminal disconnect, etc.), InSession(TimeCurrent()) must return true, SpreadOkay() must return true, and the current time must be past g_tradePauseUntil (set by the loss-driven pause guards). The session filter uses a single server-time window with SessionStartHour=7 and SessionEndHour=22, and the helper InSession() handles the midnight-wrap case automatically if the window ever spans 24 hours. The spread gate is a median-based cap: PushSpreadSample() keeps a rolling window of the last SpreadMedianWindow=20 ticks of spread, MedianSpread() sorts and returns the median, and the current spread must be at or below SpreadCapMultiplier=3.0 times that median — i.e., the current spread can be up to 3× the recent typical spread before entries are blocked. This is a permissive filter compared to fixed-point caps; it lets the EA trade through normal news-widening events but rejects pathological spikes. If pre-flight clears, the EA computes the SL and TP from StopLossPoints=300 and TakeProfitPoints=600 and sends the order through SendMarketOrder().

The order sender implements a three-pass retry loop, with each pass cycling through the three filling modes ORDER_FILLING_FOK → ORDER_FILLING_IOC → ORDER_FILLING_RETURN. If the broker rejects the order with TRADE_RETCODE_INVALID_FILL or TRADE_RETCODE_INVALID, the EA steps immediately to the next filling mode (no sleep); if it gets a requote or price-off, it refreshes the price and retries; between full passes it sleeps RetryDelayMs=250 ms. After a successful fill, the EA scans open positions for the matching magic and ensures the inline SL/TP were actually applied (some ECN brokers ignore inline stops); if they weren't, it sends a TRADE_ACTION_SLTP modify. This is a small but important detail for XAUUSD on ECN accounts, where SL/TP drops are a common cause of unexpected losses.

Position management is split into two pieces. First, the per-trade DLP step-ratchet (ApplyDynamicLockProfitToPosition()) runs on every tick against every owned position. It computes movedPts from entry to current bid/ask, divides by InpLockProfitEveryXPoints=150 and floors it to get the number of completed lock steps, sets lockFromEntryPts = steps × 150 - InpLockMinusYPointsBuffer=20, and proposes a new SL at entry ± lockFromEntryPts. The proposed SL is then clamped against SYMBOL_TRADE_STOPS_LEVEL and refused if it would land inside SYMBOL_TRADE_FREEZE_LEVEL. Critically, the ratchet only ever tightens — if(curSL > 0 && newSL <= curSL + _Point*0.5) return; — so a sudden spike can never loosen the stop. After 150 points of progress, the SL moves to entry+130, after 300 points to entry+280, after 450 to entry+430, and so on. Second, the scaling gate in PlaceEntry() enforces the Initial vs Add#N hierarchy: the first same-direction trade gets the comment tag Psgrowth.com Expert_12053 Initial BUY/SELL; every additional same-direction trade is gated by IsAllSameDirProfitableAtLeast() which checks that every existing same-direction position is at least MinProfitPerTradeToAdd=5.0 points in profit, then gets the tag ... Add#N BUY/SELL with g_addCountBuy/g_addCountSell as the per-direction counter. The AllowOnlyProfitableAdditions flag (default true) controls whether the gate is enforced. Total same-direction scaling is capped at MaxOpenTrades=5.

The pause-guard system runs from OnTradeTransaction() on every deal-add event. When a deal entry of type DEAL_ENTRY_OUT (i.e. a closing deal) lands and the deal belongs to this EA's magic and symbol, the EA reads DEAL_PROFIT + DEAL_SWAP + DEAL_COMMISSION for the round-turn PnL. If the PnL is negative, g_lossStreakCount increments and the loss amount is added to g_lossStreakAmt; if it's positive or zero, both reset to zero (one win wipes the streak). Two independent trigger paths then check the running streak: PauseOnConsecutiveLosses (default OFF) at PauseConsecutiveLossesCount=3 losses sets g_tradePauseUntil = TimeCurrent() + PauseConsecutiveLossesMinutes*60; PauseOnLossAmount (default OFF) at PauseLossAmount=100 USD sets the same kind of pause for PauseLossAmountMinutes=60 minutes. The two paths stack via MathMax, so triggering both gives the longer pause. Pause logging is throttled to once every 15 seconds to keep the Experts tab clean.

On the risk and sizing side, EX12053 offers two modes. The default is UseRiskPercent=false with FixedLot=0.10, which on a $100 account with a 300-point SL on XAUUSD represents roughly 30% margin on a typical gold contract — comfortable for a single-position lot, but with the 5-trade scale-in cap the EA can stack up to 0.50 lots. The second mode is UseRiskPercent=true with RiskPercent=1.0, in which case LotsByRisk() computes the lot size from AccountInfoDouble(ACCOUNT_BALANCE) * (RiskPercent/100) / (sl_points * valuePerPointPerLot), snapped to the symbol's SYMBOL_VOLUME_STEP and clamped to SYMBOL_VOLUME_MIN / SYMBOL_VOLUME_MAX. The function ClampVolume() does the snap-and-clamp math. There is no ATR-sizing, no per-trade risk override, no equity curve filter — the EA is intentionally small. The CTrade wrappers TryClose_EX12053, TryClosePartial_EX12053, and TryModify_EX12053 are present for any external utility hooks, each with a 3-attempt loop and 200ms/100ms sleep on requote or timeout.

The combination of a 14-input control surface, a 3-handle indicator stack, and a 4-condition signal makes EX12053 the most approachable member of the MultiIndicatorConfluence family. There is nothing in this EA that an intermediate trader cannot read end-to-end: the inputs are exactly what they say, the signal logic is the same code in GenerateSignal() you would write on a whiteboard, and the risk rules are explicit. What the EA gives up by being small is breadth — there is no regime classifier, no on-tester optimization, no pending-order infrastructure, no AutoTune volatility adaptation, no separate per-direction EMA — and what it gains is transparency. The HA-led 4-condition confluence is the design choice that ties it together: a single, testable, repeatable rule about what counts as a valid trend entry, applied on every new bar.

Strategy Deep Dive

On every tick, OnTick() calls PushSpreadSample() to keep a 20-tick rolling median of the current spread, then walks every open position and runs ApplyDynamicLockProfitToPosition() to tighten the SL one DLP step if price has advanced another 150 points in profit. When IsNewBar() returns true, the EA calls GenerateSignal(), which pulls the last two closed-bar values from the three native handles (EMA 21, EMA 50, MACD 12/26/9) and computes Heikin-Ashi on the closed bar from a 200-bar inline rate copy. The four confluence checks (HA direction, EMA cross, sign-bounded MACD cross, EMA slope) must all agree; otherwise the bar is skipped. If a valid signal survives PreflightAllowsEntry() (server-time session 7-22, median spread ≤ 3× recent typical, no active pause, trade count under cap), PlaceEntry() decides Initial vs Add#N from CountOpenPositions() and the per-direction counters, computes SL/TP from the 300/600 point defaults, and submits through a 3-retry, 3-filling-mode order sender. OnTradeTransaction() accumulates losses on closing deals and stacks pause windows when the consecutive-loss or loss-amount guards fire.

Entry Signal

Entry requires four independent conditions to agree on the just-closed bar: Heikin-Ashi direction (HA close above HA open for a long, or below for a short, with HA computed inline from a 200-bar raw-price copy), EMA(21) above EMA(50) for a long or below for a short, MACD main line above its signal line AND above zero (sign-bounded bullish cross) for a long or symmetric for a short, and the fast EMA sloping in the trade direction on at least MinEMASlopeBars-1 of the last MinEMASlopeBars bars as verified by EMASlopeOK(). A single sub-condition failure blocks the signal. Entries are then gated by PreflightAllowsEntry() (server-time session 7-22, median-spread cap at 3.0× the 20-tick median, no active pause window, trade count under MaxOpenTrades=5).

Exit Signal

Exits are driven primarily by the fixed TakeProfit at 600 points (1:2 RR against the 300-point SL) and by the stop-loss ratchet via ApplyDynamicLockProfitToPosition(). The DLP step-ratchet runs on every tick against every owned position and tightens the SL to entry + (steps × 150 − 20) points after each 150-point move in profit, so a deep enough move converts the SL into a trailing stop. There is no signal-based reversal exit — a position closes either at the TP, at the ratcheted SL, or at the initial SL, and the EA will not close one direction to open the opposite on the same signal bar.

Stop Loss

Initial SL is set at entry ± 300 points via StopLossPoints at order time and is then managed by the DLP step-ratchet that runs every tick. The ratchet only ever tightens (never loosens) and refuses to move the SL into the SYMBOL_TRADE_STOPS_LEVEL or the SYMBOL_TRADE_FREEZE_LEVEL bands, so a widening spread or a freeze-level protection will not be violated. After 150 points of progress the SL moves to entry+130, after 300 to entry+280, and so on, with InpLockMinusYPointsBuffer=20 keeping the lock just inside the round number.

Take Profit

TP is a fixed 600 points from the entry, set inline at order time via TakeProfitPoints=600 and never modified by the EA. This produces a 1:2 risk-to-reward ratio against the 300-point SL by construction. The ApplyDynamicLockProfitToPosition() function preserves the TP through every DLP step (it reads the current TP and passes it back unchanged in the modify request), so the EA does not need to choose between trailing the stop and holding the original TP — both happen simultaneously.

Best For

Best suited to XAUUSD on the M5 timeframe with a $100 minimum deposit at MEDIUM risk — a 0.10-lot default position with the 300/600 point SL/TP fits inside a typical micro-lot gold contract, and the 7-22 server-time session window covers both the London and New York sessions in sequence (so run on a GMT+2 or GMT+3 server for cleanest session coverage). The median-spread cap at 3.0× tolerates the wider spreads typical of retail gold brokers, but execution is still cleaner on an ECN or RAW-spread account with sub-4-point typical spread. The EA is not designed for sub-M5 timeframes (Heikin-Ashi smoothing becomes a liability when the raw candles are already small) and the 300-point SL is too tight for H4 and above where the daily range of gold routinely exceeds 1500 points.

Strategy Logic

Pipsgrowth EX12053 MultiIndicatorConfluence — Strategy Logic Analysis (from .mq5 source)

Family: MultiIndicatorConfluence Magic: 22212053 Version: 2.00

BRIEF: TrendCatcher EA using Heikin-Ashi direction + EMA(21/50) regime + MACD(12,26,9) cross for entry, with spread cap, session filter, DLP step-ratchet, initial vs additional trade gating, and pause guards on loss streaks. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • andleEMAfast
  • andleEMAslow
  • andleMACD

KEY FUNCTIONS:

  • NormalizePriceToTick()
  • IsNewBar()
  • InSession()
  • PushSpreadSample()
  • MedianSpread()
  • SpreadOkay()
  • CountOpenPositions()
  • CountAllOpenPositions()
  • OwnsPosition()
  • OwnsDeal()
  • IsAllSameDirProfitableAtLeast()
  • ClampVolume()
  • ...and 13 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (14 total across 7 groups):

  • [=== CORE ===] MagicNumber = 22212053 // 2220 + Expert ID (320)
  • [=== CORE ===] InpTradeComment = "Psgrowth.com Expert_12053" // ---- DYNAMIC LOCK PROFIT (DLP)
  • [=== DYNAMIC LOCK PROFIT ===] InpLockMinusYPointsBuffer = 20 // ---- INITIAL vs ADDITIONAL
  • [=== INITIAL vs ADDITIONAL ===] MinProfitPerTradeToAdd = 5.0 // points
  • [=== PAUSE GUARDS ===] PauseConsecutiveLossesMinutes = 60 // Pause by loss amount (deposit currency) across the current loss streak
  • [=== PAUSE GUARDS ===] PauseLossAmount = 100.0 // e.g., 100 = 100 USD
  • [=== PAUSE GUARDS ===] PauseLossAmountMinutes = 60 // ---- ENTRY & FILTERS
  • [=== ENTRY & FILTERS ===] SessionStartHour = 7 // server time
  • [=== ENTRY & FILTERS ===] SessionEndHour = 22 // server time
  • [=== ENTRY & FILTERS ===] SpreadMedianWindow = 20 // last N ticks median
  • [=== ENTRY & FILTERS ===] MinEMASlopeBars = 3 // EMA21 slope check length
  • [=== RISK & STOPS ===] RiskPercent = 1.0 // if UseRiskPercent=true
  • [=== RISK & STOPS ===] TakeProfitPoints = 600 // ---- EXECUTION
  • [=== EXECUTION ===] AllowBothDirections = true // if false, only trend-per regime
Pseudocode
// Pipsgrowth EX12053 MultiIndicatorConfluence — Execution Flow (from source analysis)
// Family: MultiIndicatorConfluence
// TrendCatcher EA using Heikin-Ashi direction + EMA(21/50) regime + MACD(12,26,9) cross for entry, with spread cap, session filter, DLP step-ratchet, initial vs additional trade gating, and pause guards on loss streaks. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

ON_INIT:
    Create indicator handles: andleEMAfast, andleEMAslow, andleMACD
    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:
M5H1

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 a chart matching the recommended timeframe
  7. 7Configure parameters according to the table on this page
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
MagicNumber222120532220 + Expert ID (320)
InpTradeComment"Psgrowth.com Expert_12053"---- DYNAMIC LOCK PROFIT (DLP)
InpLockMinusYPointsBuffer20---- INITIAL vs ADDITIONAL
MinProfitPerTradeToAdd5.0points
PauseConsecutiveLossesMinutes60Pause by loss amount (deposit currency) across the current loss streak
PauseLossAmount100.0e.g., 100 = 100 USD
PauseLossAmountMinutes60---- ENTRY & FILTERS
SessionStartHour7server time
SessionEndHour22server time
SpreadMedianWindow20last N ticks median
MinEMASlopeBars3EMA21 slope check length
RiskPercent1.0if UseRiskPercent=true
TakeProfitPoints600---- EXECUTION
AllowBothDirectionstrueif false, only trend-per regime
Source Code (.mq5)Open Source
Pipsgrowth_com_EX12053.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX12053 EX21 — TrendCatcher EA with Heikin-Ashi, EMA regime and MACD cross, full 12-layer stack."
#include <Trade\Trade.mqh>

//============================== INPUTS ==============================//
//---- CORE
input group "=== CORE ==="
input long   MagicNumber        = 22212053; // 2220 + Expert ID (320)
input string InpTradeComment = "Psgrowth.com Expert_12053";

//---- DYNAMIC LOCK PROFIT (DLP)
input group "=== DYNAMIC LOCK PROFIT ==="
input bool   InpEnableDynamicLockProfit = true;
input int    InpLockProfitEveryXPoints  = 150;
input int    InpLockMinusYPointsBuffer  = 20;

//---- INITIAL vs ADDITIONAL
input group "=== INITIAL vs ADDITIONAL ==="
input int     MaxOpenTrades                 = 5;
input bool    AllowOnlyProfitableAdditions  = true;
input double  MinProfitPerTradeToAdd        = 5.0; // points

//---- PAUSE GUARDS
input group "=== PAUSE GUARDS ==="
// Pause by consecutive losing trades
input bool   PauseOnConsecutiveLosses      = false;
input int    PauseConsecutiveLossesCount   = 3;
input int    PauseConsecutiveLossesMinutes = 60;
// Pause by loss amount (deposit currency) across the current loss streak
input bool   PauseOnLossAmount             = false;
input double PauseLossAmount               = 100.0;   // e.g., 100 = 100 USD
input int    PauseLossAmountMinutes        = 60;

//---- ENTRY & FILTERS
input group "=== ENTRY & FILTERS ==="
input int    EMA_Fast_Period   = 21;
input int    EMA_Slow_Period   = 50;
input int    MACD_Fast         = 12;
input int    MACD_Slow         = 26;
input int    MACD_Signal       = 9;
input bool   UseSessionFilter  = true;
input int    SessionStartHour  = 7;   // server time
input int    SessionEndHour    = 22;  // server time
input bool   UseSpreadCap      = true;
input int    SpreadMedianWindow= 20;  // last N ticks median
input double SpreadCapMultiplier = 3.0;
input int    MinEMASlopeBars   = 3;   // EMA21 slope check length

//---- RISK & STOPS
input group "=== RISK & STOPS ==="
input bool   UseRiskPercent    = false;
input double RiskPercent       = 1.0; // if UseRiskPercent=true
input double FixedLot          = 0.10;
input int    StopLossPoints    = 300;
input int    TakeProfitPoints  = 600;

//---- EXECUTION

Full source code available on download

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

Tags:ex12053multiindicatorconfluencepipsgrowthfreemt5xauusd

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_EX12053.mq5
File Size28.2 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyOther
Risk LevelMedium Risk
Timeframes
M5H1
Currency Pairs
XAUUSD
Min. Deposit$100