preview
Automating Trading Strategies in MQL5 (Part 54): Consolidation Breakout and Retest Entry Model

Automating Trading Strategies in MQL5 (Part 54): Consolidation Breakout and Retest Entry Model

MetaTrader 5 — Trading |
160 0
Allan Munene Mutiiria
Allan Munene Mutiiria

Contents

  1. Introduction
  2. Understanding the Consolidation Breakout and Retest Model
  3. Detecting Consolidations and Their Breakouts
  4. Entering on the Retest and Managing the Trade
  5. Backtesting
  6. Conclusion


Introduction

A breakout is only one piece of evidence: a single close beyond a line we drew. So we take it. Often, price closes back inside the range on the next bar, and we get stopped out for a loss, one the chart warned us about in hindsight. Two failures sit underneath that. First, the range itself may be invalid. A window can drift while oscillating and still look like a consolidation, but its edges are meaningless because no one defended them. Second, timing is poor. The close that clears the edge is the least proven and most extended moment of the move, and we lack a mechanism to wait for confirmation. When the first attempt does fail on a setup that was sound, we have usually deleted the level and moved on, so the second chance passes us by.

This article is for MetaQuotes Language 5 (MQL5) developers and traders who want the range proved before the break, and the break proved before the entry. Success means every trade the program takes has passed three checks first, a valid range, a confirmed break and a rejected retest, and that a backtest shows how the full system performs on real history.

In our previous article (Part 53), we built a double top and double bottom reversal model. In this article, we validate a consolidation before trading it. We count edge-to-edge crossings, cap the height by the symbol's typical candle size, and reject windows with excessive net drift. Only then do we look for a close that clears an edge by a buffer and moves away from the zone. Instead of entering immediately, we wait for price to return to the broken edge and reject it. By the end of this article, we will be able to:

  • Validate a consolidation by its edge touches, its height against the typical candle size, and its net drift, so a channel that merely oscillates while trending is refused.
  • Require a close beyond an edge by a buffer and a move away from the range before arming a setup, then wait a fixed window for price to return and retest that edge.
  • Enter on a strong close back on the breakout side of the edge after price reaches into the retest zone, with the stop beyond the retest extreme and the target at a multiple of that risk.
  • Trail the position, and trade the same range again after a loss once a fresh breakout and retest form, up to a set number of attempts.
  • Draw each consolidation, its retest zone, and a caption with its height, attempts, and closing reason on the chart, colored by the state of the setup.


Understanding the Consolidation Breakout and Retest Model

A consolidation is not simply a stretch of bars inside two lines. It is a stretch where both edges were tested and held, which is what makes those edges worth watching. So we measure three things before trusting a consolidation. We count how often price crossed from one edge to the other, since a range where price touched the top three times without ever reaching the bottom is not a range at all. We cap its height against the typical candle of whatever symbol we are on, so the limit scales with the symbol instead of being a fixed number of points, although spread, sessions, and costs still differ from one instrument to another. And we compare the average close of the oldest third of the window against the newest third, rejecting the candidate when that drift covers too much of the height, which is how a trending channel that oscillates as it climbs gets refused.

The break itself is treated as a claim rather than a conclusion. We require the close to clear the edge by a buffer rather than by a single point, and we require price to leave the zone afterwards. We treat a close that clears by a hair and hovers as too weak to trade, even though some of those breaks do go on to run. Even then we do not enter. What we wait for is the return, price coming back to the edge it just broke, which is the moment the level shows whether it has flipped. A rejection at that edge is the second condition our model asks for, and it becomes our trade signal. It does not prove the break is genuine. It only means the rules of the model are met. We give that return a fixed window, and once price enters the retest zone, we allow it only a few bars to reject before we consider the setup stale.

We enter on a strong close back on the breakout side after price reaches the zone. The entry can occur on the touch bar or on a later bar while the setup is armed: long above a broken top, short below a broken bottom. The stop goes beyond the extreme the retest reached rather than beyond the range, which ties our risk to the depth of the pullback instead of the width of the box. The target is a multiple of that distance, so every trade is measured in the same terms. A first loss does not retire the setup. The setup goes back to waiting on the same range for a fresh breakout and retest, with a new stop measured from that retest, and we allow a limited number of attempts. By default, a win retires the setup, and an input lets it keep trading instead. In brief, the following diagram shows what we intend to build.

CONSOLIDATION BREAKOUT AND RETEST BLUEPRINT


Detecting Consolidations and Their Breakouts

We begin the implementation with the range itself, measuring a candidate against three tests before we are willing to call it a consolidation worth trading. First, we expose the settings that define a valid range, a real breakout, and the retest that follows, and declare the record carrying one setup through its whole life.

//+------------------------------------------------------------------+
//|                                   Breakout Retest Reentry EA.mq5 |
//|                           Copyright 2026, Allan Munene Mutiiria. |
//|                                   https://t.me/Forex_Algo_Trader |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, Allan Munene Mutiiria."
#property link "https://t.me/Forex_Algo_Trader"
#property version "1.00"

//--- Stamp one shared prefix onto every chart object this program creates
#define OBJ_PREFIX "BRR_"

//--- Pull in the standard trade class that sends and modifies orders
#include <Trade\Trade.mqh>

//+------------------------------------------------------------------+
//| Enumerations                                                     |
//+------------------------------------------------------------------+
enum RangeState
  {
   RNG_ACTIVE,                   // Hold a formed consolidation that awaits its breakout
   RNG_BROKEN,                   // Hold a broken consolidation that awaits the return of price
   RNG_ARMED,                    // Hold price parked inside the retest zone
   RNG_IN_TRADE,                 // Hold a live position riding this setup
   RNG_DONE                      // Hold a retired setup kept only for inspection
  };
//+------------------------------------------------------------------+
//| Inputs                                                           |
//+------------------------------------------------------------------+
input group "GENERAL"
input long           InpMagicNumber        = 1107;              // Magic Number
input double         InpLotSize            = 0.01;              // Lot Size
input string         InpOrderComment       = "BRR";             // Order Comment
input int            InpScaleBars          = 50;                // Bars Measured For The Typical Candle Size

