preview
Automating Chart Patterns in MQL5 (Part 4): The Flag and Pennant

Automating Chart Patterns in MQL5 (Part 4): The Flag and Pennant

MetaTrader 5 — Examples |
112 0
Tola Moses Hector
Tola Moses Hector

Introduction

A reversal pattern asks whether a trend is ending. A continuation pattern asks the opposite question: whether a pause in a trend is temporary. The flag and pennant are the classic examples. Both begin with a pole, a fast, steep, high-momentum price move that signals strong directional conviction. Furthermore, both are followed by a brief consolidation, a pause where the market absorbs the move without giving up much of the ground it gained. Both resolve with a breakout in the original direction, and both project a target using the height of the pole itself.

In Part 1 of this series, we built "CSwingEngine," a swing detection engine that reads market structure from a higher timeframe and labels every confirmed swing HH, LH, HL, or LL. Parts 2 and Part 3 used that engine to detect reversal patterns: the double top, double bottom, and head and shoulders. This article turns to a different kind of pattern entirely.

The classical distinction between the two is geometric. A flag consolidates in a shallow channel of two roughly parallel lines. A pennant consolidates in a converging wedge. The detector in this article does not measure geometry. Instead, it tests what both patterns share: a single impulsive leg, a bounded pause of sufficient length, and a close beyond the pause boundary. In plain terms it is a pole-and-consolidation breakout detector, and the flag and pennant names are used for the family of patterns it targets, not for shapes it distinguishes. The known limitations section returns to this.

A pole is also simpler to find than a reversal. A reversal needs several swings arranged in a specific sequence. A pole needs exactly two adjacent swings, one low and one high, and the distance between them must be large and quick. The consolidation that follows is then watched on the EA's own chart timeframe, because a pole's aftermath plays out over a handful of chart bars, not over a full higher-timeframe swing cycle.

A note on timeframes before going further: every "H4" reference in this article describes the default value of "InpSwingTF". The swing timeframe is a configurable input, not a hardcoded assumption. If you set "InpSwingTF" to "PERIOD_D1" or "PERIOD_H1", read every "H4" reference below as the configured swing timeframe. The chart timeframe must not be higher than "InpSwingTF", and the EA refuses to start otherwise.


The Flag and Pennant—Structure and Measurement

The flag pattern structure

Fig. 1. The flag pattern structure.

The pennant pattern structure

Fig. 2. The pennant pattern structure.

The pattern has four components.

  1. The pole. A single impulsive leg: the most recent swing of one type and the swing of the opposite type immediately before it, with no other swing in between. For a bullish continuation this is a swing low followed directly by a swing high. To qualify as a pole rather than an ordinary swing leg, it must be both tall, at least "InpMinPoleATR" × H4-ATR, and fast, forming within "InpMaxPoleBars" real H4 bars. A move that is tall but slow is a grind, not an impulse. A move that is fast but shallow is noise.
  2. The flag. The consolidation that follows the pole. It begins at the close of the H4 bar that holds the pole's final swing point, and it is tracked on the chart timeframe from that bar onward. The boundary is the running extreme in the pole's direction (the highest high for a bullish pole) and the opposite running extreme (the lowest low), both starting at the pole's end price. A minimum number of chart bars, "InpMinFlagBars", must pass before a breakout is valid. A close beyond the boundary before that minimum is reached means the market never paused, and the pole is discarded. A maximum retracement, expressed as a fraction of the pole's own height ("InpMaxRetracePct"), bounds how far price may give back before the setup is discarded as a failed continuation.
  3. The breakout. A chart-bar close beyond the boundary in the pole's direction, on the bar that has just closed. This is the entry trigger. A breakout that happened on an earlier bar is never chased.
  4. The measured move target. The height of the pole, projected from the breakout level, which is the flag boundary that was broken. If the pole rose 2000 points and the flag boundary that was broken sits at 1.1050, the target is 1.1250. The target is a price fixed by the pattern, not by the bar's close or the fill price. This is the default. Setting "InpUseMeasuredMove" to false switches to a 2R fallback, described with the entry functions.

The bearish version mirrors every component: a swing high followed directly by a swing low, a boundary made of the running lowest low and the opposite running highest high, a breakout on a close below the boundary, and a target projected downward.


Swing Time and Swing Confirmation Time

A swing point and the moment the engine confirms it are different events. A swing high carries the time of the H4 bar that made the high. The engine can only confirm it after "InpSwingStrength" further H4 bars have closed. A pole whose end swing sits at 08:00 on an H4 chart with a strength of 3 is not visible to the EA until the bar that opens at 20:00 has closed.

The consolidation, however, begins when the pole's last bar closes, not when the engine finally reports it. If the EA started counting at confirmation, it would discard the chart bars that have already been spent in consolidation, and the minimum and maximum flag durations would be measured from the wrong moment.

This article therefore uses the swing timestamp and replays chart bars starting from it. Each time the EA evaluates a locked pole, it walks chart bars from that point to the last closed bar. This keeps the flag age equal to the true number of chart bars since the pole ended, even if the pole was discovered late. A consequence worth noting: by the time a pole is confirmed, its flag may already be partly or fully elapsed. The replay resolves that case correctly. A flag that broke out inside the confirmation lag is a missed breakout, and a flag that is still pending is tracked from its true age.


What Makes a Pole a Single Leg

A trend read is not enough to define a pole. "TREND_UP" says the engine's latest swings form higher highs and higher lows. It does not say that the latest high and the latest low belong to one continuous impulse. The two could be separated by several intermediate swings, with the "pole" actually being a slow staircase.

The detector therefore does not use "GetTrend()" at all. It walks the engine's swing list from the newest swing and takes the first swing of the pole's end type, then requires the swing immediately before it to be of the opposite type. Because "GetSwing(i + 1)" is the neighbour of "GetSwing(i)" in time order, no swing lies between the two endpoints by construction, and the leg is a single move. If the neighbour is of the same type, which happens when the engine reports two consecutive highs, the candidate is rejected rather than stitched together.

Two further properties follow from this definition. Both endpoints are ordered in time explicitly, and the pole never depends on the labels (HH, LH, HL, LL) of its endpoints, so it cannot collide with a label-based condition the way a trend gate did in Part 3.

Choosing Between a Bullish and a Bearish Pole

Both directions can produce a valid candidate at the same time. Consider swings, newest first, of low, high, low. The earlier low and the high form a bullish pole, and the high and the newest low form a bearish pole. The article's rule is that the pole whose end swing is more recent wins, because it describes the freshest impulse and the older pole's consolidation would contain the newer leg. A swing is either a high or a low, so two poles never share an end time and the rule always yields exactly one choice.


What Makes a Valid Pattern?

