P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX16004 Trend

MT5 Expert Advisor (Open Source) · XAUUSD, EURUSD, GBPUSD, USDJPY · D1, H4

Pipsgrowth.com EX16004 Price_Action_EA — 2-bar reversal price action EA, full 12-layer stack.

Overview

The 2-bar reversal EA built for traders who don't trust indicators.

Pipsgrowth EX16004 Trend runs on a deliberately minimalist premise: read two consecutive closed bars, and act only when the second one fails to follow through on the first. There is no moving average, no oscillator, no multi-timeframe stack — just bar[1] and bar[2] doing the talking, and a 14-period Average True Range doing the math for the stop distance and trailing ratchet. That compactness is the EA's defining feature. In a PipsGrowth corpus full of multi-indicator trend followers, EX16004 stands out as the price-action native — the strategy that argues two candles of honest rejection are worth more than five overlapping filters.

The two patterns are mirrors of each other, and both encode a specific market story: a failed breakout in one direction, immediately followed by a bar that closes back inside the prior range. The 2-bar reversal is, in market-microstructure terms, a liquidity grab — a stop hunt beyond the obvious level that produces a wick on bar[1] and a body close back on the right side of the prior bar's extreme.

A BUY fires when bar[2] is bearish (close[2] < open[2]) AND bar[1] makes a new low (low[1] < low[2]) but bar[1] closes back above bar[2]'s low (close[1] > low[2]). The bear pattern is already in motion; bar[1] extends it to a fresh extreme; but the buyers reclaim the bar and close back inside. Buyers won.

A SELL fires symmetrically: bar[2] is bullish, bar[1] takes out the prior high (high[1] > high[2]), but bar[1] closes back below bar[2]'s high. The bull pattern was the bait; the bar[1] upper wick is the trap; the close is the rejection.

Both signals use fully closed bars (bar[1] and bar[2]), so the entry fires only on the open of bar[0] — no repaint, no live-bar re-evaluation. The same closed-bar discipline applies to the ATR(14) read in CheckSignal(): SL/TP are computed off bar[1]'s ATR, not the still-forming bar[0].

Position management: the 14-period ATR does triple duty

Initial stop is ATR × InpATR_Multiplier (default 2.0), and the take-profit is stop × InpRiskReward (default 2.0), giving a fixed 1:2 reward-to-risk on the static level placed at entry. Once in profit, the ManageOpenPositions() function runs every tick and applies a two-stage ratchet:

Breakeven — when profit distance ≥ ATR × InpBEStart_ATR (default 1.0), the stop moves to open + InpBEOffset × Point for buys (and open − offset for sells). The 30-point offset means the breakeven stop is placed slightly past entry, not exactly at it, so a small spread-induced whipsaw can't re-stop the trade after the BE fires.

Trailing stop — when profit distance ≥ ATR × InpTrailStart_ATR (default 1.5), the stop follows price at a distance of ATR × InpTrailDist_ATR (default 0.5). A tighter trail (0.5× ATR) is intentionally less generous than the breakeven trigger (1.0× ATR), so the trade has room to breathe before the trail kicks in. The trailing stop never goes below entry (the trailSL > openPrice check on line 447 enforces this).

Both stages are wired through TryModify_EX16004(), which retries up to 3 times on REQUOTE / TIMEOUT before giving up — a small but real protection against broker requote storms on D1-bar opens when volatility spikes.

Pyramiding (off by default)

InpEnablePyramid = false is the shipped default. When the trader turns it on, the EA permits up to InpMaxPositions = 2 in the same direction, but every additional entry is gated by IsGridSafe() — a guard that walks the open-position list and refuses to add unless every existing same-direction position is in profit by at least InpMinProfitPoints = 300 points. The 300-point floor (3 pips on a 5-digit pair, 30 points on XAUUSD) prevents the EA from averaging into a loser; it can only scale into a confirmed winner. A blocked pyramid logs a Pyramid BLOCKED line to the journal with the actual profit distance and the required threshold.

Drawdown protection

CheckDrawdownLimits() compares two real-time metrics each tick:

  • Daily loss — InpMaxDailyLoss = 3.0% of g_dailyStartBalance (the balance at the start of the trading day, refreshed at CheckNewDay() at server midnight).
  • Equity drawdown from peak — InpMaxEquityLoss = 10.0% of g_peakEquity (the highest equity seen since the EA attached, updated each tick).