input group "CONSOLIDATION"
input int            InpMinRangeBars       = 20;                // Min Bars To Form A Consolidation
input int            InpMaxRangeBars       = 50;                // Max Bars Scanned For A Consolidation
input double         InpMaxHeightMult      = 5.0;               // Max Consolidation Height (x candle size)
input double         InpTouchTolMult       = 0.35;              // Touch Tolerance At Each Edge (x candle size)
input int            InpMinEdgeSwitches    = 3;                 // Min Times Price Must Swing Edge To Edge
input double         InpMaxDriftFrac       = 0.40;              // Max Net Drift Across The Container (fraction of height)
input int            InpMaxSetups          = 3;                 // Max Live Setups Tracked At Once


input group "BREAKOUT"
input int            InpMaxWaitBars        = 100;               // Bars To Wait For A Breakout Before Expiring
input double         InpBreakBufferMult    = 0.40;              // Close Must Exceed The Edge By (x candle size)
input double         InpMoveAwayMult       = 1.00;              // Price Must Leave The Zone By (x candle size)
input int            InpRetestWindowBars   = 20;                // Retest Window After Breakout (bars)

input group "RETEST AND ENTRY"
input double         InpZoneHalfMult       = 0.90;              // Retest Zone Half Width (x candle size)
input bool           InpRequireStrongClose = true;              // Require Strong Rejection Close
input int            InpMaxArmedBars       = 8;                 // Max Bars Allowed Inside The Zone

input group "STOP LOSS AND TAKE PROFIT"
input double         InpStopBufferMult     = 0.60;              // Stop Buffer Beyond Retest Extreme (x candle size)
input double         InpMinStopMult        = 2.00;              // Minimum Stop Distance (x candle size)
input double         InpRewardRiskRatio    = 2.0;               // Reward To Risk Ratio
input bool           InpUseTrailing        = true;              // Enable Trailing Stop
input int            InpTrailingStopPoints = 300;               // Trailing Stop (points)
input int            InpMinProfitToTrail   = 1000;              // Minimum Profit Before Trailing (points)

input group "REENTRY"
input int            InpMaxAttempts        = 2;                 // Max Trades Per Setup
input bool           InpRetireAfterWin     = true;              // Retire The Setup After A Win

input group "LOGGING"
input bool           InpShowLogs           = true;              // Print Logs To The Journal
input string         InpLogPrefix          = "BRR> ";           // Log Prefix

input group "CHART VISUALS"
input bool           InpDrawVisuals        = true;              // Draw Setup Structure On Chart
input int            InpArrowLabelSize     = 8;                 // Arrow Label Font Size
input color          InpRangeFill          = C'242,245,248';    // Consolidation Box Fill
input color          InpRangeBorder        = C'109,124,140';    // Consolidation Box Border
input color          InpZoneFill           = C'255,247,229';    // Retest Zone Fill
input color          InpBullColor          = C'21,101,192';     // Upside Breakout Color
input color          InpBearColor          = C'176,34,34';      // Downside Breakout Color
input color          InpDoneColor          = C'176,180,184';    // Finished Setup Color
input color          InpTpColor            = C'27,105,31';      // Take Profit Line Color
input color          InpSlColor            = C'176,34,34';      // Stop Loss Line Color
//+------------------------------------------------------------------+
//| Hold one tracked consolidation and its full setup lifecycle      |
//+------------------------------------------------------------------+
struct Range
  {
   int               id;             // Carry the unique id that builds the object names
   double            top;            // Carry the upper edge of the consolidation
   double            bottom;         // Carry the lower edge of the consolidation
   datetime          startTime;      // Carry the bar time of the first consolidation bar
   datetime          formedTime;     // Carry the bar time of the last consolidation bar
   datetime          waitFrom;       // Carry the bar time the current breakout wait began
   RangeState        state;          // Carry the current lifecycle state
   int               dir;            // Carry the breakout direction, +1 up, -1 down, 0 undecided
   double            level;          // Carry the broken edge that is now being retested
   datetime          breakTime;      // Carry the bar time of the breakout close
   int               breakIdx;       // Carry the attempt index this breakout belongs to
   double            zoneHalf;       // Carry the retest zone half width frozen at the break
   bool              leftZone;       // Flag price having moved clear of the zone after the break
   datetime          armTime;        // Carry the bar time price first entered the retest zone
   double            retestExtreme;  // Carry the deepest push into the zone, used as stop anchor
   int               attempts;       // Carry the number of trades already taken on this setup
   ulong             posId;          // Carry the position id while a trade runs
   datetime          endTime;        // Carry the bar time the setup reached its terminal state
   string            endReason;      // Carry the short reason the setup ended
  };

Almost every distance here is a multiple rather than a price, and what they multiply is the typical candle of the chart we are on, so one set of numbers describes a tight box and a wide one without us touching them per symbol. The exceptions are the two trailing distances, which are in points and need setting again for each symbol. The defaults are starting values, and we have not measured how sensitive the result is to them. In candle units, they read plainly: a touch tolerance of 0.35 candles decides how close a bar must come to count as reaching an edge, and a drift cap of 0.40 rejects a window whose two outer thirds sit more than two fifths of its height apart. A breakout must close 0.40 candles beyond the edge, the retest zone reaches 0.90 candles either side of the broken edge, and the stop sits 0.60 candles beyond the deepest retest push.

The "Range" structure is a state machine in disguise: "state" says which stage the setup has reached, "level" holds the edge that was broken, "zoneHalf" freezes the retest band so it cannot resize underneath price, and "attempts" counts the entries this setup has already spent. We keep "leftZone" as a flag because a return to the zone only means something once price has genuinely left it. Before any of this applies, a candidate has to prove it is a range.

Proving Price Oscillated and Did Not Drift

Two measurements separate a real consolidation from a channel that merely wandered sideways while trending.