Before either pole check runs, "atr" is validated: an ATR handle that has not warmed up, or a symbol with a data gap, can return zero or "EMPTY_VALUE," and every distance check below multiplies against it.

  • Condition 1—Single leg. The swing that ends the pole and the swing immediately before it must be of opposite types, ordered in time, with no swing between them.
  • Condition 2—Pole height. The price distance between the pole's two endpoints must be at least "InpMinPoleATR" × H4-ATR.
  • Condition 3—Pole duration. The number of real H4 bars between the two endpoints, counted with "iBarShift()" on the swing timeframe, must be between 1 and "InpMaxPoleBars." A count based on dividing a time difference by the bar length would classify the same price leg differently depending on weekends and data gaps.

Passing these three conditions confirms that a pole exists. Four further conditions govern whether its breakout is ever traded, and they are evaluated by replaying the chart bars since the pole ended:

  • Condition 4—Minimum consolidation. At least "InpMinFlagBars" chart bars must precede the breakout bar. A close beyond the boundary earlier than that discards the pole.
  • Condition 5—Maximum retracement. Price may not retrace more than "InpMaxRetracePct" of the pole's height at any point in the flag.
  • Condition 6—Lifetime. At most "InpMaxFlagBars" chart bars may precede the breakout bar. A flag that is still unresolved beyond that is discarded.
  • Condition 7—Freshness. The breakout must be on the bar that has just closed. A breakout that occurred on an earlier bar, for example during the confirmation lag or after a failed entry, is never entered late.
Whatever the outcome, a pole is used exactly once. When it is traded, discarded, or expires, its end time is recorded as spent, so the same pole cannot be locked again.

File Structure

The EA uses two files:

  • "MQL5\Include\ChartPatterns\SwingEngine.mqh"—the swing engine from Part 1, unchanged.
  • "MQL5\Experts\FlagPennant\FlagPennantEA.mq5"—the flag and pennant expert advisor.

No other dependencies are required.


Implementation

Inputs

//+------------------------------------------------------------------+
//|                                                FlagPennantEA.mq5 |
//|                                Copyright 2026, Tola Moses Hector |
//|                                          https://t.me/tolahector |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, Tola Moses Hector"
#property link      "https://t.me/tolahector"
#property version   "1.00"
#property description "Flag and Pennant continuation pattern EA"
#property description "Swing structure reads InpSwingTF (default H4) internally"
#property description "Requires SwingEngine.mqh from Part 1"

#include <Trade\Trade.mqh>
#include <ChartPatterns\SwingEngine.mqh>

input group "=== Swing Engine ==="
input int              InpSwingStrength   = 3;            // H4 bars on each side of a swing
input int              InpSwingLookback   = 200;          // Maximum H4 bars to scan
input ENUM_TIMEFRAMES  InpSwingTF         = PERIOD_H4;    // Timeframe for swing structure

input group "=== Pattern Settings ==="
input double InpMinPoleATR     = 2.0;                     // Minimum pole height, in swing-TF ATR
input int    InpMaxPoleBars    = 15;                      // Maximum swing-TF bars for the pole to form
input int    InpMinFlagBars    = 5;                       // Minimum CHART bars of consolidation before a breakout counts
input int    InpMaxFlagBars    = 30;                      // Maximum CHART bars to consolidate before the setup expires
input double InpMaxRetracePct  = 0.5;                     // Maximum flag retracement, as a fraction of pole height
input int    InpATRPeriod      = 14;                      // ATR period, computed on InpSwingTF

input group "=== Entry and Risk ==="
input double InpRiskPercent      = 1.0;                   // Account risk per trade, percent
input double InpSLBufferATR      = 0.5;                   // Stop loss buffer beyond the flag boundary, swing-TF ATR
input bool   InpUseMeasuredMove  = true;                  // Use measured move target (false = 2R fallback)
input double InpMaxSlipATR       = 0.5;                   // Skip entry if price is already this many ATR past the breakout level

input group "=== General ==="
input int    InpMagicNumber      = 444004;                // Magic number
input int    InpSlippage         = 10;                    // Slippage in points
input bool   InpShowLabels       = true;                  // Draw pattern labels on chart
input bool   InpDebugLog         = false;                 // Log the reason every rejected pattern check fails

The "InpMinFlagBars" and "InpMaxFlagBars" bound the consolidation's duration in both directions: too short and the pattern never paused, too long and the setup is stale. Both count chart bars, and both count them from the end of the pole. "InpMaxRetracePct" is a fraction of the pole's own height rather than a fixed ATR distance, matching the classical guideline that a genuine flag rarely gives back more than about half of the move that preceded it.

The defaults are neutral starting values chosen for a EURUSD H1 chart with H4 swings. They are not the result of an optimization run and are not tuned to any symbol. Each has a simple reading on that chart pair:

Input
Default Reading on an H1 chart with H4 swings Effect of raising it (lowering does the opposite)
InpMinPoleATR
2.0 The pole spans at least two average H4 ranges. Fewer, stronger poles.
InpMaxPoleBars
15 15 H4 bars, about two and a half trading days. Slower legs qualify as poles.
InpMinFlagBars
5 Five H1 bars, about five hours of pause. More breakouts are discarded as early.
InpMaxFlagBars
30 30 H1 bars, a little over 1 trading day. More setups survive to breakout, but staler ones.
InpMaxRetracePct
0.5 Half of the pole may be given back. Deeper pullbacks are tolerated.

The two flag settings count chart bars, so on another chart timeframe they cover a different span of time: on M15, 30 bars is seven and a half hours. Treat the table as the expected direction of each input’s effect, and test any change on the symbol and timeframe you intend to use.

Global State and Pattern State Machine
//+------------------------------------------------------------------+
//| Pattern lifecycle                                                |
//+------------------------------------------------------------------+
enum ENUM_FL_STATE
  {
   FL_STATE_SCANNING,   // No pole locked, evaluating every bar
   FL_STATE_TRACKING,   // Pole locked, replaying the flag each bar
   FL_STATE_IN_TRADE    // Position open from this pattern
  };

//+------------------------------------------------------------------+
//| Result of replaying the flag since the pole ended                |
//+------------------------------------------------------------------+
enum ENUM_FLAG_STATUS
  {
   FLAG_PENDING,        // Consolidating inside every limit
   FLAG_BREAKOUT,       // Valid breakout on the bar that just closed
   FLAG_EARLY_BREAK,    // Closed beyond the boundary before InpMinFlagBars
   FLAG_MISSED_BREAK,   // Valid breakout happened on an earlier bar
   FLAG_RETRACED,       // Gave back more than InpMaxRetracePct of the pole
   FLAG_EXPIRED,        // More than InpMaxFlagBars bars without a breakout
   FLAG_NO_DATA         // Chart history not available yet, retry next bar
  };

