P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX16021 Trend

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

Pipsgrowth.com EX16021 BlackCrows_WhiteSoldiers_MFI — Candlestick pattern with MFI confirmation, full 12-layer stack.

Overview

Pipsgrowth EX16021 reads three consecutive candles as a single geometric formation rather than trusting any standard indicator stack. The strategy is built around two of the oldest reversal patterns in Japanese candlestick theory — Three Black Crows at tops and Three White Soldiers at bottoms — but the EA defines them with a tighter set of rules than a textbook would. To qualify, each of the last three bars must have a body that exceeds the 12-bar average body size (InpAverBodyPeriod = 12) AND the midpoint of each bar (defined as (High + Low) / 2 inside the MidPoint() helper) must step strictly in the direction of the pattern. A black candle must open above its close, a white candle must close above its open, and the midpoints have to cascade downward for the bearish three crows or upward for the bullish three soldiers. That cascade rule is the heart of the strategy: it filters out noisy three-bar sequences that look bearish in body size but don't actually step lower in their range midpoints, which is a common failure mode of naive candlestick recognition.

The candlestick geometry is only half of the entry decision. The other half comes from the MFI oscillator configured at period 37 with VOLUME_TICK applied volume (InpPeriodMFI = 37, InpVolume = VOLUME_TICK). The 37-period MFI is a deliberately slow choice — most chart packages default to 14, so the EA is reading money flow over more than a full trading day's worth of bars on M5. A buy signal from Three White Soldiers only gets executed when the MFI(1) value is below 40, meaning money flow is depressed enough to make the bullish reversal plausible from an oversold baseline. A sell signal from Three Black Crows only gets executed when MFI(1) is above 60, requiring elevated money flow to support the bearish reversal. This confirmation asymmetry — buys need depressed flow, sells need elevated flow — is the EA's way of forcing the oscillator to agree with the price geometry before any order goes to the broker.

Once a pattern is detected and confirmed, PositionOpen() fires a market order at the current Ask (for buys) or Bid (for sells) with the configured fixed lot (InpLot = 0.10) and the configured 200-point stop loss and 200-point take profit (InpSL = 200, InpTP = 200). The 1:1 risk-reward ratio at fixed pips means the EA expects to lose about as often as it wins on a per-trade basis and relies on a hit rate above 50% (or favorable money flow timing) to come out ahead. There is a useful safety net inside PositionOpen(): if the current spread is wider than the configured stop loss — for example, if the broker is quoting a 250-point spread while InpSL is 200 — the EA overrides the stop to a single spread's distance from the entry price and logs a warning. The same override applies to the take profit. Without this guard, a buy order with a 200-point stop during a 250-point spread would be rejected by the broker, and the trade would simply not happen. With the guard, the trade goes through at a degraded stop distance rather than being skipped entirely.

Exits in EX16021 come from three independent sources, evaluated in order. The first is an MFI cross-signal in CheckCloseSignal(): a long position is closed if MFI(1) drops below 70 while MFI(2) was above 70 (overbought-to-cooling cross) OR if MFI(1) drops below 30 while MFI(2) was above 30 (oversold confirmation). A short position is closed on the mirror: MFI(1) above 30 with MFI(2) below 30, or MFI(1) above 70 with MFI(2) below 70. This MFI cross logic uses the same indicator and the same 70/30 thresholds but applies them to the close decision rather than the entry decision — the same oscillator is doing double duty as both gate and trigger. The second exit source is the hard time stop (InpDuration = 10): the BarsHold() helper copies MqlRates from the position's open time to TimeCurrent() and returns the number of bars in between, and CloseByTime() force-closes any position that has held for 10 or more bars. The third exit source is the static 200/200 SL/TP, which catches anything that the MFI cross and the time stop both missed. There is no trailing stop, no break-even, no partial close, and no scaling in or out — the only position management is the trio of MFI cross, time stop, and fixed pips.