//+------------------------------------------------------------------+
//| Count how often price swings from one edge across to the other   |
//+------------------------------------------------------------------+
int CountEdgeSwitches(int bars, double top, double bottom)
  {
//--- Start the switch tally at zero
   int switches = 0;
//--- Remember the edge touched last, holding zero until the first touch
   int lastEdge = 0;
//--- Convert the touch tolerance into a price distance
   double tol = Sz(InpTouchTolMult);
//--- Walk the candidate from its oldest bar down to its newest bar
   for(int i = bars; i >= 1; i--)
     {
      //--- Decide which edge this bar reaches, if it reaches either
      int edge = 0;
      if(iHigh(_Symbol, _Period, i) >= top - tol)
         edge = 1;
      else
         if(iLow(_Symbol, _Period, i) <= bottom + tol)
            edge = -1;
      //--- Skip the bars that stay in the middle of the container
      if(edge == 0)
         continue;
      //--- Count a swing whenever the touched edge flips over
      if(lastEdge != 0 && edge != lastEdge)
         switches++;
      //--- Remember this edge for the next comparison
      lastEdge = edge;
     }
//--- Hand back the number of edge to edge swings
   return switches;
  }
//+------------------------------------------------------------------+
//| Measure the net drift from the start to the end of a candidate   |
//+------------------------------------------------------------------+
double MeasureDrift(int bars)
  {
//--- Use a third of the window on each side, never fewer than one bar
   int part = MathMax(1, bars / 3);
//--- Average the closes across the oldest third
   double early = 0.0;
   for(int i = bars; i > bars - part; i--)
      early += iClose(_Symbol, _Period, i);
   early /= part;
//--- Average the closes across the newest third
   double late = 0.0;
   for(int i = 1; i <= part; i++)
      late += iClose(_Symbol, _Period, i);
   late /= part;
//--- Hand back how far the newest third sits from the oldest third
   return MathAbs(late - early);
  }

The "CountEdgeSwitches" function walks the window carrying a memory of which edge price last touched, counting a switch each time the touched edge flips from top to bottom or back, so a run of six touches on the top counts as nothing. It reads only the high and low of each closed bar, so it cannot see the order of movement inside a bar, and a bar that reaches both edges counts as a top touch. That is the test that throws out a box whose lower edge was never defended. The "MeasureDrift" function then compares the average close of the oldest third against the newest third, which catches the staircase, since a window that oscillates convincingly while climbing leaves a large gap between those two averages. It is a coarse test, since it ignores the middle third, so a window that rises and falls back to its starting level passes it. Both of them feed a single scan.

Scanning for the Widest Window Under the Height Cap

We grow a window bar by bar until its height breaks the cap, then put the widest window that still fits through the remaining tests.

//+------------------------------------------------------------------+
//| Find the widest consolidation ending on the last closed bar      |
//+------------------------------------------------------------------+
bool FindConsolidation(double &top, double &bottom, int &bars)
  {
//--- Convert the tallest permitted height into a price distance
   double maxHeight = Sz(InpMaxHeightMult);
//--- Clamp the minimum bar count so a container always spans several bars
   int minBars = MathMax(3, InpMinRangeBars);
//--- Clamp the maximum bar count so the scan stays bounded
   int maxBars = MathMax(minBars, InpMaxRangeBars);
//--- Demand enough history to scan the widest candidate
   if(iBars(_Symbol, _Period) < maxBars + 2)
      return false;
//--- Track the widest window that still fits under the height cap
   int best = 0;
//--- Grow the window one bar at a time, since the height only ever grows
   for(int w = minBars; w <= maxBars; w++)
     {
      //--- Measure the highest high across the candidate window
      double hi = iHigh(_Symbol, _Period, iHighest(_Symbol, _Period, MODE_HIGH, w, 1));
      //--- Measure the lowest low across the candidate window
      double lo = iLow(_Symbol, _Period, iLowest(_Symbol, _Period, MODE_LOW, w, 1));
      //--- Stop growing as soon as the window breaches the height cap
      if(hi - lo > maxHeight)
         break;
      //--- Remember this window as the widest one that still qualifies
      best = w;
      top = hi;
      bottom = lo;
     }
//--- Reject the candidate when no window reached the minimum bar count
   if(best < minBars)
      return false;
//--- Reject a container too shallow to hold a sensible stop
   if(top - bottom < Sz(InpMinStopMult))
      return false;
//--- Demand enough edge to edge swings to prove price oscillated inside
   if(CountEdgeSwitches(best, top, bottom) < InpMinEdgeSwitches)
      return false;
//--- Reject a window that climbs from one edge to the other like a staircase
   if(MeasureDrift(best) > InpMaxDriftFrac * (top - bottom))
      return false;
//--- Reject a candidate sitting on top of a setup already tracked
   if(OverlapsTrackedSetup(top, bottom, iTime(_Symbol, _Period, best)))
      return false;
//--- Publish the bar count of the accepted consolidation
   bars = best;
//--- Report that a consolidation was found
   return true;
  }

Growing the window is safe because its height only ever increases as bars are added, so "FindConsolidation" can stop at the first breach instead of testing every possible width. We keep the widest window that fits under the cap and test only that one, so when it fails the edge switch or drift test, the scan ends for that bar without trying a shorter window. The height floor is practical rather than theoretical, as a box thinner than our minimum stop leaves nowhere sensible to put one. Refusing a candidate that overlaps a setup already tracked stops the same stretch of price being registered twice under two IDs. Finding a range and tracking one are different things.

Registering One Consolidation at a Time

Each scan runs only when there is room in the tracker and no earlier setup is still waiting for its break.

