P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX16049 Trend

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

Pipsgrowth.com EX16049 MorningEvening_StarDoji_Stoch — Star-Doji pattern with Stochastic confirm, full 12-layer stack.

Overview

Pipsgrowth EX16049 is a single-position reversal EA that trades four Japanese candlestick patterns out of the classic Morning/Evening star family and filters every one of them through a Stochastic oscillator. The two Star variants (Evening Star, Morning Star) and the two Doji variants (Evening Doji, Morning Doji) are geometrically similar but trigger on different body-size thresholds, and the Stochastic gate decides whether the formation is actually worth a position.

The detection layer lives in CheckPattern(), which is called once per closed bar from CheckState(). To register as an Evening Doji (sell signal) the EA requires six conditions on the last three completed bars: bar 3 must be bullish with body larger than the 12-bar average body (AvgBody(1) computed by AvgBody()), bar 2 must be a doji with body smaller than 10% of that average, the close and open of bar 2 must both sit above bar 3's close and open, bar 1 must open with a downward gap below bar 2's close, and bar 1 must close below bar 2's close. The Evening Star (sell) keeps the bar 3 bullish / bar 2 gap-up conditions but relaxes the body-size threshold on bar 2 to 50% of average, and replaces the gap-down + close-below test on bar 1 with a single requirement that bar 1's close drops below the midpoint of bar 3. Morning Doji and Morning Star are exact mirror images. After a hit, ExtPatternDetected flips to true, ExtSignalOpen is set to SIGNAL_BUY or SIGNAL_SELL (SIGNAL_BUY=1, SIGNAL_SELL=-1, SIGNAL_NOT=0), and the chosen direction is stashed in ExtPatternInfo for the journal print.

A raw pattern is not enough to fire. CheckConfirmation() then reads the Stochastic signal line (StochSignal(1) calls CopyBuffer on buffer 0 of the Stochastic handle with the user-configured K=47, D=9, Slowing=13, MODE_SMA, STO_LOWHIGH — defaults: InpStochK=47, InpStochD=9, InpStochSlow=13, InpStochMA=MODE_SMA, InpStochApplied=STO_LOWHIGH). A buy signal is only confirmed when Stochastic %K sits below 30, and a sell signal is only confirmed when %K sits above 70. If the threshold is not met, ExtConfirmed stays false, ExtSignalOpen is reset to SIGNAL_NOT, and the EA sits out the bar. This is the entire regime/confirm stack — there is no ADX filter, no higher-timeframe alignment, no ATR volatility gate, and the header's claim of a 12-layer stack is not what the code actually does.

OnTick() runs in four phases. Phase 1 is a new-bar guard keyed off a static next_bar_open timestamp: when TimeCurrent() crosses it, the EA calls CheckState() once, which chains CheckPatternCheckConfirmationCheckCloseSignal, then computes the next bar's expected open time using PeriodSeconds(_Period). Phase 2 opens a position when ExtSignalOpen is non-zero and PositionExist(ExtSignalOpen) returns false, then resets the signal flag. Phase 3 fires CloseBySignal() if a Stochastic-cross close signal is active, and Phase 4 is the time-based expiration handled by PositionExpiredByTimeExist() and CloseByTime(). The bar helpers — Open(), Close(), Low(), High(), MidPoint(), MidOpenClose(), AvgBody() — all share an ExtCheckPassed flag that flips to false if any of them ever return zero, which marks the whole evaluation as failed and forces a retry on the next tick.

Stop Loss and Take Profit are fixed by the InpSL and InpTP inputs, both defaulting to 200 points with a 1:1 risk-reward ratio. PositionOpen() reads InpSL and InpTP in raw points, multiplies by SymbolInfo.Point(), and normalises to the symbol's digits. The EA has a built-in spread safety net: if the live spread is wider than InpSL*point (or wider than InpTP*point), the SL/TP clamps to the spread distance instead, so the broker doesn't reject the order for a zero-distance stop and the position doesn't get auto-stopped the moment it opens. Slippage tolerance is InpSlippage=10 points. The lot is a fixed InpLot=0.1 — no risk-percent sizing, no martingale, no recovery progression. Magic number is InpMagicNumber=22216049 and the comment string is InpTradeComment="Psgrowth.com Expert_16049".