//+------------------------------------------------------------------+
//| The confirmed pole and the flag measurements derived from it     |
//+------------------------------------------------------------------+
struct SPatternResult
  {
   bool              valid;
   bool              is_bullish;               // true = bullish pole (long breakout), false = bearish pole (short breakout)
   double            pole_start;               // Price where the pole began
   double            pole_end;                 // Price where the pole ended, the flag's starting boundary
   double            break_level;              // Flag boundary in the pole's direction (the level to break)
   double            stop_ref;                 // Opposite flag extreme, the reference for the stop
   int               flag_bars;                // Chart bars in the flag before the current bar
   double            target;                   // Filled in at breakout
   double            stop;                     // Filled in at breakout
   datetime          pole_start_time;          // H4 bar time of the pole's first swing
   datetime          pole_end_time;            // H4 bar time of the pole's last swing, also the pattern identity
  };

CSwingEngine   g_engine;                       // Swing engine from Part 1, reads InpSwingTF internally
CTrade         g_trade;                        // Trade execution object
int            g_atr_handle  = INVALID_HANDLE; // ATR handle on InpSwingTF
datetime       g_last_bar    = 0;              // Last processed CHART bar time
string         g_obj_prefix  = "";             // Unique per symbol + magic number, set in OnInit()

ENUM_FL_STATE  g_state = FL_STATE_SCANNING;    // Current pattern lifecycle state
SPatternResult g_active;                       // The one pole currently locked in

datetime       g_spent_bull_pole = 0;          // pole_end_time of the last bullish pole used up
datetime       g_spent_bear_pole = 0;          // pole_end_time of the last bearish pole used up
string         g_gv_bull_name    = "";         // Global variable names that persist the two values
string         g_gv_bear_name    = "";

The "pole_end_time" doubles as the pattern's identity, the same role "rs_time" played for the head and shoulders and "point2_time" played for the double top. It is also the clock that the flag replay starts from.

The state machine works as follows:

  • SCANNING: Every bar, the detector looks for a bullish and a bearish pole whose end time has not already been spent. If both exist, the one with the more recent end time is locked. The locked pole is evaluated immediately on the same bar.
  • TRACKING: Every bar, the EA confirms the pole is still the engine's pole, then replays the flag from the pole's end to the last closed bar. The replay returns exactly one status. A pending flag is kept. Every other status ends the pole: a breakout is traded, and the rest are discarded. Either way the pole is marked spent and the state leaves TRACKING.
  • IN_TRADE: Every bar, the EA checks "HasOpenPosition()" against the actual position list. When it reports no matching position, the state returns to "SCANNING."

As in Parts 2 and 3, there is no separate boolean for trade state. The position list is the only source of truth, including in "OnInit()". Therefore, when the EA is reattached with an existing position, it resolves to the correct state on the first tick.

Utility Functions

//+------------------------------------------------------------------+
//| Prints a message only when debug logging is enabled              |
//+------------------------------------------------------------------+
void DebugLog(string msg)
  {
   if(InpDebugLog)
      Print("FlagPennantEA[debug]: ", msg);
  }

//+------------------------------------------------------------------+
//| True if a position matching this symbol and magic number exists  |
//| The single source of truth for whether we are in a trade.        |
//+------------------------------------------------------------------+
bool HasOpenPosition(const string symbol, const long magic)
  {
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(!PositionSelectByTicket(ticket))
         continue;
      if(PositionGetString(POSITION_SYMBOL)  != symbol)
         continue;
      if(PositionGetInteger(POSITION_MAGIC)  != magic)
         continue;
      return true;
     }
   return false;
  }

//+------------------------------------------------------------------+
//| Computes lot size from risk percent and stop distance in points  |
//| Skips the trade if the risk-appropriate size rounds below the    |
//| broker minimum, rather than forcing the minimum lot and quietly  |
//| exceeding InpRiskPercent. The stop must be final before this is  |
//| called, because the lot size is only correct for that distance.  |
//+------------------------------------------------------------------+
double CalcLots(double sl_points)
  {
   double balance    = AccountInfoDouble(ACCOUNT_BALANCE);
   double risk_amt   = balance * InpRiskPercent / 100.0;
   double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
   double tick_size  = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   if(tick_size <= 0 || tick_value <= 0 || sl_points <= 0)
      return 0;
   double point_value = (_Point / tick_size) * tick_value;   // Money value of one point, 1.0 lot
   double step    = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   if(step <= 0)
      return 0;
   double raw_lots = risk_amt / (sl_points * point_value);
   double steps    = MathFloor(raw_lots / step + 0.0000001); // Epsilon guards float rounding
   double lots     = NormalizeDouble(steps * step, 8);
   if(lots < min_lot)
      return 0;                                              // Skip rather than over-risk
   return MathMin(max_lot, lots);
  }

//+------------------------------------------------------------------+
//| True if free margin covers the position this order would open    |
//+------------------------------------------------------------------+
bool HasSufficientMargin(ENUM_ORDER_TYPE order_type, double lots, double price)
  {
   double margin_required = 0;
   if(!OrderCalcMargin(order_type, _Symbol, lots, price, margin_required))
      return false;
   return (margin_required <= AccountInfoDouble(ACCOUNT_MARGIN_FREE));
  }

//+------------------------------------------------------------------+
//| Clears every field so no stale value survives between patterns   |
//+------------------------------------------------------------------+
void ResetPattern(SPatternResult &p)
  {
   p.valid           = false;
   p.is_bullish      = true;
   p.pole_start      = 0;
   p.pole_end        = 0;
   p.break_level     = 0;
   p.stop_ref        = 0;
   p.flag_bars       = 0;
   p.target          = 0;
   p.stop            = 0;
   p.pole_start_time = 0;
   p.pole_end_time   = 0;
  }

//+------------------------------------------------------------------+
//| Marks a pole as used and persists the record across restarts     |
//| Called for every way a pole can end: traded, failed entry,       |
//| early break, retrace, missed break, or expiry.                   |
//+------------------------------------------------------------------+
void ClosePole(const SPatternResult &pat)
  {
   if(pat.is_bullish)
     {
      g_spent_bull_pole = pat.pole_end_time;
      GlobalVariableSet(g_gv_bull_name, (double)pat.pole_end_time);
     }
   else
     {
      g_spent_bear_pole = pat.pole_end_time;
      GlobalVariableSet(g_gv_bear_name, (double)pat.pole_end_time);
     }
  }

//+------------------------------------------------------------------+
//| Rewrites the stored records so the terminal's four-week purge    |
//| of unused global variables never reaches a record in use         |
//+------------------------------------------------------------------+
void RefreshSpentRecords()
  {
   if(g_spent_bull_pole > 0)
      GlobalVariableSet(g_gv_bull_name, (double)g_spent_bull_pole);
   if(g_spent_bear_pole > 0)
      GlobalVariableSet(g_gv_bear_name, (double)g_spent_bear_pole);
  }

//+------------------------------------------------------------------+
//| Short text for each flag status, used by the debug log           |
//+------------------------------------------------------------------+
string FlagStatusText(ENUM_FLAG_STATUS st)
  {
   switch(st)
     {
      case FLAG_PENDING:
         return "still consolidating";
      case FLAG_BREAKOUT:
         return "breakout";
      case FLAG_EARLY_BREAK:
         return "closed beyond the boundary before the minimum consolidation";
      case FLAG_MISSED_BREAK:
         return "breakout already happened on an earlier bar";
      case FLAG_RETRACED:
         return "retraced beyond the maximum fraction of the pole";
      case FLAG_EXPIRED:
         return "maximum consolidation length exceeded";
      case FLAG_NO_DATA:
         return "chart history not available";
     }
   return "unknown";
  }