Either threshold trips g_ddLimitHit, which halts all new entries for the rest of the day. If InpCloseOnDDLimit = true (the default), the EA also fires CloseAllPositions() to flatten the book. The day reset happens at server midnight via CheckNewDay(), which compares a YYYY.MM.DD string to g_lastDayTime — so a Sunday re-attachment after a weekend flat does not inherit a stale daily-loss flag.

Time filter

CheckTimeFilter() enforces a Monday-to-Friday window. By default it accepts all 24 hours (InpStartHour = 0 to InpEndHour = 23), but the trade decision happens on D1 bars, so the actual decision point is the daily bar open — not the minute clock. InpFridayCloseHour = 20 calls CloseAllPositions() on Friday at 20:00 server time, which means the EA is flat going into the weekend. Weekend trading is blocked by the day_of_week == 0 || day_of_week == 6 check.

Slippage, spread, retries

InpSlippage = 30 points is the cap passed to trade.SetDeviationInPoints(). InpMaxSpread = 250 points (2.5 pips on a 5-digit FX pair, 25 points on XAUUSD) is the no-trade gate. For D1/H4 trading this is loose — it filters out the worst illiquidity events but lets through normal spreads on a standard ECN book. InpMaxRetries = 3 is the in-loop retry count for OpenPosition(); after each failed attempt the code Sleep(100), refreshes the symbol, and tries again.

Sizing and account cap

CalculateLotSize() resolves a risk-based lot: riskMoney = balance × InpRiskPercent / 100 (default 1%), divided by the per-lot loss at the stop distance, then NormalizeLot()-clamped to the symbol's lot step, between minLot and MathMin(maxLot, InpMaxLotSize = 5.0). Setting InpRiskPercent = 0 falls back to InpFixedLot = 0.01 for the all-fixed-size mode. Before sending the order, OpenPosition() calls OrderCalcMargin() to confirm the account has enough free margin — no partial fills, no rejected orders from under-margined attempts.

Fill policy

SetProperFillingMode() reads SYMBOL_FILLING_MODE at OnInit and chooses FOK, IOC, or RETURN based on what the broker advertises. Exness / IC Markets / Pepperstone support is therefore automatic — no input needed and no per-broker template required.

Chart panel

A 220×140 dark-slate-gray rectangle in the top-left corner with six labels: title (gold), magic number, current ATR, spread, buy/sell position counts, and live P&L (lime if positive, red if negative). The panel is created in CreateInfoPanel() and refreshed on every OnTick() by UpdateInfoPanel(). All chart objects are prefixed EA_ and cleared in OnDeinit() so that removing the EA from the chart leaves no orphan objects behind.

What it does not have

There is no OnTester() function in the source — the brief in the file header lists "OnTester" as one of 12 layers, but the .mq5 does not actually implement a custom optimization criterion. There is no multi-timeframe read (the EA only sees _Period bars), no news filter, no session-specific behavior beyond the Mon-Fri and Friday-close gates, and no hedging logic — IsGridSafe() operates only on same-direction positions, so a buy and a sell can coexist on the same symbol if both patterns fire on adjacent bars. TryClosePartial_EX16004 is defined as a 3-attempt retry helper but is not wired into any live call in this source — the EA never partial-closes.

What to expect in backtest

D1 reversal patterns are rare — typical frequency is 1-3 signals per pair per month on liquid FX, more on XAUUSD where the daily range is wider. The 1:2 RR and the trailing ratchet are designed to make the few winners count: a single trend day that runs 3× ATR after the trail activates (which kicks in at 1.5× ATR) can return 2-3× the initial stop. The 3% daily DD cap means the EA will not fight a bad day past the third percent; the 10% equity-peak cap means the equity curve can give back up to a tenth of its high-water mark before the EA goes quiet for the session.

Strategy Deep Dive