//+------------------------------------------------------------------+
//| Scan the closed bars for one fresh consolidation                 |
//+------------------------------------------------------------------+
void DetectRanges()
  {
//--- Stop once the tracker already carries its full load of setups
   if(CountLiveSetups() >= InpMaxSetups)
      return;
//--- Allow only one unbroken container at a time so boxes never stack up
   for(int i = 0; i < ArraySize(g_ranges); i++)
     {
      //--- Leave as soon as a container is still waiting for its breakout
      if(g_ranges[i].state == RNG_ACTIVE)
         return;
     }
//--- Declare the outputs that the consolidation scan will fill
   double top, bottom;
   int bars;
//--- Register the container whenever the scan accepts one
   if(FindConsolidation(top, bottom, bars))
      AddRange(top, bottom, bars);
  }

The rule in "DetectRanges" that nothing new is registered while an existing range still waits on its breakout keeps the chart from filling with overlapping boxes drawn across the same bars. A setup that has already broken out stops blocking the scan, since its edges are settled and its attention has moved to the retest. Registration hands the range a unique ID, stamps the bars it formed on, sets it waiting for a break and draws it, with every later stage keyed to that ID so its objects can be found and replaced. What that setup waits for next is a close that clears one of its edges.

Turning a Close Beyond an Edge into a Break

We give a registered range a fixed number of bars to break, require the close to clear an edge by a buffer, then freeze the retest zone and move the setup into its broken state.

//+------------------------------------------------------------------+
//| Run one setup through its lifecycle on the last closed bar       |
//+------------------------------------------------------------------+
void ProcessRange(Range &rg)
  {
//--- Leave a finished setup alone, it only lingers to be inspected
   if(rg.state == RNG_DONE)
      return;
//--- Read the high of the last closed bar
   double h = iHigh(_Symbol, _Period, 1);
//--- Read the low of the last closed bar
   double l = iLow(_Symbol, _Period, 1);
//--- Read the close of the last closed bar
   double c = iClose(_Symbol, _Period, 1);
//--- Read the time of the last closed bar
   datetime t1 = iTime(_Symbol, _Period, 1);
//--- Convert the breakout buffer into a price distance
   double buffer = Sz(InpBreakBufferMult);
//--- Handle the setup while it waits on a breakout close
   if(rg.state == RNG_ACTIVE)
     {
      //--- Expire a container that waited too long without breaking out
      if(BarsSince(rg.waitFrom) > InpMaxWaitBars)
        {
         EndRange(rg, "no breakout");
         return;
        }
      //--- Test for a close sitting clear above the upper edge
      bool upBreak = c > rg.top + buffer;
      //--- Test for a close sitting clear below the lower edge
      bool downBreak = c < rg.bottom - buffer;
      //--- Keep waiting while price still closes inside the container
      if(!upBreak && !downBreak)
         return;
      //--- Store the direction the breakout points the setup in
      rg.dir = upBreak ? 1 : -1;
      //--- Take the broken edge as the level that will be retested
      rg.level = upBreak ? rg.top : rg.bottom;
      //--- Stamp the bar the breakout closed on
      rg.breakTime = t1;
      //--- Bind the drawings of this breakout to the current attempt
      rg.breakIdx = rg.attempts;
      //--- Freeze the zone width so the band never resizes under price
      rg.zoneHalf = Sz(InpZoneHalfMult);
      //--- Note that price still sits in the zone it has just cut through
      rg.leftZone = false;
      //--- Move the setup into its broken state
      rg.state = RNG_BROKEN;
      //--- Draw the retest zone together with the breakout marker
      DrawRange(rg);
      //--- Report the breakout to the journal
      Log("breakout " + (upBreak ? "up through " : "down through ") + P(rg.level) + (rg.attempts > 0 ? " again (re-entry window)" : "") + ", waiting for retest");
      return;
     }
  }

Here, we demand the close sit clear of the edge by the buffer rather than merely beyond it, because we treat a close a single point past the line as too weak to show that the level has flipped. The moment a side gives way we record the broken edge as the level that will be retested, stamp the bar, and freeze "zoneHalf" from the candle size at that instant, which stops the band from resizing later and moving the goalposts under price. Setting "leftZone" false says what is true at that moment, that price is still sitting in the zone it just cut through, so the return we are waiting for cannot be satisfied by the breakout bar itself. A range that never breaks is retired once its wait runs out, freeing the tracker to look for the next one. What follows is the return to that edge.


Entering on the Retest and Managing the Trade

We pick the state machine up where the break left it, waiting for price to return to the broken edge, and take the trade only when that return is rejected. The same function carries the setup through the return to the zone, the rejection that triggers an entry, and what happens to a setup once its trade has closed.