The global variables written by "ClosePole()" let the anti-repeat record outlive the EA. The terminal deletes a global variable that has not been accessed for four weeks, so the record needs a stated lifetime rather than an assumed one. Two things set it. First, "RefreshSpentRecords()," called once per chart bar from "OnTick()," writes both values again, so while the EA is attached the four-week limit never runs out. Second, the record only has to cover a short window. A spent pole can be traded again only if its replay returns a breakout on the bar that has just closed, and the replay rejects any pole older than "InpMaxFlagBars" chart bars plus the confirmation lag as expired or missed. At the default settings that is about two days of H1 bars. The engine may still return a much older pole within "InpSwingLookback," which is long, since 200 H4 bars is about 6.7 weeks of trading bars. But if its record has been purged, the replay discards that stale pole anyway, so a purge cannot cause a repeat trade. The case the record exists for is a restart within a bar or two of a breakout, and there the record is fresh.

Chart Drawing Helpers

//+------------------------------------------------------------------+
//| Creates or moves a horizontal line at the specified price level  |
//+------------------------------------------------------------------+
void DrawHLine(string name, double price, color clr, ENUM_LINE_STYLE style)
  {
   if(!InpShowLabels)
      return;
   string obj = g_obj_prefix + name;
   if(ObjectFind(0, obj) < 0)
     {
      if(!ObjectCreate(0, obj, OBJ_HLINE, 0, 0, price))
        { DebugLog("ObjectCreate failed for " + obj); return; }
     }
   ObjectSetDouble(0,  obj, OBJPROP_PRICE, price);
   ObjectSetInteger(0, obj, OBJPROP_COLOR, clr);
   ObjectSetInteger(0, obj, OBJPROP_STYLE, style);
   ObjectSetInteger(0, obj, OBJPROP_WIDTH, 1);
  }

//+------------------------------------------------------------------+
//| Creates or moves a text label at the specified time and price    |
//+------------------------------------------------------------------+
void DrawLabel(string name, datetime t, double price, string text, color clr)
  {
   if(!InpShowLabels)
      return;
   string obj = g_obj_prefix + name;
   if(ObjectFind(0, obj) < 0)
     {
      if(!ObjectCreate(0, obj, OBJ_TEXT, 0, t, price))
        { DebugLog("ObjectCreate failed for " + obj); return; }
     }
   ObjectMove(0, obj, 0, t, price);
   ObjectSetString(0,  obj, OBJPROP_TEXT, text);
   ObjectSetInteger(0, obj, OBJPROP_COLOR, clr);
   ObjectSetInteger(0, obj, OBJPROP_FONTSIZE, 9);
  }

//+------------------------------------------------------------------+
//| Deletes a single named object, if it exists                      |
//+------------------------------------------------------------------+
void DeleteObject(string name)
  {
   string obj = g_obj_prefix + name;
   if(ObjectFind(0, obj) >= 0)
      ObjectDelete(0, obj);
  }

//+------------------------------------------------------------------+
//| Removes every chart object created by this EA instance           |
//+------------------------------------------------------------------+
void ClearLabels()
  {
   int total = ObjectsTotal(0);
   for(int i = total - 1; i >= 0; i--)
     {
      string name = ObjectName(0, i);
      if(StringFind(name, g_obj_prefix) == 0)
         ObjectDelete(0, name);
     }
  }

Pole Detection

"FindPole()" locates the two adjacent swings. "CheckPole()" applies the height and duration conditions. Neither evaluates the flag, and neither prints anything on success, because "CheckPole()" runs on every scanning bar and the single "pole locked" message belongs to the moment of locking.

//+------------------------------------------------------------------+
//| Finds the newest swing of the pole's end type and the swing      |
//| directly before it. A bullish pole ends on a swing high and      |
//| starts on the swing low immediately preceding it; a bearish pole |
//| mirrors this. No swing can lie between the two endpoints.        |
//+------------------------------------------------------------------+
bool FindPole(bool bullish, SSwingPoint &pole_start, SSwingPoint &pole_end)
  {
   int count = g_engine.GetSwingCount();
   for(int i = 0; i < count - 1; i++)
     {
      SSwingPoint sp = g_engine.GetSwing(i);                 // Index 0 is the newest swing
      if(sp.is_high != bullish)
         continue;                                           // Wrong type to end this pole
      SSwingPoint prev = g_engine.GetSwing(i + 1);           // Its older neighbour
      if(prev.is_high == bullish)
         return false;                                       // Two same-type neighbours: not a single leg
      if(prev.time <= 0 || sp.time <= prev.time)
         return false;
      pole_end   = sp;
      pole_start = prev;
      return true;
     }
   return false;
  }

//+------------------------------------------------------------------+
//| Applies the height and duration conditions to the current pole   |
//| atr must be computed on InpSwingTF, not the chart timeframe      |
//+------------------------------------------------------------------+
bool CheckPole(bool bullish, double atr, SPatternResult &out)
  {
   ResetPattern(out);
   out.is_bullish = bullish;
   string side = bullish ? "Bull" : "Bear";

   SSwingPoint s_start, s_end;
   if(!FindPole(bullish, s_start, s_end))
     { DebugLog(side + " pole reject: no single-leg pole in the latest swings."); return false; }

   double pole_height = bullish ? s_end.price - s_start.price
                        : s_start.price - s_end.price;
   if(pole_height < atr * InpMinPoleATR)
     { DebugLog(StringFormat("%s pole reject: height %.5f below minimum.", side, pole_height)); return false; }

//--- Real swing-TF bar count, not a time difference divided by the bar length
   int start_shift = iBarShift(_Symbol, InpSwingTF, s_start.time, true);
   int end_shift   = iBarShift(_Symbol, InpSwingTF, s_end.time,   true);
   if(start_shift < 0 || end_shift < 0)
     { DebugLog(side + " pole reject: swing bar not found on the swing timeframe."); return false; }
   int pole_bars = start_shift - end_shift;
   if(pole_bars <= 0 || pole_bars > InpMaxPoleBars)
     { DebugLog(StringFormat("%s pole reject: duration=%d bars outside (0, %d].", side, pole_bars, InpMaxPoleBars)); return false; }

   out.valid           = true;
   out.pole_start      = s_start.price;
   out.pole_end        = s_end.price;
   out.pole_start_time = s_start.time;
   out.pole_end_time   = s_end.time;
   return true;
  }

Replaying the Flag

"EvaluateFlag()" is the center of the EA. It does not carry any state from one bar to the next. It starts at the first chart bar after the pole's last H4 bar closed and walks forward to the last closed bar, applying the retracement, minimum-length, lifetime, and breakout rules in the order a trader reading the chart would. Because it recomputes everything from the chart's own history, the same function serves a freshly locked pole, a pole tracked for twenty bars, and a pole rediscovered after an EA restart.