Each tick, OnTick() refreshes the symbol, enforces the 250-point spread cap and the Mon-Fri / Friday-close time filter, walks the open positions through ManageOpenPositions() for the BE/trailing ratchet using the latest ATR(14), and reads the current bar's open time to detect a new bar. On a new bar, CheckNewDay() resets the daily balance and g_ddLimitHit flag at server midnight, then CheckSignal() evaluates the 2-bar reversal pattern using bar[1] and bar[2]. If the pattern matches and no same-direction position is already open, OpenPosition() computes ATR-based SL/TP, calls CalculateLotSize() for risk-based sizing, and submits with up to 3 retries on REQUOTE / TIMEOUT / PRICE_OFF / PRICE_CHANGED. The drawdown gate runs every tick: CheckDrawdownLimits() compares balance-to-start-of-day and equity-to-peak, and either threshold trips g_ddLimitHit which blocks entries (and optionally closes all) until the next server day.

Entry Signal

A BUY signal fires when bar[2] is bearish and bar[1] extends below bar[2]'s low but closes back above it — a failed-breakdown wick rejection that returns buyers to the prior range. A SELL signal mirrors that: bar[2] bullish, bar[1] pokes above bar[2]'s high, but bar[1] closes back below it. Both signals use fully closed bars (bar[1] and bar[2]) so entries are decided on the open of bar[0] and do not repaint. ATR(14) sized to InpATR_Multiplier (default 2.0) sets the initial stop distance, and the take-profit is SL × InpRiskReward (default 2.0).

Exit Signal

The TP is the static level placed at entry (default 1:2) and the trade-management stack ratchets the stop first to breakeven after 1.0× ATR profit (+30 points offset) and then to a trailing stop after 1.5× ATR profit at 0.5× ATR distance. There is no separate exit signal — the position closes on TP, the trailing stop, or the breakeven stop. An opposite-direction 2-bar reversal does not close the existing position; it opens a new opposing position, which IsGridSafe() may gate when pyramiding is enabled. TryModify_EX16004 retries the stop modification up to 3 times on REQUOTE / TIMEOUT before giving up.

Stop Loss

Initial stop is ATR(14) × InpATR_Multiplier (default 2.0) below entry for longs and above entry for shorts, normalized to the symbol's digit precision. Once profit reaches ATR × InpBEStart_ATR (1.0), the stop moves to entry + InpBEOffset × Point (30-point buffer to absorb spread) via ManageOpenPositions(). No per-account stop is enforced; the 3% daily-loss and 10% equity-peak caps act as portfolio-level cutoffs and flatten the book if InpCloseOnDDLimit is true.

Take Profit

Take-profit is set at entry as stop_distance × InpRiskReward (default 2.0), so the static target is twice the risk in points. There is no separate exit signal — the trade is closed by hitting TP, the trailing stop, or the breakeven stop. Same-direction 2-bar reversal signals do not close the existing position; they open a new opposing one (which IsGridSafe() may gate if pyramiding is on). TryClose_EX16004 retries the close up to 3 times on REQUOTE / TIMEOUT / PRICE_OFF / PRICE_CHANGED.

Best For