//+------------------------------------------------------------------+
//| Run one setup through its lifecycle on the last closed bar       |
//+------------------------------------------------------------------+
void ProcessRange(Range &rg)
  {
//--- EXISTING LOGIC
//--- Read the breakout direction into a plain readable flag
   bool isBull = (rg.dir > 0);
//--- Test whether the bar closed clear of the zone on the breakout side
   bool clear = isBull ? (c > rg.level + rg.zoneHalf + Sz(InpMoveAwayMult)) : (c < rg.level - rg.zoneHalf - Sz(InpMoveAwayMult));
//--- Test whether the bar reached back into the retest zone
   bool touched = isBull ? (l <= rg.level + rg.zoneHalf) : (h >= rg.level - rg.zoneHalf);
//--- Take the container midpoint as the line a real failure must cross
   double midpoint = (rg.top + rg.bottom) * 0.5;
//--- Test whether the bar closed back deep inside the container
   bool failed = isBull ? (c < midpoint) : (c > midpoint);
//--- Test whether the bar still closed on the breakout side of the edge
   bool closedBeyond = isBull ? (c > rg.level) : (c < rg.level);
//--- Test whether the close finished in the stronger half of its own bar
   bool strong = !InpRequireStrongClose || (h - l <= 0) || (isBull ? (c >= l + 0.5 * (h - l)) : (c <= h - 0.5 * (h - l)));
//--- Combine the three tests into a single rejection verdict
   bool rejected = touched && closedBeyond && strong;
//--- Handle the setup while it waits for price to come back
   if(rg.state == RNG_BROKEN)
     {
      //--- Finish the setup once the retest window has run out
      if(BarsSince(rg.breakTime) > InpRetestWindowBars)
        {
         EndRange(rg, "no retest");
         return;
        }
      //--- Finish the setup when price closes back past the container midpoint
      if(failed)
        {
         EndRange(rg, "breakout failed");
         return;
        }
      //--- Record the moment price finally moves clear of the zone
      if(!rg.leftZone && clear)
        {
         //--- Allow a return to the zone to count as a retest from here on
         rg.leftZone = true;
         //--- Report that the setup now waits on that return
         Log("price left the zone at " + P(rg.level) + ", retest now possible");
         return;
        }
      //--- Ignore zone bars while price has never left, that is just the break
      if(!rg.leftZone)
         return;
      //--- Keep waiting while price has not come back to the zone
      if(!touched)
         return;
      //--- Stamp the bar price first re-entered the zone on
      rg.armTime = t1;
      //--- Seed the stop anchor with the push this bar made into the zone
      rg.retestExtreme = isBull ? l : h;
      //--- Take the trade at once when the touching bar already rejected
      if(rejected)
        {
         TryEnter(rg);
         return;
        }
      //--- Otherwise sit armed inside the zone waiting on the rejection
      rg.state = RNG_ARMED;
      //--- Refresh the setup visuals in the armed state
      DrawRange(rg);
      //--- Report the arming to the journal
      Log("retest of " + P(rg.level) + " armed, waiting for the rejection close");
      return;
     }
//--- Handle the setup while it sits armed inside the zone
   if(rg.state == RNG_ARMED)
     {
      //--- Deepen the stop anchor with the furthest push made so far
      rg.retestExtreme = isBull ? MathMin(rg.retestExtreme, l) : MathMax(rg.retestExtreme, h);
      //--- Finish the setup when price closes back past the container midpoint
      if(failed)
        {
         EndRange(rg, "breakout failed");
         return;
        }
      //--- Take the trade once a strong close reclaims the broken edge
      if(closedBeyond && strong)
        {
         TryEnter(rg);
         return;
        }
      //--- Disarm after too many bars of chop inside the zone
      if(BarsSince(rg.armTime) > InpMaxArmedBars)
        {
         //--- Drop back to waiting for a cleaner retest
         rg.state = RNG_BROKEN;
         //--- Refresh the setup visuals in the waiting state
         DrawRange(rg);
         //--- Report the disarm to the journal
         Log("retest of " + P(rg.level) + " disarmed, chop in the zone");
        }
      return;
     }
//--- Handle the setup while it holds an open trade
   if(rg.state == RNG_IN_TRADE)
     {
      //--- Keep waiting while a position with this identifier is still open
      if(FindOpenPositionTicket(rg.posId) > 0)
         return;
      //--- Read the closed result of the finished position
      double pnl = ClosedProfitOfPosition(rg.posId);
      //--- Classify that outcome as a win or a loss
      bool won = (pnl > 0);
      //--- Report the closure to the journal
      Log("trade on the retest of " + P(rg.level) + " closed " + (won ? "WIN " : "LOSS ") + DoubleToString(pnl, 2));
      //--- Release the binding to the closed position
      rg.posId = 0;
      //--- Retire the setup after a win whenever that is configured
      if(won && InpRetireAfterWin)
        {
         EndRange(rg, "target hit");
         return;
        }
      //--- Retire the setup once its attempts are all used up
      if(rg.attempts >= InpMaxAttempts)
        {
         EndRange(rg, "attempts used");
         return;
        }
      //--- Send the setup back to waiting on a fresh breakout
      rg.state = RNG_ACTIVE;
      //--- Restart the breakout wait from the bar the trade closed on
      rg.waitFrom = t1;
      //--- Clear the old breakout so a new one has to form
      rg.breakTime = 0;
      //--- Clear the old arm time
      rg.armTime = 0;
      //--- Clear the old stop anchor
      rg.retestExtreme = 0;
      //--- Force the next breakout to leave the zone all over again
      rg.leftZone = false;
      //--- Refresh the setup visuals in the waiting state
      DrawRange(rg);
      //--- Report that the setup stands open for a re-entry
      Log("re-entry armed: needs a fresh breakout and retest");
      return;
     }

Three tests decide a rejection, and "ProcessRange" keeps them apart on purpose. Price must reach back into the zone, the bar must still close on the breakout side of the edge, and that close must finish in the stronger half of its own range. That last test is what separates a bar that defended the level from one that merely touched it and drifted. Once the setup is armed, a later bar needs only the two close tests, so the entry bar itself does not have to reach the zone. We track the deepest push into the zone as we go, since that extreme is where the stop will sit, and we let it deepen while the setup stays armed rather than freezing it at the first touch.

Two exits protect us from waiting forever. A close back past the midpoint of the original box means the break has genuinely failed, and we retire the setup rather than hoping. Chop inside the zone for too many bars disarms it instead, dropping it back to waiting so a cleaner retest can still arm it later. When a trade closes, a win retires the setup while retiring after a win is switched on, which is the default. A loss sends it back to waiting for a fresh breakout of the same range, with the zone flag cleared so the next break has to leave and return all over again. That is the re-entry, a new breakout and retest cycle rather than a second entry on the old retest, and each one costs an attempt.

Placing the Stop, the Target, and the Order

The entry goes to market, the stop sits beyond the deepest retest push, and the target is a multiple of that distance.

//+------------------------------------------------------------------+
//| Open the trade of an armed setup on its rejection candle         |
//+------------------------------------------------------------------+
bool OpenTrade(Range &rg)
  {
//--- Read the breakout direction into a plain readable flag
   bool isBull = (rg.dir > 0);
//--- Enter at the market on the correct side of the spread
   double entry = isBull ? NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), SymDigits) : NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), SymDigits);
//--- Place the stop beyond the deepest retest push by the configured buffer
   double stop = isBull ? rg.retestExtreme - Sz(InpStopBufferMult) : rg.retestExtreme + Sz(InpStopBufferMult);