//+------------------------------------------------------------------+
//| Replays chart bars from the end of the pole to the last closed   |
//| bar and returns the status of the flag. Fills break_level,       |
//| stop_ref and flag_bars on the pattern.                           |
//| For a bar k, "prior" is the number of flag bars before it. The   |
//| boundary used to judge bar k is the one as it stood BEFORE bar k.|
//+------------------------------------------------------------------+
ENUM_FLAG_STATUS EvaluateFlag(SPatternResult &pat)
  {
//--- The flag starts when the pole's last swing-TF bar has closed
   datetime flag_start = pat.pole_end_time + PeriodSeconds(InpSwingTF);
   int s = iBarShift(_Symbol, PERIOD_CURRENT, flag_start, false);
   if(s < 0)
      return FLAG_NO_DATA;
   if(iTime(_Symbol, PERIOD_CURRENT, s) < flag_start)
      s--;                                                   // Start fell in a gap: use the first bar after it

   pat.break_level = pat.pole_end;
   pat.stop_ref    = pat.pole_end;
   pat.flag_bars   = 0;
   if(s < 1)
      return FLAG_PENDING;                                   // No closed chart bar in the flag yet

   double pole_height = MathAbs(pat.pole_end - pat.pole_start);
   double max_retrace = pole_height * InpMaxRetracePct;
   double level       = pat.pole_end;                        // Running extreme in the pole's direction
   double opposite    = pat.pole_end;                        // Running extreme against the pole's direction

   for(int k = s; k >= 1; k--)
     {
      int prior = s - k;                                     // Flag bars before bar k
      if(prior > InpMaxFlagBars)
         return FLAG_EXPIRED;

      double h = iHigh(_Symbol,  PERIOD_CURRENT, k);
      double l = iLow(_Symbol,   PERIOD_CURRENT, k);
      double c = iClose(_Symbol, PERIOD_CURRENT, k);

      bool broke;
      if(pat.is_bullish)
        {
         if(l < pat.pole_end - max_retrace)
            return FLAG_RETRACED;
         broke = (c > level);
        }
      else
        {
         if(h > pat.pole_end + max_retrace)
            return FLAG_RETRACED;
         broke = (c < level);
        }

      if(broke)
        {
         if(prior < InpMinFlagBars)
            return FLAG_EARLY_BREAK;                         // Never paused: not a flag
         if(k > 1)
            return FLAG_MISSED_BREAK;                        // Already happened: do not chase
         pat.break_level = level;
         pat.stop_ref    = opposite;
         pat.flag_bars   = prior;
         return FLAG_BREAKOUT;
        }

      //--- No breakout on this bar: it becomes part of the flag boundary
      if(pat.is_bullish)
        {
         level    = MathMax(level,    h);
         opposite = MathMin(opposite, l);
        }
      else
        {
         level    = MathMin(level,    l);
         opposite = MathMax(opposite, h);
        }
     }

   pat.break_level = level;
   pat.stop_ref    = opposite;
   pat.flag_bars   = s;
   return FLAG_PENDING;
  }

Trade Entry Functions

By the time either of these is called, "pat.target" and "pat.stop" have been computed from the final flag measurements. Each function returns "true" only if an order was actually placed, so the caller can tell a trade from a skipped entry.

The order of operations matters. The stop is made valid first, the target is checked, and only then is the lot size computed from the final stop distance. Sizing the position before the stop is adjusted would let the real risk drift above "InpRiskPercent." Only the broker's stops level is used to validate the placement of a new stop and target. The freeze level restricts the modification of orders that are already near the market, not the placement of a new one. Two different prices are used on purpose. The validity checks on the stop and target are measured from the price at which the position would close, the bid for a buy and the ask for a sell, because that is the side the broker compares them with. The lot size is measured from the price at which the position opens to the stop, the ask for a buy and the bid for a sell, because that is the distance the position loses if the stop is hit. The spread is therefore already inside the risk calculation, which keeps the loss at the stop within "InpRiskPercent," apart from lot-step rounding and slippage.

The target has two modes. By default (InpUseMeasuredMove = true) it is the measured move computed in "TrackFlag()." With "InpUseMeasuredMove" = false, the target is placed at twice the stop distance from the entry price, so the reward is 2R: ask + (ask - sl) * 2.0 for a buy and bid - (sl - bid) * 2.0 for a sell. It is computed after the stop has been made valid, so the ratio holds for the stop that is actually sent. The pole’s height plays no part in this mode.

//+------------------------------------------------------------------+
//| Opens a long trade on a confirmed bullish flag breakout          |
//+------------------------------------------------------------------+
bool TryEntryLong(const SPatternResult &pat, double atr)
  {
   if(HasOpenPosition(_Symbol, InpMagicNumber))
      return false;                                                            // Belt-and-braces position check

   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

   if(ask > pat.break_level + atr * InpMaxSlipATR)
     { DebugLog("Bull entry skipped: price already too far past the breakout level."); return false; }

   double min_dist = (double)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * _Point;

//--- 1. Make the stop valid. A buy position closes at the bid.
   double sl = NormalizeDouble(pat.stop, _Digits);
   if(bid - sl < min_dist)
      sl = NormalizeDouble(bid - min_dist - _Point, _Digits);

//--- 2. Target
   double tp = NormalizeDouble(InpUseMeasuredMove ? pat.target : ask + (ask - sl) * 2.0, _Digits);
   if(tp - bid < min_dist)
     { DebugLog("Bull entry skipped: target is already inside the minimum stop distance."); return false; }

//--- 3. Size from the final stop distance
   double lots = CalcLots((ask - sl) / _Point);
   if(lots <= 0)
     { DebugLog("Bull entry skipped: risk-appropriate lot size is below the broker minimum."); return false; }

   if(!HasSufficientMargin(ORDER_TYPE_BUY, lots, ask))
     { DebugLog("Bull entry skipped: insufficient free margin."); return false; }

   if(!g_trade.Buy(lots, _Symbol, 0.0, sl, tp, "Bull Flag"))
     {
      Print("FlagPennantEA: Buy failed | Retcode:", g_trade.ResultRetcode(), " | Error:", GetLastError());
      return false;
     }

   DrawHLine("POLE_START", pat.pole_start,  clrGray,       STYLE_DOT);
   DrawHLine("BREAKOUT",   pat.break_level, clrOrange,     STYLE_DASH);
   DrawHLine("TARGET",     tp,              clrGold,       STYLE_DOT);
   DrawHLine("STOP",       sl,              clrDodgerBlue, STYLE_DOT);
   DrawLabel("ENTRY", iTime(_Symbol, PERIOD_CURRENT, 1),
             iLow(_Symbol, PERIOD_CURRENT, 1) - _Point * 50, "FLAG", clrDodgerBlue);
   Print(StringFormat("FlagPennantEA: LONG | Lots:%.2f | Ask:%.5f | SL:%.5f | TP:%.5f", lots, ask, sl, tp));
   return true;
  }