A point worth flagging: the header comment claims a 12-layer architecture (REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester), but only seven of those layers are actually wired into the code. SIGNAL (the candlestick pattern) is wired. ENTRY (market order) is wired. CONFIRM (MFI gate) is wired. NO-TRADE (the new-bar guard via the static next_bar_open datetime in OnTick) is wired. RISK (200-point SL) is wired. SIZING (fixed 0.10 lot) is wired. EXIT (MFI cross + time + SL/TP) is wired. What is NOT wired: REGIME detection (no volatility filter, no session filter, no trend filter — the body-size check inside CheckPattern() is the only proxy), CAPITAL CAP (no daily loss limit, no equity drawdown stop, no max-position guard), MANAGE (no trailing, no break-even, no partial), SCALING (no pyramiding, no martingale, no grid), and OnTester (no custom optimization criterion — the EA does not export a tester fitness function). Three retry helpers are defined at the bottom of the file — TryClose_EX16021, TryClosePartial_EX16021, and TryModify_EX16021 — each attempting the trade action up to three times with 100–200ms sleeps on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED. TryClose_EX16021 is wired into CloseBySignal() and CloseByTime(); TryClosePartial and TryModify are dead code that is never called from any active function.

EX16021 carries magic 22216021, which makes it a sibling to EX16020 (magic 22216020). The two EAs share the same strategy, the same fixed 0.10 lot, the same 200/200 SL/TP, the same 10-bar time stop, and the same MFI(37) confirmation thresholds, but they are independent trade streams because of the unique magic. A practical deployment is to run both on the same XAUUSD M5 chart on the same account: because the magic number filters positions, EX16021 will only manage its own trades and will not touch EX16020's open positions or vice versa, so the combined exposure is two concurrent trades when both fire on the same bar. The default timeframe is M5 and the alternative the header recommends is H1; the same source code runs on both because the candlestick definitions are timeframe-agnostic and the MFI(37) period scales naturally. The minimum recommended balance is $100 USD (the InpLot of 0.10 lot on XAUUSD implies a notional of roughly 1,000 USD at XAUUSD = 2,000, so a $100 account runs 10:1 notional leverage, which is high but workable for a 1:1 risk-reward scalper). The risk level is classified MEDIUM because the fixed 0.10 lot and the 1:1 risk-reward create volatility around the equity curve, even though the strategy is mechanically simple.

What to expect in backtest: a relatively small number of trades per week (the three-candle cascade is a strict filter and the MFI gate eliminates more than half of the patterns that form), with a hit rate that needs to stay above 50% for the 1:1 risk-reward to produce a positive expectancy. The 10-bar time stop means the EA never holds through a weekend or through major news, which removes gap risk as a failure mode. The spread-overrides-stop safety means the worst-case loss on a single trade in extreme spread conditions is one full spread, not a blown-through stop. The OnTick function has four phases: Phase 1 calls CheckState() at the new bar to set ExtPatternDetected, ExtConfirmed, ExtSignalOpen, ExtSignalClose, and ExtPatternInfo; Phase 2 opens a position if there is a signal and no position in that direction; Phase 3 closes a position if there is a close signal; Phase 4 force-closes any position that has held for 10 or more bars. The new-bar guard (the static datetime next_bar_open inside OnTick) ensures the EA does not act on the same signal multiple times within a single bar, which is critical because the MFI and pattern readings can flicker on intra-bar ticks.

If you are running this EA, two configuration decisions matter. First, pick a broker with low spread on XAUUSD because the spread-overrides-stop safety will degrade the 200-point stop distance to whatever the spread is whenever the market widens — a 50-point spread broker will preserve most of the 200-point stop, while a 250-point spread broker will collapse the stop to 250 points on most trades. Second, decide whether you want to run the MFI confirmation enabled or disabled by leaving the InpPeriodMFI and InpVolume inputs at their defaults — the defaults (37 and VOLUME_TICK) are the values the strategy was designed around, and changing them will change the entry frequency and the win rate without any guidance from the source on what the new optimum looks like. The EA does not log trade results in a custom file and does not push notifications — only Print() statements to the terminal — so plan to read the MT5 journal to see what happened on any given day.

Strategy Deep Dive