//--- Push a buy stop lower when the retest landed too close to the entry
   if(isBull && entry - stop < Sz(InpMinStopMult))
      stop = entry - Sz(InpMinStopMult);
//--- Push a sell stop higher when the retest landed too close to the entry
   if(!isBull && stop - entry < Sz(InpMinStopMult))
      stop = entry + Sz(InpMinStopMult);
//--- Read the shortest stop distance the broker will accept
   double stopsLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * SymPoint;
//--- Widen a buy stop that would sit inside that broker limit
   if(isBull && entry - stop < stopsLevel)
      stop = entry - stopsLevel;
//--- Widen a sell stop that would sit inside that broker limit
   if(!isBull && stop - entry < stopsLevel)
      stop = entry + stopsLevel;
//--- Normalize the finished stop to the symbol precision
   stop = NormalizeDouble(stop, SymDigits);
//--- Measure the entry to stop distance that defines one R
   double riskDistance = MathAbs(entry - stop);
//--- Abandon the trade when that risk distance is unusable
   if(riskDistance <= 0)
     {
      //--- Report the sizing problem to the journal
      Log("invalid risk distance");
      return false;
     }
//--- Project the take profit out at the reward multiple of the stop
   double takeProfit = NormalizeDouble(isBull ? entry + InpRewardRiskRatio * riskDistance : entry - InpRewardRiskRatio * riskDistance, SymDigits);
//--- Use the configured lot size on every order
   double lots = InpLotSize;
//--- Send the market order on the correct side
   bool ok = isBull ? Trade.Buy(lots, _Symbol, entry, stop, takeProfit, InpOrderComment) : Trade.Sell(lots, _Symbol, entry, stop, takeProfit, InpOrderComment);
//--- Abandon the attempt when the server turned the order down
   if(!ok)
     {
      //--- Report the server response to the journal
      Log("open failed: " + Trade.ResultRetcodeDescription());
      return false;
     }
//--- Fall back on the order ticket as the position identifier
   ulong posId = Trade.ResultOrder();
//--- Read the deal that the fill produced
   ulong deal = Trade.ResultDeal();
//--- Prefer the true position id carried by that fill deal
   if(deal > 0 && HistoryDealSelect(deal))
      posId = (ulong)HistoryDealGetInteger(deal, DEAL_POSITION_ID);
//--- Count this fill as one attempt spent on the setup
   rg.attempts++;
//--- Bind the open position to the setup
   rg.posId = posId;
//--- Move the setup into its in trade state
   rg.state = RNG_IN_TRADE;
//--- Draw the entry, stop and target lines of this attempt
   DrawEntryLevels(rg, isBull, iTime(_Symbol, _Period, 0), entry, stop, takeProfit);
//--- Refresh the setup visuals in the direction color
   DrawRange(rg);
//--- Report the fill to the journal
   Log((isBull ? "BUY" : "SELL") + " filled @ " + P(entry) + "  SL " + P(stop) + "  TP " + P(takeProfit) + "  lots " + DoubleToString(lots, 2) + "  retest of " + P(rg.level) + "  attempt " + IntegerToString(rg.attempts));
//--- Report the successful fill back to the caller
   return true;
  }

Anchoring the stop to "retestExtreme" rather than to the far side of the range is what keeps our risk proportional to the pullback we actually traded, which on a shallow retest is a fraction of the box height. Two floors then guard it, our own minimum distance for a retest that landed almost on top of the entry, and the broker's own stops level, which no order can sit inside. Only once the stop survives both do we measure the risk distance and project the target from it, so the reward ratio is honest rather than being quoted from a stop that was later moved. We resolve the position identifier from the fill deal and keep it rather than a position ticket. The identifier is what the deal history is filed under, so it gives us the closed result later. While the trade runs, we find the open position by walking the open positions for that identifier, rather than passing the identifier to "PositionSelectByTicket", which expects a ticket.

//+------------------------------------------------------------------+
//| Find the open position carrying a position identifier            |
//+------------------------------------------------------------------+
ulong FindOpenPositionTicket(ulong posId)
  {
//--- Walk every open position from the last one to the first
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      //--- Select the position through its ticket
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0 || !PositionSelectByTicket(ticket))
         continue;
      //--- Hand back the ticket of the position whose identifier matches
      if((ulong)PositionGetInteger(POSITION_IDENTIFIER) == posId)
         return ticket;
     }
//--- Report that no open position carries the identifier
   return 0;

The "FindOpenPositionTicket" function hands back the ticket of the open position carrying our identifier, or zero when none is open, which is how "ProcessRange" learns the trade has closed. Any later call that needs a ticket, such as a modification, can use the ticket it returns.


Gating the Entry

Every condition that must hold before an order is sent is checked in one place, with the reason reported when one fails.

//+------------------------------------------------------------------+
//| Check every gate that must stand open before an entry            |
//+------------------------------------------------------------------+
bool EntryGatesOpen(const Range &rg, string &why)
  {
//--- Block the entry while a position of ours is already running
   if(CountOurPositions() > 0)
     {
      why = "position already open";
      return false;
     }
//--- Block the entry once the setup has used up its attempts
   if(rg.attempts >= InpMaxAttempts)
     {
      why = "attempts exhausted";
      return false;
     }
//--- Report that every gate stands open
   return true;
  }
//+------------------------------------------------------------------+
//| Attempt the entry and fall back to waiting on a closed gate      |
//+------------------------------------------------------------------+
void TryEnter(Range &rg)
  {
//--- Prepare the text that will carry the blocking reason
   string why;
//--- Try to open the trade while every gate stands open
   if(EntryGatesOpen(rg, why))
     {
      //--- Leave once the order has gone through successfully
      if(OpenTrade(rg))
         return;
      //--- Fall through carrying the order failure as the reason
      why = "order failed";
     }
//--- Report the skipped rejection to the journal
   Log("rejection at " + P(rg.level) + " skipped: " + why);
//--- Drop back to waiting so the next rejection can still be taken
   rg.state = RNG_BROKEN;
//--- Refresh the setup visuals in the waiting state
   DrawRange(rg);
  }