//+------------------------------------------------------------------+
//| Opens a short trade on a confirmed bearish flag breakout         |
//+------------------------------------------------------------------+
bool TryEntryShort(const SPatternResult &pat, double atr)
  {
   if(HasOpenPosition(_Symbol, InpMagicNumber))
      return false;

   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

   if(bid < pat.break_level - atr * InpMaxSlipATR)
     { DebugLog("Bear entry skipped: price already too far past the breakout level."); return false; }

   double min_dist = (double)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * _Point;

//--- 1. Make the stop valid. A sell position closes at the ask.
   double sl = NormalizeDouble(pat.stop, _Digits);
   if(sl - ask < min_dist)
      sl = NormalizeDouble(ask + min_dist + _Point, _Digits);

//--- 2. Target
   double tp = NormalizeDouble(InpUseMeasuredMove ? pat.target : bid - (sl - bid) * 2.0, _Digits);
   if(ask - tp < min_dist)
     { DebugLog("Bear entry skipped: target is already inside the minimum stop distance."); return false; }

//--- 3. Size from the final stop distance
   double lots = CalcLots((sl - bid) / _Point);
   if(lots <= 0)
     { DebugLog("Bear entry skipped: risk-appropriate lot size is below the broker minimum."); return false; }

   if(!HasSufficientMargin(ORDER_TYPE_SELL, lots, bid))
     { DebugLog("Bear entry skipped: insufficient free margin."); return false; }

   if(!g_trade.Sell(lots, _Symbol, 0.0, sl, tp, "Bear Flag"))
     {
      Print("FlagPennantEA: Sell failed | Retcode:", g_trade.ResultRetcode(), " | Error:", GetLastError());
      return false;
     }

   DrawHLine("POLE_START", pat.pole_start,  clrGray,    STYLE_DOT);
   DrawHLine("BREAKOUT",   pat.break_level, clrOrange,  STYLE_DASH);
   DrawHLine("TARGET",     tp,              clrGold,    STYLE_DOT);
   DrawHLine("STOP",       sl,              clrCrimson, STYLE_DOT);
   DrawLabel("ENTRY", iTime(_Symbol, PERIOD_CURRENT, 1),
             iHigh(_Symbol, PERIOD_CURRENT, 1) + _Point * 50, "FLAG", clrCrimson);
   Print(StringFormat("FlagPennantEA: SHORT | Lots:%.2f | Bid:%.5f | SL:%.5f | TP:%.5f", lots, bid, sl, tp));
   return true;
  }

Tracking a Locked Pole

"TrackFlag()" is the only place where a locked pole changes state. It first confirms the pole is still the one the engine reports, then replays the flag and acts on the single status that comes back.

//+------------------------------------------------------------------+
//| Revalidates and replays the locked pole, then acts on the result |
//+------------------------------------------------------------------+
void TrackFlag(double atr)
  {
//--- Is this still the engine's pole? Identity is checked by both endpoint times.
   SSwingPoint cur_start, cur_end;
   bool same_pole = FindPole(g_active.is_bullish, cur_start, cur_end) &&
                    cur_end.time   == g_active.pole_end_time &&
                    cur_start.time == g_active.pole_start_time;
   if(!same_pole)
     {
      DebugLog("Locked pole is no longer the engine's pole: discarding.");
      DeleteObject("FLAG_WATCH");
      g_state = FL_STATE_SCANNING;
      return;
     }

   ENUM_FLAG_STATUS status = EvaluateFlag(g_active);

   if(status == FLAG_NO_DATA)
     { DebugLog("Flag replay skipped: " + FlagStatusText(status)); return; }   // Retry on the next bar

   if(status == FLAG_PENDING)
     {
      DrawHLine("FLAG_WATCH", g_active.break_level, clrOrange, STYLE_DASH);
      return;
     }

   DeleteObject("FLAG_WATCH");

   if(status != FLAG_BREAKOUT)
     {
      DebugLog("Pole discarded: " + FlagStatusText(status));
      ClosePole(g_active);                                                     // Spent: this pole is never locked again
      g_state = FL_STATE_SCANNING;
      return;
     }

//--- Breakout: the target is measured from the broken boundary, not from the bar's close
   double pole_height = MathAbs(g_active.pole_end - g_active.pole_start);
   if(g_active.is_bullish)
     {
      g_active.target = g_active.break_level + pole_height;
      g_active.stop   = g_active.stop_ref - atr * InpSLBufferATR;
     }
   else
     {
      g_active.target = g_active.break_level - pole_height;
      g_active.stop   = g_active.stop_ref + atr * InpSLBufferATR;
     }
   Print(StringFormat("FlagPennantEA: %s breakout | Level:%.5f | FlagBars:%d | Pole:%.5f",
                      g_active.is_bullish ? "Bull" : "Bear",
                      g_active.break_level, g_active.flag_bars, pole_height));

   bool placed = g_active.is_bullish ? TryEntryLong(g_active, atr)
                 : TryEntryShort(g_active, atr);

   ClosePole(g_active);                                                        // Traded or skipped, the pole is spent either way
   g_state = placed ? FL_STATE_IN_TRADE : FL_STATE_SCANNING;
  }
OnInit, OnDeinit, and OnTick
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(InpSwingStrength <= 0 || InpSwingLookback <= 0 || InpATRPeriod <= 0 ||
      InpMinPoleATR <= 0    || InpMaxPoleBars <= 0    || InpMinFlagBars <= 0 ||
      InpMaxFlagBars < InpMinFlagBars                 ||
      InpMaxRetracePct <= 0 || InpMaxRetracePct > 1.0 ||
      InpRiskPercent <= 0   || InpSLBufferATR < 0     || InpMaxSlipATR < 0)
     {
      Print("FlagPennantEA: one or more input parameters are out of range.");
      return INIT_PARAMETERS_INCORRECT;
     }

//--- The flag is replayed on chart bars and the pole ends on a swing-TF bar,
//--- so a chart bar must never be longer than a swing-TF bar.
   if(PeriodSeconds(PERIOD_CURRENT) > PeriodSeconds(InpSwingTF))
     {
      Print("FlagPennantEA: the chart timeframe must not be higher than InpSwingTF.");
      return INIT_PARAMETERS_INCORRECT;
     }

   g_obj_prefix  = StringFormat("FL_%s_%d_", _Symbol, InpMagicNumber);
   g_gv_bull_name = StringFormat("FL_%s_%d_SPENT_BULL", _Symbol, InpMagicNumber);
   g_gv_bear_name = StringFormat("FL_%s_%d_SPENT_BEAR", _Symbol, InpMagicNumber);

   if(!g_engine.Init(InpSwingStrength, InpSwingLookback, InpSwingTF))
     {
      Print("FlagPennantEA: swing engine initialization failed.");
      return INIT_FAILED;
     }

   g_atr_handle = iATR(_Symbol, InpSwingTF, InpATRPeriod);
   if(g_atr_handle == INVALID_HANDLE)
     {
      Print("FlagPennantEA: ATR handle creation failed.");
      return INIT_FAILED;
     }

   g_trade.SetExpertMagicNumber(InpMagicNumber);
   g_trade.SetDeviationInPoints(InpSlippage);