OnTick runs four phases guarded by a static next_bar_open datetime so the same signal cannot fire twice within a bar. Phase 1 calls CheckState() at the new bar, which runs CheckPattern() to detect the three-candle cascade (each body > 12-bar average body, midpoints strictly stepping in pattern direction), CheckConfirmation() to require MFI(1) < 40 for buys or MFI(1) > 60 for sells via the MFI(37) handle, and CheckCloseSignal() to evaluate the MFI cross logic. Phase 2 fires PositionOpen() with the fixed 0.10 lot and the configured 200/200 SL/TP. Phase 3 calls CloseBySignal() which routes through TryClose_EX16021 (up to 3 attempts with 200ms sleeps on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED) when an MFI cross-signal triggers. Phase 4 calls CloseByTime() to force-close any position whose BarsHold() count has reached InpDuration = 10. Two retry helpers (TryClosePartial_EX16021 and TryModify_EX16021) are defined but never called from any active function, and 5 of the 12 header-claimed layers (REGIME, CAPITAL CAP, MANAGE, SCALING, OnTester) are not wired into the code.

Entry Signal

Three consecutive candles whose bodies each exceed the 12-bar average body size (InpAverBodyPeriod = 12) and whose range midpoints cascade strictly in the pattern direction, gated by the MFI(37) oscillator: long entry on Three White Soldiers with MFI(1) < 40, short entry on Three Black Crows with MFI(1) > 60.

Exit Signal

Three independent exit sources in priority order: (1) MFI(37) cross-signal in CheckCloseSignal closing longs on MFI(1) < 70 with prior MFI(2) > 70 OR MFI(1) < 30 with prior MFI(2) > 30, and shorts on the mirror through the 30 and 70 thresholds; (2) hard 10-bar time stop in CloseByTime force-closing any position that has held for InpDuration = 10 bars via the BarsHold() CopyRates-based bar count; (3) static 200/200 SL/TP. No trailing stop, no break-even, no partial close, no scaling in or out.

Stop Loss

Fixed 200-point stop loss (InpSL = 200) on every market order, with a safety override in PositionOpen() that collapses the stop distance to a single spread if the broker's current spread is wider than the configured stop, to prevent broker-side rejection during volatile quotes.

Take Profit

Fixed 200-point take profit (InpTP = 200) on every market order, producing a symmetric 1:1 risk-reward ratio with the stop loss. Same spread-overrides-stop safety applies: if the current spread exceeds the configured TP, the EA sets takeprofit to a single spread's distance from the entry price instead of skipping the trade.

Best For

Recommended for XAUUSD traders running M5 (default) or H1 (alternative) on an ECN/RAW-spread broker where the typical spread stays well under 200 points so the spread-overrides-stop safety does not collapse the SL/TP. Minimum recommended balance is $100 USD; the fixed 0.10 lot implies roughly 10:1 notional leverage on gold at current prices, which fits a MEDIUM-risk account comfortable with the 1:1 risk-reward volatility. Best deployed as a sibling to EX16020 (magic 22216020) for users who want two independent streams of the same Three Crows / White Soldiers + MFI strategy on the same XAUUSD M5 chart, since the unique magic 22216021 filters EX16021 to its own positions only.

Strategy Logic

Pipsgrowth EX16021 Trend — Strategy Logic Analysis (from .mq5 source)

Family: Trend Magic: 22216021 Version: 2.00

BRIEF: Candlestick pattern EA that detects Three Black Crows and Three White Soldiers formations, confirms with MFI oscillator, and enters with fixed SL/TP and time-based position exit. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • CheckState()
  • PositionOpen()
  • CloseBySignal()
  • CloseByTime()
  • PositionExist()
  • PositionExpiredByTimeExist()
  • BarsHold()
  • Open()
  • Close()
  • Low()
  • High()
  • MidPoint()
  • ...and 9 more

INTERNAL CONSTANTS (3 total):

  • SIGNAL_BUY = 1 // Buy signal
  • SIGNAL_NOT = 0 // no trading signal
  • CLOSE_LONG = 2 // signal to close Long