Keeping the gates in "EntryGatesOpen" separates two questions that are easy to tangle: whether the setup looks right, which the state machine answered, and whether we are allowed to trade it at all, which depends on our own exposure and the attempts already spent. Returning a reason rather than a bare false is what makes a quiet run diagnosable, since the journal then says why an entry that looked valid never fired. The "TryEnter" function is the single doorway to an order, so no path into the market bypasses those checks.

Trailing the Open Position

Once a trade is running, the stop is moved behind price by a fixed multiple, but only ever in the profitable direction.

//+------------------------------------------------------------------+
//| Trail the stop of one open position                              |
//+------------------------------------------------------------------+
void TrailOnePosition(ulong ticket)
  {
//--- Leave when the position can no longer be selected
   if(!PositionSelectByTicket(ticket))
      return;
//--- Leave when the position belongs to another program
   if(PositionGetInteger(POSITION_MAGIC) != InpMagicNumber)
      return;
//--- Leave when the position belongs to another symbol
   if(PositionGetString(POSITION_SYMBOL) != _Symbol)
      return;
//--- Read the side the position was opened on
   bool isBull = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY);
//--- Read the fill price of the position
   double entry = PositionGetDouble(POSITION_PRICE_OPEN);
//--- Read the stop price currently sitting on the position
   double currentStop = PositionGetDouble(POSITION_SL);
//--- Read the target price currently sitting on the position
   double currentTP = PositionGetDouble(POSITION_TP);
//--- Read the price the position would close at right now
   double px = isBull ? SymbolInfoDouble(_Symbol, SYMBOL_BID) : SymbolInfoDouble(_Symbol, SYMBOL_ASK);
//--- Leave until the trade runs ahead by the minimum profit
   if((isBull ? (px - entry) : (entry - px)) <= InpMinProfitToTrail * SymPoint)
      return;
//--- Place the new stop the configured points behind the current price
   double newStop = NormalizeDouble(isBull ? px - InpTrailingStopPoints * SymPoint : px + InpTrailingStopPoints * SymPoint, SymDigits);
//--- Leave unless the new stop would tighten the one already there
   if(isBull ? newStop <= currentStop : (currentStop != 0 && newStop >= currentStop))
      return;
//--- Send the modification and report it once the server accepts
   if(Trade.PositionModify(ticket, newStop, currentTP))
      Log("stop trailed to " + P(newStop));
  }

The trail in "TrailOnePosition" only ever tightens, because a stop that could move away from price would undo the risk we accepted at entry. It waits until the position is a set distance into profit, and it sends a modification only when the new stop is tighter than the current one. All of this waits on the handlers that drive it.

Driving the Model from the Event Handlers

In the "OnInit" event handler we cache the symbol figures and refuse impossible settings, the "OnTick" event handler advances every setup once a bar closes, and the "OnDeinit" event handler clears our drawings.

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- Cache the symbol digits that every price format relies on
   SymDigits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
//--- Cache the symbol point size that every distance conversion relies on
   SymPoint = _Point;
//--- Stamp our magic number onto every order this program sends
   Trade.SetExpertMagicNumber(InpMagicNumber);
//--- Allow a little slippage so market entries still fill
   Trade.SetDeviationInPoints(30);
//--- Reject a lot size that could never be sent
   if(InpLotSize <= 0)
     {
      Print(InpLogPrefix + "Lot Size must be greater than zero");
      return INIT_PARAMETERS_INCORRECT;
     }
//--- Reject a minimum bar count too small to form a container
   if(InpMinRangeBars < 3)
     {
      Print(InpLogPrefix + "Min Bars To Form A Consolidation must be at least 3");
      return INIT_PARAMETERS_INCORRECT;
     }
//--- Reject a maximum bar count smaller than the minimum
   if(InpMaxRangeBars < InpMinRangeBars)
     {
      Print(InpLogPrefix + "Max Bars Scanned must be at least the minimum bar count");
      return INIT_PARAMETERS_INCORRECT;
     }
//--- Reject a height multiplier that leaves no room for a container
   if(InpMaxHeightMult <= 0)
     {
      Print(InpLogPrefix + "Max Consolidation Height must be greater than zero");
      return INIT_PARAMETERS_INCORRECT;
     }
//--- Start out with an empty setup array
   ArrayResize(g_ranges, 0);
//--- Reset the running setup id counter
   g_rangeSeq = 0;
//--- Seed the bar guard with the time of the forming bar
   g_lastBarTime = iTime(_Symbol, _Period, 0);
//--- Print the ready banner carrying the key settings
   Log("Breakout Retest Reentry EA ready on " + _Symbol + " " + EnumToString((ENUM_TIMEFRAMES)_Period) + " | container " + IntegerToString(InpMinRangeBars) + " to " + IntegerToString(InpMaxRangeBars) + " bars under " + DoubleToString(InpMaxHeightMult, 2) + " candles | zone " + DoubleToString(InpZoneHalfMult, 2) + " candles | attempts " + IntegerToString(InpMaxAttempts));
//--- Report a successful startup
   return INIT_SUCCEEDED;
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- Clear our objects on a real removal only, sparing tester visuals
   if(reason == REASON_REMOVE || reason == REASON_CHARTCLOSE || reason == REASON_CLOSE)
      ObjectsDeleteAll(0, OBJ_PREFIX);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- Run the setup logic only once a new bar has opened
   if(IsNewBar())
     {
      //--- Proceed only when the chart scale can be measured
      if(MeasureCandleSize())
        {
         //--- Advance every tracked setup through its lifecycle
         for(int i = 0; i < ArraySize(g_ranges); i++)
            ProcessRange(g_ranges[i]);
         //--- Forget the finished setups no scan can collide with any more
         PruneRanges();
         //--- Scan the closed bars for one fresh container
         DetectRanges();
         //--- Extend the live drawings onto the new bar
         if(VisualsAllowed())
           {
            //--- Redraw only the setups that still move, finished ones never do
            for(int i = 0; i < ArraySize(g_ranges); i++)
              {
               //--- Skip a finished setup, since its drawing is frozen
               if(g_ranges[i].state != RNG_DONE)
                  DrawRange(g_ranges[i]);
              }
            //--- Push the updated objects onto the chart
            ChartRedraw(0);
           }
        }
     }