//--- Restore the record of spent poles. Nothing else needs restoring: an open position
//--- carries its own stop and target, and an unresolved flag is rebuilt by the replay.
   g_spent_bull_pole = GlobalVariableCheck(g_gv_bull_name) ? (datetime)GlobalVariableGet(g_gv_bull_name) : 0;
   g_spent_bear_pole = GlobalVariableCheck(g_gv_bear_name) ? (datetime)GlobalVariableGet(g_gv_bear_name) : 0;

//--- Decide the starting state from the actual position list, not an assumption
   g_state = HasOpenPosition(_Symbol, InpMagicNumber) ? FL_STATE_IN_TRADE : FL_STATE_SCANNING;
   ResetPattern(g_active);
   g_last_bar = 0;

   Print(StringFormat(
            "FlagPennantEA initialized | Symbol:%s | ChartTF:%s | SwingTF:%s | Magic:%d | StartState:%s",
            _Symbol, EnumToString(PERIOD_CURRENT), EnumToString(InpSwingTF), InpMagicNumber,
            (g_state == FL_STATE_IN_TRADE ? "IN_TRADE (recovered)" : "SCANNING")));
   return INIT_SUCCEEDED;
  }

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   if(g_atr_handle != INVALID_HANDLE)
      IndicatorRelease(g_atr_handle);
   ClearLabels();
  }

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   datetime current_bar = iTime(_Symbol, PERIOD_CURRENT, 0);
   if(current_bar == g_last_bar)
      return;                                                           // One run per chart bar
   g_last_bar = current_bar;

   RefreshSpentRecords();                                               // Keeps the stored records alive while the EA runs

   if(Bars(_Symbol, PERIOD_CURRENT) < 5)
      return;                                                           // Chart history not ready yet

   g_engine.Update();                                                   // Self-gated on a new swing-TF bar

   double atr_buf[];
   ArraySetAsSeries(atr_buf, true);
   if(CopyBuffer(g_atr_handle, 0, 1, 1, atr_buf) < 1)
      return;
   double atr = atr_buf[0];
   if(atr <= 0 || atr == EMPTY_VALUE)
     { DebugLog("ATR invalid on this bar, skipping."); return; }

   switch(g_state)
     {
      case FL_STATE_IN_TRADE:
        {
         if(!HasOpenPosition(_Symbol, InpMagicNumber))
           {
            Print("FlagPennantEA: position closed, resuming scan.");
            g_state = FL_STATE_SCANNING;
            ClearLabels();
           }
         break;
        }

      case FL_STATE_TRACKING:
        {
         TrackFlag(atr);
         break;
        }

      case FL_STATE_SCANNING:
        {
         if(HasOpenPosition(_Symbol, InpMagicNumber))                   // Safety net, should be rare
           { g_state = FL_STATE_IN_TRADE; break; }

         SPatternResult bull, bear;
         bool have_bull = CheckPole(true,  atr, bull) && bull.pole_end_time != g_spent_bull_pole;
         bool have_bear = CheckPole(false, atr, bear) && bear.pole_end_time != g_spent_bear_pole;
         if(!have_bull && !have_bear)
            break;

         //--- If both qualify, the pole that ended more recently is the fresher impulse
         bool take_bull = have_bull && (!have_bear || bull.pole_end_time > bear.pole_end_time);
         if(take_bull)
            g_active = bull;
         else
            g_active = bear;
         g_state = FL_STATE_TRACKING;

         Print(StringFormat("FlagPennantEA: %s pole locked | Start:%.5f | End:%.5f | EndTime:%s",
                            g_active.is_bullish ? "Bull" : "Bear",
                            g_active.pole_start, g_active.pole_end,
                            TimeToString(g_active.pole_end_time, TIME_DATE | TIME_MINUTES)));

         TrackFlag(atr);                                                // Replay the flag on this same bar
         break;
        }
     }

   ChartRedraw(0);                                                      // One redraw per bar, not per object
  }
//+------------------------------------------------------------------+


The State Machine—Why It Matters

A flag is not a fixed level the way a neckline is. The double top and head and shoulders both lock a single price the moment the pattern is confirmed and wait for a close through it. A flag's boundary is still being built while the EA watches it: every bar that fails to break out may extend the boundary, and the pattern's own validity, such as whether it has retraced too far or taken too long, has to be judged against that moving boundary.

This article's design choice is to avoid maintaining a running boundary. "EvaluateFlag()" recomputes the boundary from chart history on every bar, starting at the end of the pole. That choice removes a whole class of problems that come from keeping a counter and a boundary up to date by hand. The flag age is the real number of bars since the pole ended, not the number of bars since the EA noticed the pole. The same code handles a pole that was found late, a pole tracked since it ended, and a pole rediscovered after a restart. A breakout is tested against the boundary as it stood before the bar being tested, and the boundary is extended afterwards.

Every ending is explicit. A pole can end in six ways: a traded breakout, a breakout that was skipped by the entry checks, an early breakout, a retracement, a breakout that already happened, or an expiry. In every case "ClosePole()" records the pole's end time as spent, and the state leaves "TRACKING." This closes two gaps that a simpler machine leaves open. A skipped entry cannot be retried on the next bar, because the pole is spent. An expired or failed pole cannot be locked again on the next bar, because the same pole would otherwise be found again by the next scan and restart at age zero.

The spent record is saved with "GlobalVariableSet()" and read back in "OnInit()," so it survives a restart. This is the only state that needs to. An open position holds its own stop and target, and "HasOpenPosition()" restores the "IN_TRADE" state. A flag that was still unresolved at restart needs no stored copy, because the replay rebuilds it from the swing engine and the chart history on the first bar.

The pole's identity is checked on every bar. If new swing data changes which swings form the pole, for example because a newer swing now sits between the two endpoints or the pole's end type has a newer swing, the locked pole is dropped without being marked spent, and scanning evaluates the engine's current pole from scratch.


Backtesting Notes

What to expect:

Poles that meet the height and duration thresholds are more common than full Head and Shoulders sequences, but most do not produce a clean flag. Many retrace beyond "InpMaxRetracePct" within the first few bars, and many break out before "InpMinFlagBars" is reached and are discarded as never having paused. With "InpDebugLog" enabled, the journal gives each outcome its own reason: no single-leg pole, a pole below the height or duration limit, and, once a pole is locked, an early breakout, a retracement, a breakout that had already happened, or an expiry.