INPUT PARAMETERS (10 total across 2 groups):

  • [=== STRATEGY PARAMETERS ===] InpAverBodyPeriod = 12 // period for calculating average candlestick size
  • [=== STRATEGY PARAMETERS ===] InpPeriodMFI = 37 // MFI period
  • [=== STRATEGY PARAMETERS ===] InpVolume = VOLUME_TICK // volume type
  • [=== TRADE PARAMETERS ===] InpDuration = 10 // position holding time in bars
  • [=== TRADE PARAMETERS ===] InpSL = 200 // Stop Loss in points
  • [=== TRADE PARAMETERS ===] InpTP = 200 // Take Profit in points
  • [=== TRADE PARAMETERS ===] InpSlippage = 10 // slippage in points
  • [=== TRADE PARAMETERS ===] InpLot = 0.1 // lot
  • [=== TRADE PARAMETERS ===] InpMagicNumber = 22216021 // Magic Number
  • [=== TRADE PARAMETERS ===] InpTradeComment = "Psgrowth.com Expert_16021" // Trade Comment
Pseudocode
// Pipsgrowth EX16021 Trend — Execution Flow (from source analysis)
// Family: Trend
// Candlestick pattern EA that detects Three Black Crows and Three White Soldiers formations, confirms with MFI oscillator, and enters with fixed SL/TP and time-based position exit. 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:
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 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
InpAverBodyPeriod12period for calculating average candlestick size
InpPeriodMFI37MFI period
InpVolumeVOLUME_TICKvolume type
InpDuration10position holding time in bars
InpSL200Stop Loss in points
InpTP200Take Profit in points
InpSlippage10slippage in points
InpLot0.1lot
InpMagicNumber22216021Magic Number
InpTradeComment"Psgrowth.com Expert_16021"Trade Comment
Source Code (.mq5)Open Source
Pipsgrowth_com_EX16021.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX16021 BlackCrows_WhiteSoldiers_MFI — Candlestick pattern with MFI confirmation, full 12-layer stack."

#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>

#define SIGNAL_BUY    1             // Buy signal
#define SIGNAL_NOT    0             // no trading signal
#define SIGNAL_SELL  -1             // Sell signal

#define CLOSE_LONG    2             // signal to close Long
#define CLOSE_SHORT  -2             // signal to close Short

//--- Input parameters
input group "=== STRATEGY PARAMETERS ==="
input int  InpAverBodyPeriod=12;    // period for calculating average candlestick size
input int  InpPeriodMFI     =37;    // MFI period
input ENUM_APPLIED_VOLUME InpVolume=VOLUME_TICK;   // volume type

input group "=== TRADE PARAMETERS ==="
input uint InpDuration=10;          // position holding time in bars
input uint InpSL      =200;         // Stop Loss in points
input uint InpTP      =200;         // Take Profit in points
input uint InpSlippage=10;          // slippage in points
//--- money management parameters
input double InpLot   =0.1;         // lot
//--- Expert ID
input long InpMagicNumber=22216021;   // Magic Number
input string InpTradeComment="Psgrowth.com Expert_16021"; // Trade Comment

//--- global variables
int    ExtAvgBodyPeriod;            // average candlestick calculation period
int    ExtSignalOpen     =0;        // Buy/Sell signal
int    ExtSignalClose    =0;        // signal to close a position
string ExtPatternInfo    ="";       // current pattern information
string ExtDirection      ="";       // position opening direction
bool   ExtPatternDetected=false;    // pattern detected
bool   ExtConfirmed      =false;    // pattern confirmed
bool   ExtCloseByTime    =true;     // requires closing by time
bool   ExtCheckPassed    =true;     // status checking error

//---  indicator handle
int    ExtIndicatorHandle=INVALID_HANDLE;

//--- service objects
CTrade      ExtTrade;
CSymbolInfo ExtSymbolInfo;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   Print("InpSL=", InpSL);
   Print("InpTP=", InpTP);
//--- set parameters for trading operations
   ExtTrade.SetDeviationInPoints(InpSlippage);    // slippage
   ExtTrade.SetExpertMagicNumber(InpMagicNumber); // Expert Advisor ID

Full source code available on download

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

Tags:ex16021trendpipsgrowthfreemt5xauusd

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_EX16021.mq5
File Size25.6 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M5H1
Currency Pairs
XAUUSD
Min. Deposit$100