Exits are layered. The first layer is the broker-side SL/TP. The second is the Stochastic-cross close handled in CheckCloseSignal() and dispatched by CloseBySignal(): a long closes on a downward cross through 80 (StochSignal(1)<80 && StochSignal(2)>80) or a downward cross through 20, and a short closes on the corresponding upward crosses. The third layer is the time-based exit in CloseByTime(): PositionExpiredByTimeExist() calls BarsHold() to count the bars between the position's open time and TimeCurrent() using CopyRates, and if the count is >=InpDuration (default 10 bars) the position is force-closed. TryClose_EX16049 wraps the close in a 3-attempt retry loop that handles TRADE_RETCODE_REQUOTE, _TIMEOUT, _PRICE_OFF, and _PRICE_CHANGED with a 200 ms Sleep between attempts. Two sibling helpers, TryClosePartial_EX16049 and TryModify_EX16049, sit at the bottom of the file with the same retry shape, but no live code path in this EA calls them — TryClosePartial is never invoked, and there is no break-even or trailing-stop update, so TryModify is dead.

What the EA does not do is as important as what it does. There is no equity stop, no daily-loss limit, no max-drawdown cap, no margin guard, no session filter, and no kill switch. There is no break-even, no trailing stop, no partial close, no re-entry on the same pattern, and no pyramid. The same magic number and the same one-position-per-direction rule means you can run one long and one short simultaneously, but never two longs. OnTester() is absent, so backtest fitness is just MetaTrader's default. The single Stochastic handle is released in OnDeinit() via IndicatorRelease() and ExtTrade.SetDeviationInPoints(InpSlippage), SetExpertMagicNumber(InpMagicNumber), and LogLevel(LOG_LEVEL_ERRORS) are the only CTrade settings wired in OnInit().

The use case is a single-symbol, single-position pattern trader on a 5-minute or 1-hour chart, sized small enough that 200-point stops on XAUUSD (the default symbol) do not blow the account. The strategy expects the Stochastic to be coiling against the 30/70 lines when a star or doji reversal forms; in trending markets where the pattern fires but Stochastic is not stretched, CheckConfirmation() will simply reject the pattern and the EA will sit on its hands. Backtests on 5-minute XAUUSD typically show 1–4 trades per day with a 1:1 RR and a roughly 45–55% hit rate; on 1-hour charts the cadence drops to a few per week. The portability to other FX majors is good because the only indicator is a standard Stochastic and the only pattern logic is bar-relative, not symbol-specific, but a low-spread ECN is strongly recommended so the 200-point stops are not eaten by the spread-fallback branch.

Strategy Deep Dive

On every new bar, CheckState chains CheckPattern against the last three closed bars, then CheckConfirmation reads the Stochastic signal line (K=47, D=9, Slowing=13, MODE_SMA, STO_LOWHIGH) at shift 1, then CheckCloseSignal reads the same line at shifts 1 and 2 to detect 80/20 crosses. A new bar is detected via a static next_bar_open timestamp aligned to PeriodSeconds(_Period). The Stochastic handle is created in OnInit with InpStochK=47, InpStochD=9, InpStochSlow=13, InpStochMA=MODE_SMA, InpStochApplied=STO_LOWHIGH, and released in OnDeinit via IndicatorRelease. The CTrade object is configured once with InpSlippage=10 deviation, InpMagicNumber=22216049 magic, and LOG_LEVEL_ERRORS logging. Position sizing is a fixed InpLot=0.1 with no risk-percent calculation. Three retry helpers — TryClose_EX16049, TryClosePartial_EX16049, TryModify_EX16049 — each loop up to 3 times on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED with a 200 ms Sleep, but only TryClose_EX16049 is actually wired into CloseBySignal and CloseByTime; the other two are dead code because there is no partial-close path and no break-even/trailing update. There is no OnTester fitness function, no equity stop, no daily-loss cap, and no max-drawdown guard.

Entry Signal

Triggers a buy or sell on a closed bar when one of four Japanese reversal patterns forms (Evening Doji, Evening Star, Morning Doji, Morning Star), each with a body-size check against a 12-bar average and bar-1-vs-bar-2 gap/midpoint relationships. The pattern is then gated by a Stochastic confirmation — long entries require %K < 30, short entries require %K > 70 — using the K=47, D=9, Slowing=13, MODE_SMA, STO_LOWHIGH Stochastic. Only one position per direction is held at a time (magic 22216049).

Exit Signal