If very few poles are found at all, reduce "InpMinPoleATR" or increase "InpMaxPoleBars." If poles are found but are mostly discarded as retraced, "InpMaxRetracePct" may be too strict for the instrument's typical pullback depth, so try raising it toward 0.6 or 0.7. If poles are mostly discarded as early breakouts, "InpMinFlagBars" may be too high for the chosen chart timeframe. If poles survive but rarely break out before expiring, raise "InpMaxFlagBars."


Known Limitations

  • Shape is not measured. The detector confirms a pole, a bounded pause of sufficient length, and a close beyond the pause's boundary. It does not test slope, parallelism, convergence, or the internal sequence of highs and lows. A channel that drifts against the pole (a classical flag) and a narrowing wedge (a classical pennant) are therefore treated identically, and so is a plain sideways range after a strong move. The result is best understood as a post-impulse range breakout detector that targets the flag and pennant family, not as a shape classifier. Separating the two would require measuring whether the range is shrinking over time and whether the boundary lines slope, which this version does not compute.
  • No volatility contraction check. Classical continuation pattern theory often expects range and volume to contract during the consolidation. This implementation bounds the consolidation's depth and duration only, and does not verify that the bars inside it are quieter than the pole.
  • The boundary uses bar extremes. The tracked boundary is built from each chart bar's high and low. On a chart timeframe with wide bar ranges relative to the pole, a single spike can widen the boundary and delay a breakout compared with what a discretionary trader reading the same chart might call.
  • Pole thresholds use the ATR at the moment of locking. The pole's height is compared with the ATR value on the bar where the pole is first found. The identity check afterwards confirms the same two swings still form the pole, but it does not re-test the height against later ATR values.
  • No trend context is required. The pole is a single impulsive leg, and nothing in the detector requires that it continue the larger trend. A strong leg against the prevailing structure can still qualify. A filter on the engine's trend read could be added, but, as Part 3 showed, it must not demand a label on the same swing that defines the pole.
  • A skipped entry spends the pole. If the entry checks reject a valid breakout, for example because price has already moved too far or the lot size would fall below the broker minimum, the pole is not retried. This is deliberate. A late entry on the following bar would be a different trade from the one the pattern defined.
  • Spread is in the risk, not in the target. Position size is computed from the entry price to the stop, so the spread is already part of the risk at the stop. The measured-move target is a fixed price level and is not adjusted for spread: a long closes at the bid, so the bid must reach the target, and a wide spread reduces the realized reward relative to the structural figure the pattern implies. On tightly spread majors this is a small effect; on wider-spread symbols or shorter chart timeframes it can be larger.
  • One position at a time. "FL_STATE_IN_TRADE" blocks all scanning until the open position closes. A second pole that becomes eligible while a position is already open is not locked in. If its flag is still active when scanning resumes, it is picked up and replayed from its true age, and if its flag has already resolved, it is discarded as expired or missed.


Conclusion

The flag and pennant complete the first full pass across both pattern families in this series. Reversal patterns require several swings in a specific sequence, while this continuation pattern requires a single strong leg followed by a bounded pause. The engineering challenge was different in kind. The double top and head and shoulders both lock a fixed level and wait. The flag's boundary moves, so the EA replays it from the end of the pole on every bar, and the replay answers every timing question from real chart bars rather than from counters kept by hand.

Three rules carry over to any pattern built on swing data. A swing's time and its confirmation time are different moments, and anything measured from the pattern's own start must use the first. A bar count must be a count of bars, taken with "iBarShift()," never a time difference divided by a bar length. And a pattern that is traded, skipped, or discarded must be recorded as spent in storage that outlives the EA, or the anti-repeat protection only works until the next restart.

File Reference

Save "SwingEngine.mqh" from Part 1 to "MQL5\Include\ChartPatterns\SwingEngine.mqh."

Save "FlagPennantEA.mq5" to "MQL5\Experts\FlagPennant\FlagPennantEA.mq5."

Compile in MetaEditor. No additional dependencies are required beyond the MQL5 standard library.

Attach to EURUSD or GBPUSD on H1 with "InpSwingTF" set to H4. Test on a demo account before live deployment. Tested with MetaTrader 5 build [6230]: EURUSD, H1 chart, InpSwingTF = H4, default inputs, Strategy Tester in “Every tick based on real ticks” mode. The code compiles with 0 errors and 0 warnings in MetaEditor, and a successful start shows the journal line “FlagPennantEA initialized … StartState:SCANNING”.

Programs used in the article:

# Name Type Description
1 FlagPennantEA.mq5 Demo EA Flag and pennant demonstration EA.
2 SwingEngine.mqh Include File Swing detection engine from Part 1.
3 MQL5.zip Zip Archive
Archive with all files that can be unpacked into the terminal installation directory, and all files will be located in the required places.


Attached files |
FlagPennantEA.mq5 (32.66 KB)
SwingEngine.mqh (17.09 KB)
MQL5.zip (12.4 KB)
The MQL5 Standard Library Explorer (Part 19): Developing a Reusable Portfolio Risk Manager The MQL5 Standard Library Explorer (Part 19): Developing a Reusable Portfolio Risk Manager
This article explores CAccountInfo through a shared risk authority for a multi-symbol Expert Advisor. We model requests, decisions, and reservations, then apply portfolio, symbol, position, direction, and margin checks before submitting trades. The example also explains the limits of its reservation and execution handling.
Marginal Drawdown Contribution Analyzer in MQL5: Which Configuration Deepens Your Portfolio Drawdown Marginal Drawdown Contribution Analyzer in MQL5: Which Configuration Deepens Your Portfolio Drawdown
We show how to attribute realized portfolio drawdown to individual configurations inside MetaTrader 5. Using daily results grouped by magic (optionally magic and symbol), the tool rebuilds the portfolio curve and quantifies three contributions: leave-one-out drawdown, shares of the deepest drawdown episodes, and Euler variance share. Flags are checked for stability across sample halves and rolled up into a heuristic A+–F score for practical diagnostics.
Building a Prop-Firm Rule Guard in MQL5 (Part 2): Eight Rules, One Directive, and the Action Layer Building a Prop-Firm Rule Guard in MQL5 (Part 2): Eight Rules, One Directive, and the Action Layer
An MQL5 prop-firm guard must evaluate account rules before it acts and verify that protective actions have completed. This article examines eight rules, two-phase directive resolution, position closing, Algo Trading state checks and restart recovery. A demo and synthetic tests show how to use the guard and verify its rule logic.
Interactive Supply and Demand Zone Manager in MQL5 (Part VI): Dual-Timeframe Zone Detection and Lifecycle Management Interactive Supply and Demand Zone Manager in MQL5 (Part VI): Dual-Timeframe Zone Detection and Lifecycle Management
This installation implements source‑aware processing: select a lower source or a lower/higher pair, then run detection and lifecycle per source with dedicated ATR, history checks, and bar stamps. Zones store their source timeframe for logging and snapshot persistence, and only that source's chart displays and permits edits. The result is predictable chart switching, reproducible restoration, and clearer separation of signals across timeframes.