Best on D1 bars of XAUUSD, EURUSD, GBPUSD and USDJPY where the daily reversal pattern is a meaningful structural event; H4 also works but generates more, smaller signals. Minimum recommended balance is $100 (the EA's minDeposit), with $500 preferred so the 1% risk sizing and 3% daily loss cap have enough room to express themselves. The 250-point spread gate and the lack of an HTF read or news filter mean a low-spread, ECN-style broker (Exness, IC Markets, Pepperstone) is the right venue. Pyramiding ships off — leave it that way until the trader has watched the EA run for at least one full trending week, because the IsGridSafe 300-point guard is designed to add only into confirmed winners, not to rescue a loser.

Strategy Logic

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

Family: Trend Magic: 22216004 Version: 2.00

BRIEF: Pure price-action reversal EA using 2-bar reversal patterns. Bearish bar breaking prior low triggers BUY reversal; bullish bar breaking prior high triggers SELL. ATR-based SL/TP, breakeven, trailing, safe pyramiding and DD protection. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • SetProperFillingMode()
  • CheckTimeFilter()
  • CheckDrawdownLimits()
  • CheckNewDay()
  • CheckSignal()
  • OpenPosition()
  • IsGridSafe()
  • ManageOpenPositions()
  • CalculateLotSize()
  • NormalizeLot()
  • CountPositions()
  • CloseAllPositions()
  • ...and 6 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (32 total across 8 groups):

  • [=== Trade Execution ===] InpMagicNumber = 22216004 // Magic Number
  • [=== Trade Execution ===] InpSlippage = 30 // Max Slippage (points)
  • [=== Trade Execution ===] InpMaxSpread = 250 // Max Spread (points, 0=disabled)
  • [=== Trade Execution ===] InpMaxRetries = 3 // Order Retry Attempts
  • [=== Trade Execution ===] InpTradeComment = "Psgrowth.com Expert_16004" // Trade Comment
  • [=== Money Management ===] InpRiskPercent = 1.0 // Risk % per Trade
  • [=== Money Management ===] InpFixedLot = 0.01 // Fixed Lot (if Risk=0)
  • [=== Money Management ===] InpMaxLotSize = 5.0 // Maximum Lot Size Cap
  • [=== Strategy Settings ===] InpATR_Period = 14 // ATR Period for SL/TP
  • [=== Strategy Settings ===] InpATR_Multiplier = 2.0 // ATR Multiplier for SL
  • [=== Strategy Settings ===] InpRiskReward = 2.0 // Risk:Reward Ratio
  • [=== Time Filter ===] InpUseTimeFilter = true // Enable Time Filter
  • [=== Time Filter ===] InpStartHour = 0 // Start Hour (Server Time)
  • [=== Time Filter ===] InpEndHour = 23 // End Hour (Server Time)
  • [=== Time Filter ===] InpTradeFriday = true // Trade on Friday
  • [=== Time Filter ===] InpFridayCloseHour = 20 // Close All Friday After
  • [=== Trade Management ===] InpUseBreakeven = true // Enable Breakeven
  • [=== Trade Management ===] InpBEStart_ATR = 1.0 // BE Start (ATR multiplier)
  • [=== Trade Management ===] InpBEOffset = 30 // BE Offset (points above entry)
  • [=== Trade Management ===] InpEnableTrail = true // Enable Trailing Stop
  • [=== Trade Management ===] InpTrailStart_ATR = 1.5 // Trail Start (ATR multiplier)
  • [=== Trade Management ===] InpTrailDist_ATR = 0.5 // Trail Distance (ATR multiplier)
  • [=== Pyramid Settings ===] InpEnablePyramid = false // Enable Safe Pyramiding
  • [=== Pyramid Settings ===] InpMaxPositions = 2 // Max Open Positions
  • [=== Pyramid Settings ===] InpMinProfitPoints = 300 // Min Profit (points) for Next Entry
  • [=== Drawdown Protection ===] InpUseDDProtection = true // Enable Drawdown Protection
  • [=== Drawdown Protection ===] InpMaxDailyLoss = 3.0 // Max Daily Loss % (0=disabled)
  • [=== Drawdown Protection ===] InpMaxEquityLoss = 10.0 // Max Equity Loss % from Peak
  • [=== Drawdown Protection ===] InpCloseOnDDLimit = true // Close All When DD Limit Hit
  • [=== Display ===] InpShowPanel = true // Show Info Panel
  • [=== Display ===] InpPanelX = 10 // Panel X Position
  • [=== Display ===] InpPanelY = 30 // Panel Y Position
Pseudocode
// Pipsgrowth EX16004 Trend — Execution Flow (from source analysis)
// Family: Trend
// Pure price-action reversal EA using 2-bar reversal patterns. Bearish bar breaking prior low triggers BUY reversal; bullish bar breaking prior high triggers SELL. ATR-based SL/TP, breakeven, trailing, safe pyramiding and DD protection. 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:
XAUUSDEURUSDGBPUSDUSDJPY
Optimized Timeframes:
D1H4

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
InpMagicNumber22216004Magic Number
InpSlippage30Max Slippage (points)
InpMaxSpread250Max Spread (points, 0=disabled)
InpMaxRetries3Order Retry Attempts
InpTradeComment"Psgrowth.com Expert_16004"Trade Comment
InpRiskPercent1.0Risk % per Trade
InpFixedLot0.01Fixed Lot (if Risk=0)
InpMaxLotSize5.0Maximum Lot Size Cap
InpATR_Period14ATR Period for SL/TP
InpATR_Multiplier2.0ATR Multiplier for SL
InpRiskReward2.0Risk:Reward Ratio
InpUseTimeFiltertrueEnable Time Filter
InpStartHour0Start Hour (Server Time)
InpEndHour23End Hour (Server Time)
InpTradeFridaytrueTrade on Friday
InpFridayCloseHour20Close All Friday After
InpUseBreakeventrueEnable Breakeven
InpBEStart_ATR1.0BE Start (ATR multiplier)
InpBEOffset30BE Offset (points above entry)
InpEnableTrailtrueEnable Trailing Stop
InpTrailStart_ATR1.5Trail Start (ATR multiplier)
InpTrailDist_ATR0.5Trail Distance (ATR multiplier)
InpEnablePyramidfalseEnable Safe Pyramiding
InpMaxPositions2Max Open Positions
InpMinProfitPoints300Min Profit (points) for Next Entry
InpUseDDProtectiontrueEnable Drawdown Protection
InpMaxDailyLoss3.0Max Daily Loss % (0=disabled)
InpMaxEquityLoss10.0Max Equity Loss % from Peak
InpCloseOnDDLimittrueClose All When DD Limit Hit
InpShowPaneltrueShow Info Panel
InpPanelX10Panel X Position
InpPanelY30Panel Y Position
Source Code (.mq5)Open Source
Pipsgrowth_com_EX16004.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX16004 Price_Action_EA — 2-bar reversal price action EA, full 12-layer stack."

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

//+------------------------------------------------------------------+
//| INPUT GROUP: Trade Execution                                     |
//+------------------------------------------------------------------+
input group "=== Trade Execution ==="
input int      InpMagicNumber    = 22216004;   // Magic Number
input int      InpSlippage       = 30;       // Max Slippage (points)
input int      InpMaxSpread      = 250;      // Max Spread (points, 0=disabled)
input int      InpMaxRetries     = 3;        // Order Retry Attempts
input string   InpTradeComment   = "Psgrowth.com Expert_16004"; // Trade Comment

//+------------------------------------------------------------------+
//| INPUT GROUP: Money Management                                    |
//+------------------------------------------------------------------+
input group "=== Money Management ==="
input double   InpRiskPercent    = 1.0;      // Risk % per Trade
input double   InpFixedLot       = 0.01;     // Fixed Lot (if Risk=0)
input double   InpMaxLotSize     = 5.0;      // Maximum Lot Size Cap

//+------------------------------------------------------------------+
//| INPUT GROUP: Strategy Settings                                   |
//+------------------------------------------------------------------+
input group "=== Strategy Settings ==="
input int      InpATR_Period     = 14;       // ATR Period for SL/TP
input double   InpATR_Multiplier = 2.0;      // ATR Multiplier for SL
input double   InpRiskReward     = 2.0;      // Risk:Reward Ratio

//+------------------------------------------------------------------+
//| INPUT GROUP: Time Filter                                         |
//+------------------------------------------------------------------+
input group "=== Time Filter ==="
input bool     InpUseTimeFilter  = true;     // Enable Time Filter
input int      InpStartHour      = 0;        // Start Hour (Server Time)
input int      InpEndHour        = 23;       // End Hour (Server Time)
input bool     InpTradeFriday    = true;     // Trade on Friday
input int      InpFridayCloseHour= 20;       // Close All Friday After

//+------------------------------------------------------------------+
//| INPUT GROUP: Trade Management                                    |
//+------------------------------------------------------------------+
input group "=== Trade Management ==="
input bool     InpUseBreakeven   = true;     // Enable Breakeven
input double   InpBEStart_ATR    = 1.0;      // BE Start (ATR multiplier)
input int      InpBEOffset       = 30;       // BE Offset (points above entry)
input bool     InpEnableTrail    = true;     // Enable Trailing Stop
input double   InpTrailStart_ATR = 1.5;      // Trail Start (ATR multiplier)
input double   InpTrailDist_ATR  = 0.5;      // Trail Distance (ATR multiplier)

//+------------------------------------------------------------------+
//| INPUT GROUP: Pyramid Settings                                    |

Full source code available on download

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

Tags:ex16004trendpipsgrowthfreemt5xauusdeurusdgbpusdusdjpy

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_EX16004.mq5
File Size22.2 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
D1H4
Currency Pairs
XAUUSDEURUSDGBPUSDUSDJPY
Min. Deposit$100