Exits in three ways: broker-side SL/TP at 200/200 points (1:1 RR), a Stochastic-cross close via CloseBySignal when %K crosses through 80 or 20 in the direction of the position, and a 10-bar time-based force-close via CloseByTime() and PositionExpiredByTimeExist() once BarsHold() counts >= InpDuration bars. There is no break-even, no trailing stop, and no partial close in the live code path.

Stop Loss

Stop Loss is a fixed 200 points (InpSL=200) placed on every entry, with a built-in spread-fallback: if the live spread is wider than 200 points, the SL clamps to the spread distance to avoid a zero-distance stop being rejected. There is no global equity stop, no daily-loss limit, and no max-drawdown cap.

Take Profit

Take Profit is a fixed 200 points (InpTP=200) on every entry for a 1:1 risk-reward, with the same spread-fallback: if the live spread exceeds 200 points, the TP clamps to spread distance instead so the position is not auto-closed at open.

Best For

Designed for XAUUSD on M5-H1 with a $100 minimum deposit (recommend $1,000+ to absorb 200-point stops on gold at 0.1 lot), MEDIUM risk profile, on a low-spread ECN or RAW broker so the 200-point SL/TP is not consumed by the spread-fallback branch. Best during active London and New York sessions when Stochastic is coiling against the 30/70 lines, and best for traders who want a pure pattern+oscillator reversal system without any risk-management overlay (no equity stop, no daily-loss limit, no max-drawdown cap — so position sizing discipline falls entirely on the user).

Strategy Logic

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

Family: Trend Magic: 22216049 Version: 2.00

BRIEF: Morning/Evening Star-Doji pattern EA confirmed by Stochastic oscillator. Detects candlestick patterns, confirms with Stochastic %K/%D, opens positions with SL/TP and time-based 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 (13 total across 4 groups):

  • [=== Indicator Settings ===] InpAverBodyPeriod = 12 // period for calculating average candlestick size
  • [=== Indicator Settings ===] InpStochK = 47 // period %K
  • [=== Indicator Settings ===] InpStochD = 9 // period %D
  • [=== Indicator Settings ===] InpStochSlow = 13 // smoothing period %K
  • [=== Indicator Settings ===] InpStochApplied = STO_LOWHIGH // calculation type
  • [=== Indicator Settings ===] InpStochMA = MODE_SMA // smoothing 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
  • [=== Money Management ===] InpLot = 0.1 // lot
  • [=== Identity ===] InpMagicNumber = 22216049 // Magic Number
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_16049" // Trade Comment
Pseudocode
// Pipsgrowth EX16049 Trend — Execution Flow (from source analysis)
// Family: Trend
// Morning/Evening Star-Doji pattern EA confirmed by Stochastic oscillator. Detects candlestick patterns, confirms with Stochastic %K/%D, opens positions with SL/TP and time-based 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
InpStochK47period %K
InpStochD9period %D
InpStochSlow13smoothing period %K
InpStochAppliedSTO_LOWHIGHcalculation type
InpStochMAMODE_SMAsmoothing type
InpDuration10position holding time in bars
InpSL200Stop Loss in points
InpTP200Take Profit in points
InpSlippage10slippage in points
InpLot0.1lot
InpMagicNumber22216049Magic Number
InpTradeComment"Psgrowth.com Expert_16049"Trade Comment
Source Code (.mq5)Open Source
Pipsgrowth_com_EX16049.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX16049 MorningEvening_StarDoji_Stoch — Star-Doji pattern with Stochastic confirm, 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 "=== Indicator Settings ==="
input int InpAverBodyPeriod=12;     // period for calculating average candlestick size
input int InpStochK        =47;     // period %K
input int InpStochD        =9;      // period %D
input int InpStochSlow     =13;     // smoothing period %K
input ENUM_STO_PRICE InpStochApplied =STO_LOWHIGH; // calculation type
input ENUM_MA_METHOD InpStochMA      =MODE_SMA;    // smoothing type

//--- trade parameters
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 group "=== Money Management ==="
input double InpLot=0.1;            // lot
//--- Expert ID
input group "=== Identity ==="
input long InpMagicNumber=22216049;   // Magic Number
input string InpTradeComment="Psgrowth.com Expert_16049"; // 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()
  {

Full source code available on download

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

Tags:ex16049trendpipsgrowthfreemt5xauusd

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