//--- Trail only while trailing is on and a position is there to trail
   if(InpUseTrailing && PositionsTotal() > 0)
      TrailOpenPositions();
  }

Here, almost everything in the "OnTick" event handler runs once per bar rather than once per tick, because every decision the model makes is taken from closed bars and nothing would change in between. Measuring the candle size first is a gate rather than a step, since every distance in the strategy is a multiple of it and a bar where it cannot be measured is better skipped than guessed at. Order matters in the three calls that follow: setups advance, finished ones are pruned, and only then do we scan for a new range, so a fresh container can never collide with a setup that was retired on the same bar. Trailing is the exception that runs on every tick, since a stop that only moves once a bar would leave profit on the table during a fast run. In the "OnDeinit" event handler we clear our objects only on a genuine removal, which is what leaves the drawings intact on the tester's visual chart when a run finishes.


Backtesting

We tested the program on a demo hedging account, on XAUUSDm on the one-minute chart from 2026.01.01 to 2026.09.12, starting from a one thousand dollar deposit at 1:400 leverage. The Strategy Tester ran in Every tick mode, which generates ticks from the one-minute bars rather than replaying real ones, with zero latency and ideal execution, so no slippage is modeled. There is no spread setting in the MetaTrader 5 tester: in this mode it uses the spread recorded with each one-minute bar of the history, so spreads float as they did in the market, and commissions follow the account's own symbol settings. Two settings matter most in reading the result. The strong close requirement refuses any retest bar closing in the weaker half of its own range. The trailing stop arms a thousand points into profit and then follows three hundred points behind price, which on gold's three-digit quotes is one dollar and thirty cents of price. The visual run is shown below.

BREAKOUT RETEST REENTRY EA GIF

The run produced 232 trades, and 190 of them closed in profit. Profit factor was 2.13, and net profit was $189.49. Maximum equity drawdown was $20.31 (1.93%), measured from the equity peak rather than the starting deposit. The shape behind those numbers is more useful than the win rate. The average win returned 1.88 dollars while the average loss cost 4.01 dollars. That fits the trailing stop's settings: a winner is locked in once it runs a dollar, so many close long before the two-to-one target, while a loser never arms the trail and runs to the stop behind the retest extreme.

With losses more than twice the size of wins, the strategy breaks even at a win rate of about 68 percent, so the 81.90 percent it reached here is what carries the expected payoff of 0.82 dollars a trade, and the largest single loss, 13.16 dollars, shows what one bad retest can cost. The two directions were evenly matched, 122 shorts winning 83.61 percent against 110 longs winning 80.00 percent. This is a single run on one symbol, one timeframe, and one period, with no out-of-sample or forward test, so it shows how the rules behave on that data rather than proving they hold elsewhere. It also shows the result of the full system rather than the contribution of each filter, since we did not run versions with the filters switched off.

The backtest graph is shown below.

BACKTEST GRAPH

The backtest report is shown below.

BACKTEST RESULTS


Conclusion

We have turned the breakout retest idea into a program that refuses to trust any part of it on a single piece of evidence. A range is registered only after price has crossed between its edges enough times and has not drifted across its own height. A break counts only when the close clears the edge by a buffer and price then leaves the zone. The entry then waits for the return to that edge and a strong close back on the breakout side. The stop is anchored to the deepest push of that retest rather than to the far side of the box, and the target is a multiple of that same distance. A losing attempt sends the setup back to waiting for a fresh breakout and retest instead of deleting it.

On gold's one-minute chart from January to September 2026, the rules took 232 trades, won 81.90 percent of them and returned a profit factor of 2.13, with the equity drawdown held to 1.93 percent. Because the average loss is more than twice the average win, that result depends on the win rate staying well above its break-even of about 68 percent. It is one run on one symbol and one period, at the default inputs, with ideal execution and no forward test, so it demonstrates the rules rather than establishing their quality. The next steps are a real-tick run with delays, an out-of-sample period, runs with each filter switched off, and a sweep of the trailing distances on other symbols.

What was a judgment call made bar by bar is now a sequence a machine can repeat: validate the range, confirm the break, wait for the return, and trade the rejection.

Disclaimer: This article is for educational purposes only. Trading carries significant financial risk, and past performance in testing does not guarantee future results. Test any tool thoroughly on a demo account and use proper risk management before trading it with real capital.

Building a PDF Creation Library in MQL5 (Part 4): Lines Boxes and Color Building a PDF Creation Library in MQL5 (Part 4): Lines Boxes and Color
The article turns drawing primitives into PDF output: one cm flip installs a top‑left, y‑down system, while CPdfPage writes m/l/c/h/re, S/f/B, W n, and transforms from calls on CPdfSurface. PdfColor keeps RGB bytes and fixes MQL5 byte order when writing fractions. It also covers caps, joins, dashes, clipping, and Bezier circles. Demos include a printable ruler, a feature sampler, and a ready letterhead script.
Multi-Timeframe Bar Aggregator with Conflict Detection in MQL5 Multi-Timeframe Bar Aggregator with Conflict Detection in MQL5
We implement a multi‑timeframe aggregator that prevents mixing bars from different moments. It validates grid alignment, recency to the forming base bar, and closed‑bar end times, and returns either a complete bundle or a structured error. A re‑read guards against races with a new base bar, while a fake bar source powers fifteen reproducible tests and a demo indicator that plots on valid data only.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (EDCFlow) Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (EDCFlow)
In the article, we explore the EDCFlow framework, which offers a new approach to analyzing market microstructure. It combines state correlation with a difference map, making it possible to identify subtle dynamic changes in the market. The model's architecture effectively aggregates multiscale features with minimal computational cost, making it suitable for real-time analysis.