//+------------------------------------------------------------------+
//| MajorSwingHL.mq5                                                  |
//| Major Swing High/Low - custom market-structure reversals          |
//|                                                                   |
//| MAJOR (custom market structure, the main signal):                 |
//|   Swing points = swings of at least MinSwingSize (price units,    |
//|   gold 20 = 20 USD). A swing high counts once price has fallen    |
//|   MinSwingSize below it, a swing low once price has risen         |
//|   MinSwingSize above it.                                          |
//|   Bias bearish: BUY when BreakHoldCandles closed candles in a row |
//|   close above the last significant lower high = the highest       |
//|   confirmed swing high of the last SwingLength candles. The major |
//|   Swing L = lowest low since the last major Swing H. Bias turns   |
//|   bullish. SELL is the mirror (break of the significant higher    |
//|   low). BUY and SELL always alternate.                            |
//|                                                                   |
//| Benchmark modes (off by default): Original = ChartPrime Swing     |
//| High/Low (ZigZag) confirmation (MPL-2.0 open-source logic), Fast. |
//|                                                                   |
//| Every signal is decided on a CLOSED candle and is stamped on the  |
//| NEXT candle. Signals are never moved back and never removed.      |
//|                                                                   |
//| EARLY entry (v1.02, off by default): while the major bias is      |
//|   bearish and the fall from the major Swing H is at least         |
//|   MinLegForEarly, EARLY BUY when a candle closes above the last   |
//|   internal lower high (internal swings of EarlyInternalSwing) and |
//|   the leg low was made after that lower high. Stop = the leg low. |
//|   One try per major leg by default. SELL is the mirror.           |
//|                                                                   |
//| Buffers for an EA (value = swing price, EMPTY_VALUE = no signal): |
//|   0 Original BUY   1 Original SELL   2 Fast BUY   3 Fast SELL     |
//|   4 MAJOR BUY      5 MAJOR SELL                                   |
//|   6 EARLY BUY      7 EARLY SELL   (value = leg low / leg high)    |
//|   8 STOP for BUY   9 STOP for SELL (on every MAJOR/EARLY alert:   |
//|     major = last confirmed small swing of StopInternalSwing,      |
//|     early = the leg low / high)                                   |
//+------------------------------------------------------------------+
#property copyright "Major Swing High/Low"
#property version   "1.10"
#property description "Custom market-structure major swings: BUY/SELL on the next candle after a confirmed structure break, no repaint. v1.02: optional early entry + suggested stop level."
#property indicator_chart_window
#property indicator_buffers 10
#property indicator_plots   10

#property indicator_label1  "Original BUY (Swing L)"
#property indicator_type1   DRAW_ARROW
#property indicator_color1  clrLimeGreen
#property indicator_width1  3
#property indicator_label2  "Original SELL (Swing H)"
#property indicator_type2   DRAW_ARROW
#property indicator_color2  clrMagenta
#property indicator_width2  3
#property indicator_label3  "Fast BUY"
#property indicator_type3   DRAW_ARROW
#property indicator_color3  clrDodgerBlue
#property indicator_width3  2
#property indicator_label4  "Fast SELL"
#property indicator_type4   DRAW_ARROW
#property indicator_color4  clrOrange
#property indicator_width4  2
#property indicator_label5  "MAJOR BUY (swing low)"
#property indicator_type5   DRAW_NONE
#property indicator_label6  "MAJOR SELL (swing high)"
#property indicator_type6   DRAW_NONE
#property indicator_label7  "EARLY BUY (leg low)"
#property indicator_type7   DRAW_NONE
#property indicator_label8  "EARLY SELL (leg high)"
#property indicator_type8   DRAW_NONE
#property indicator_label9  "STOP for BUY"
#property indicator_type9   DRAW_NONE
#property indicator_label10 "STOP for SELL"
#property indicator_type10  DRAW_NONE

input group "Major swing (custom market structure)"
input int    SwingLength        = 200;    // Swing length (candles) to look back for the structure level
input double MinSwingSize       = 20.0;   // Minimum swing size in price (gold: 20 = 20 USD)
input int    BreakHoldCandles   = 2;      // Closed candles in a row beyond the level to confirm the break
input bool   ShowMajor          = true;   // Major BUY/SELL: show + alert

input group "Chart look"
input bool   ShowLevels         = true;   // Swing L / Swing H level lines with price labels
input bool   ShowZigzag         = true;   // Dashed lines between major swing points
input bool   ShowSignalLabels   = true;   // BUY / SELL label on the alert candle
input color  ColorSwingL        = C'34,204,102';   // Swing L / BUY colour
input color  ColorSwingH        = C'176,64,224';   // Swing H / SELL colour
input int    LabelFontSize      = 9;      // Label font size

input group "Benchmark modes (off by default)"
input bool   ShowOriginal       = false;  // Original ChartPrime confirmation: show + alert
input bool   ShowFast           = false;  // Fast detection: show + alert
input bool   UseLightConfirm    = true;   // Fast: light confirmation on/off
input int    ConfirmCandles     = 5;      // Fast: close above the highs of the last N candles (SELL: below the lows)
input bool   UseReArm           = false;  // Fast: re-arm distance on/off
input double ReArmDistance      = 10.0;   // Fast: re-arm distance in price
input bool   StrictAlternation  = false;  // Fast: strict BUY/SELL alternation

input group "Alerts"
input bool   AlertPopup         = true;   // Popup alert
input bool   AlertSound         = true;   // Sound
input string AlertSoundFile     = "alert.wav";
input bool   AlertPush          = false;  // Push notification to phone

input group "Early entry + stop level (v1.02)"
input bool   ShowEarly          = false;  // Early BUY/SELL: show + alert (buffers 6/7 are always filled)
input double EarlyInternalSwing = 8.0;    // Early: internal swing size in price (gold: 8 = 8 USD)
input double MinLegForEarly     = 30.0;   // Early: the major leg must already be this long (price)
input int    MaxEarlyTries      = 1;      // Early: tries per major leg (a try ends when its stop is hit)
input double StopInternalSwing  = 5.0;    // Stop level for MAJOR signals: last small swing of this size

double BufOB[], BufOS[], BufFB[], BufFS[], BufMB[], BufMS[], BufEB[], BufES[], BufSB[], BufSS[];

// ---- small zigzag (internal swings): keeps only the last confirmed swing high and low
struct ZZ
  {
   int    dir; double hp; int hb; double lp; int lb;
   bool   hasHi; double hiPx; int hiBar;
   bool   hasLo; double loPx; int loBar;
  };
ZZ zE, zS;                       // early internal swings, stop swings
double e_extPx; int e_extBar;    // leg extreme since the last major swing
bool   e_alive; double e_stop; int e_tries;
int    e_count;

// ---- benchmark state
int      g_next;
datetime g_nextTime;
int      g_trend;
int      g_candBar[2];
double   g_candPx[2];
bool     g_armedFlag[2];
double   g_lastPx[2];
datetime g_alerted[8];

// ---- major (structure) state
int      z_dir;                 // 0 unknown, 1 tracking a high, -1 tracking a low
double   z_hiPx, z_loPx;
int      z_hiBar, z_loBar;
int      ph_bar[]; double ph_px[]; int ph_n;   // confirmed swing highs
int      pl_bar[]; double pl_px[]; int pl_n;   // confirmed swing lows
int      m_bias;                // 0 unknown, 1 bullish, -1 bearish
int      m_legBar;              // candle of the last major swing point
double   m_legPx;
int      m_runB, m_runS;
int      m_count;               // number of major swings drawn
string   g_pfx;
string   g_lastLvl[2];          // names of the live level lines (0 = L, 1 = H)

//+------------------------------------------------------------------+
// Symbol presets use absolute price units, not broker points.
input group "Multi-market presets"
input bool AutoSymbolPreset = true;
input double US30SwingSize = 100.0;
input double EURUSDSwingSize = 0.0020;
double g_MinSwingSize, g_EarlyInternalSwing, g_MinLegForEarly, g_StopInternalSwing, g_ReArmDistance;

void ResolveSymbolPreset()
  {
   string sym = _Symbol;
   StringToUpper(sym);
   double scale = 1.0;
   if(AutoSymbolPreset)
     {
      if(StringFind(sym,"EURUSD") >= 0) scale = EURUSDSwingSize / 20.0;
      else if(StringFind(sym,"US30") >= 0 || StringFind(sym,"DJ30") >= 0 ||
              StringFind(sym,"DJI") >= 0 || StringFind(sym,"WS30") >= 0 ||
              StringFind(sym,"WALLSTREET") >= 0 || StringFind(sym,"DOW") >= 0)
         scale = US30SwingSize / 20.0;
     }
   g_MinSwingSize = MinSwingSize * scale;
   g_EarlyInternalSwing = EarlyInternalSwing * scale;
   g_MinLegForEarly = MinLegForEarly * scale;
   g_StopInternalSwing = StopInternalSwing * scale;
   g_ReArmDistance = ReArmDistance * scale;
  }

int OnInit()
  {
   ResolveSymbolPreset();
   if(SwingLength < 2 || ConfirmCandles < 1 || g_MinSwingSize <= 0 || BreakHoldCandles < 1 ||
      g_EarlyInternalSwing <= 0 || g_StopInternalSwing <= 0 || MaxEarlyTries < 0)
     {
      Print("SwingLength >= 2, g_MinSwingSize > 0, BreakHoldCandles >= 1, ConfirmCandles >= 1, internal swing sizes > 0 and MaxEarlyTries >= 0 are needed");
      return(INIT_PARAMETERS_INCORRECT);
     }
   SetIndexBuffer(0, BufOB, INDICATOR_DATA);
   SetIndexBuffer(1, BufOS, INDICATOR_DATA);
   SetIndexBuffer(2, BufFB, INDICATOR_DATA);
   SetIndexBuffer(3, BufFS, INDICATOR_DATA);
   SetIndexBuffer(4, BufMB, INDICATOR_DATA);
   SetIndexBuffer(5, BufMS, INDICATOR_DATA);
   SetIndexBuffer(6, BufEB, INDICATOR_DATA);
   SetIndexBuffer(7, BufES, INDICATOR_DATA);
   SetIndexBuffer(8, BufSB, INDICATOR_DATA);
   SetIndexBuffer(9, BufSS, INDICATOR_DATA);
   PlotIndexSetInteger(0, PLOT_ARROW, 233);
   PlotIndexSetInteger(1, PLOT_ARROW, 234);
   PlotIndexSetInteger(2, PLOT_ARROW, 241);
   PlotIndexSetInteger(3, PLOT_ARROW, 242);
   PlotIndexSetInteger(0, PLOT_ARROW_SHIFT, 12);
   PlotIndexSetInteger(1, PLOT_ARROW_SHIFT, -12);
   PlotIndexSetInteger(2, PLOT_ARROW_SHIFT, 12);
   PlotIndexSetInteger(3, PLOT_ARROW_SHIFT, -12);
   for(int p = 0; p < 10; p++)
      PlotIndexSetDouble(p, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   if(!ShowOriginal) { PlotIndexSetInteger(0, PLOT_DRAW_TYPE, DRAW_NONE); PlotIndexSetInteger(1, PLOT_DRAW_TYPE, DRAW_NONE); }
   if(!ShowFast)     { PlotIndexSetInteger(2, PLOT_DRAW_TYPE, DRAW_NONE); PlotIndexSetInteger(3, PLOT_DRAW_TYPE, DRAW_NONE); }
   IndicatorSetString(INDICATOR_SHORTNAME, StringFormat("Major Swing HL (%d, %s)", SwingLength, DoubleToString(g_MinSwingSize, _Digits)));
   IndicatorSetInteger(INDICATOR_DIGITS, _Digits);
   g_pfx = StringFormat("MSHL_%d_%s_%d_%d_", SwingLength, DoubleToString(g_MinSwingSize, _Digits), BreakHoldCandles, (int)ShowEarly);
   ResetState();
   ArrayInitialize(g_alerted, 0);
   return(INIT_SUCCEEDED);
  }

void OnDeinit(const int reason) { ObjectsDeleteAll(0, g_pfx); ChartRedraw(); }

//+------------------------------------------------------------------+
void ResetState()
  {
   g_next = 0;
   g_nextTime = 0;
   g_trend = -1;
   for(int d = 0; d < 2; d++)
     {
      g_candBar[d] = -1; g_candPx[d] = 0;
      g_armedFlag[d] = true; g_lastPx[d] = 0;
     }
   z_dir = 0; z_hiPx = 0; z_loPx = 0; z_hiBar = 0; z_loBar = 0;
   ph_n = 0; pl_n = 0;
   ArrayResize(ph_bar, 0, 1024); ArrayResize(ph_px, 0, 1024);
   ArrayResize(pl_bar, 0, 1024); ArrayResize(pl_px, 0, 1024);
   m_bias = 0; m_legBar = 0; m_legPx = 0; m_runB = 0; m_runS = 0; m_count = 0;
   ZZReset(zE); ZZReset(zS);
   e_extPx = 0; e_extBar = 0; e_alive = false; e_stop = 0; e_tries = 0; e_count = 0;
   g_lastLvl[0] = ""; g_lastLvl[1] = "";
   ObjectsDeleteAll(0, g_pfx);
  }

//+------------------------------------------------------------------+
double HighestH(const double &h[], int i) { return h[ArrayMaximum(h, i - SwingLength + 1, SwingLength)]; }
double LowestL(const double &l[], int i)  { return l[ArrayMinimum(l, i - SwingLength + 1, SwingLength)]; }

//+------------------------------------------------------------------+
void DoAlert(int k, string what, double px, datetime t, bool live)
  {
   if(!live || g_alerted[k] == t)
      return;
   g_alerted[k] = t;
   string msg = StringFormat("Major Swing %s | %s %s | swing %s", what, _Symbol,
                             StringSubstr(EnumToString((ENUM_TIMEFRAMES)_Period), 7), DoubleToString(px, _Digits));
   if(AlertPopup) Alert(msg);
   if(AlertSound && !AlertPopup) PlaySound(AlertSoundFile);
   if(AlertPush) SendNotification(msg);
  }

//+------------------------------------------------------------------+
//| Chart objects                                                    |
//+------------------------------------------------------------------+
void Txt(string name, datetime t, double px, string text, color c, ENUM_ANCHOR_POINT anc)
  {
   ObjectCreate(0, name, OBJ_TEXT, 0, t, px);
   ObjectSetString(0, name, OBJPROP_TEXT, text);
   ObjectSetInteger(0, name, OBJPROP_COLOR, c);
   ObjectSetInteger(0, name, OBJPROP_FONTSIZE, LabelFontSize);
   ObjectSetString(0, name, OBJPROP_FONT, "Arial Bold");
   ObjectSetInteger(0, name, OBJPROP_ANCHOR, anc);
   ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
  }

void Line(string name, datetime t1, double p1, datetime t2, double p2, color c, ENUM_LINE_STYLE st, int w, bool ray)
  {
   ObjectCreate(0, name, OBJ_TREND, 0, t1, p1, t2, p2);
   ObjectSetInteger(0, name, OBJPROP_COLOR, c);
   ObjectSetInteger(0, name, OBJPROP_STYLE, st);
   ObjectSetInteger(0, name, OBJPROP_WIDTH, w);
   ObjectSetInteger(0, name, OBJPROP_RAY_RIGHT, ray);
   ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
   ObjectSetInteger(0, name, OBJPROP_BACK, true);
  }

void Mark(string name, datetime t, double px, int code, color c, ENUM_ARROW_ANCHOR anc, int w)
  {
   ObjectCreate(0, name, OBJ_ARROW, 0, t, px);
   ObjectSetInteger(0, name, OBJPROP_ARROWCODE, code);
   ObjectSetInteger(0, name, OBJPROP_COLOR, c);
   ObjectSetInteger(0, name, OBJPROP_ANCHOR, anc);
   ObjectSetInteger(0, name, OBJPROP_WIDTH, w);
   ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
  }

// draw one major swing: swing point j (price px), alert candle a
void DrawMajor(bool buy, int j, double px, int a, const datetime &time[], const double &high[], const double &low[], const double &close[])
  {
   color c = buy ? ColorSwingL : ColorSwingH;
   string id = g_pfx + IntegerToString(m_count);
   // swing candle mark (small circle on the real turning candle)
   Mark(id + "_pt", time[j], px, 161, c, buy ? ANCHOR_TOP : ANCHOR_BOTTOM, 1);
   // dashed line from the previous major swing point
   if(ShowZigzag && m_count > 0)
      Line(id + "_zz", time[m_legBar], m_legPx, time[j], px, buy ? ColorSwingH : ColorSwingL, STYLE_DASH, 1, false);
   // level line: the previous level of the same side stops here, the new one runs to the right
   if(ShowLevels)
     {
      int s = buy ? 0 : 1;
      if(g_lastLvl[s] != "")
        {
         ObjectSetInteger(0, g_lastLvl[s], OBJPROP_RAY_RIGHT, false);
         ObjectSetInteger(0, g_lastLvl[s], OBJPROP_TIME, 1, time[j]);
         ObjectDelete(0, g_lastLvl[s] + "_t");
        }
      g_lastLvl[s] = id + "_lv";
      Line(g_lastLvl[s], time[j], px, time[a], px, c, STYLE_SOLID, 2, true);
      Txt(g_lastLvl[s] + "_t", time[a], px, StringFormat("Swing %s (%s)", buy ? "L" : "H", DoubleToString(px, _Digits)), c, buy ? ANCHOR_LEFT_UPPER : ANCHOR_LEFT_LOWER);
     }
   // BUY / SELL label on the alert candle
   if(ShowSignalLabels)
     {
      int b0 = MathMax(0, a - 30);
      double rng = high[ArrayMaximum(high, b0, a - b0 + 1)] - low[ArrayMinimum(low, b0, a - b0 + 1)];
      double y = buy ? low[a] : high[a];
      Mark(id + "_ar", time[a], y, buy ? 233 : 234, c, buy ? ANCHOR_TOP : ANCHOR_BOTTOM, 3);
      Txt(id + "_lb", time[a], buy ? y - rng * 0.35 : y + rng * 0.35,
          StringFormat("%s %s", buy ? "BUY" : "SELL", DoubleToString(close[a - 1], _Digits)), c, buy ? ANCHOR_LEFT_UPPER : ANCHOR_LEFT_LOWER);
     }
   m_count++;
  }

// keep the level labels at the right edge + the developing leg line
void RefreshLive(int rates_total, const datetime &time[], const double &high[], const double &low[])
  {
   datetime tr = time[rates_total - 1] + PeriodSeconds() * 3;
   for(int s = 0; s < 2; s++)
      if(g_lastLvl[s] != "" && ObjectFind(0, g_lastLvl[s] + "_t") >= 0)
         ObjectSetInteger(0, g_lastLvl[s] + "_t", OBJPROP_TIME, 0, tr);
   string nm = g_pfx + "dev";
   if(!ShowZigzag || m_count == 0) { ObjectDelete(0, nm); return; }
   int k;
   if(m_bias > 0) k = ArrayMaximum(high, m_legBar, rates_total - m_legBar);
   else           k = ArrayMinimum(low,  m_legBar, rates_total - m_legBar);
   double p = (m_bias > 0 ? high[k] : low[k]);
   if(ObjectFind(0, nm) < 0)
      Line(nm, time[m_legBar], m_legPx, time[k], p, m_bias > 0 ? ColorSwingL : ColorSwingH, STYLE_DOT, 1, false);
   ObjectMove(0, nm, 0, time[m_legBar], m_legPx);
   ObjectMove(0, nm, 1, time[k], p);
   ObjectSetInteger(0, nm, OBJPROP_COLOR, m_bias > 0 ? ColorSwingL : ColorSwingH);
  }

//+------------------------------------------------------------------+
//| MAJOR: custom market structure on closed candle i, stamp on i+1  |
//+------------------------------------------------------------------+
void ProcessMajor(int i, const double &h[], const double &l[], const double &c[], int rates_total, const datetime &time[])
  {
   double hh = h[i], ll = l[i], cc = c[i];
   if(i == 0) { z_hiPx = hh; z_hiBar = 0; z_loPx = ll; z_loBar = 0; }
   // ---- swing points of at least g_MinSwingSize
   if(z_dir >= 0 && hh > z_hiPx) { z_hiPx = hh; z_hiBar = i; }
   if(z_dir <= 0 && ll < z_loPx) { z_loPx = ll; z_loBar = i; }
   if(z_dir == 0)
     {
      if(z_hiPx - ll >= g_MinSwingSize && z_hiBar < i)      { AddHi(); z_dir = -1; z_loPx = ll; z_loBar = i; }
      else if(hh - z_loPx >= g_MinSwingSize && z_loBar < i) { AddLo(); z_dir = 1;  z_hiPx = hh; z_hiBar = i; }
     }
   else if(z_dir == 1)
     {
      if(z_hiPx - ll >= g_MinSwingSize && z_hiBar < i)      { AddHi(); z_dir = -1; z_loPx = ll; z_loBar = i; }
     }
   else
     {
      if(hh - z_loPx >= g_MinSwingSize && z_loBar < i)      { AddLo(); z_dir = 1;  z_hiPx = hh; z_hiBar = i; }
     }
   // ---- small swings (early entry + stop level)
   ZZStep(zE, i, hh, ll, g_EarlyInternalSwing);
   ZZStep(zS, i, hh, ll, g_StopInternalSwing);
   // ---- leg extreme + early stop
   if(m_bias < 0)
     {
      if(ll < e_extPx) { e_extPx = ll; e_extBar = i; }
      if(e_alive && ll < e_stop) e_alive = false;
     }
   else if(m_bias > 0)
     {
      if(hh > e_extPx) { e_extPx = hh; e_extBar = i; }
      if(e_alive && hh > e_stop) e_alive = false;
     }
   // ---- structure break
   int start = i - SwingLength + 1;
   int a = i + 1;
   bool live = (a == rates_total - 1);
   if(m_bias <= 0 && ph_n > 0)
     {
      double lvl = 0; bool got = false;
      for(int k = ph_n - 1; k >= 0; k--)
        {
         if(ph_bar[k] < start) break;
         if(!got || ph_px[k] > lvl) { lvl = ph_px[k]; got = true; }
        }
      if(!got) lvl = ph_px[ph_n - 1];
      m_runB = (cc > lvl ? m_runB + 1 : 0);
      if(m_runB >= BreakHoldCandles)
        {
         int s0 = (m_bias != 0 ? m_legBar : MathMax(0, i - SwingLength + 1));
         int j = ArrayMinimum(l, s0, i - s0 + 1);
         BufMB[a] = l[j];
         BufSB[a] = (zS.hasLo ? zS.loPx : l[j]);
         if(ShowMajor)
           {
            DrawMajor(true, j, l[j], a, time, h, l, c);
            DoAlert(4, "BUY (major swing low)", l[j], time[a], live);
           }
         m_bias = 1; m_legBar = j; m_legPx = l[j]; m_runB = 0; m_runS = 0;
         NewLeg(i, h, l);
         return;
        }
     }
   if(m_bias >= 0 && pl_n > 0)
     {
      double lvl = 0; bool got = false;
      for(int k = pl_n - 1; k >= 0; k--)
        {
         if(pl_bar[k] < start) break;
         if(!got || pl_px[k] < lvl) { lvl = pl_px[k]; got = true; }
        }
      if(!got) lvl = pl_px[pl_n - 1];
      m_runS = (cc < lvl ? m_runS + 1 : 0);
      if(m_runS >= BreakHoldCandles)
        {
         int s0 = (m_bias != 0 ? m_legBar : MathMax(0, i - SwingLength + 1));
         int j = ArrayMaximum(h, s0, i - s0 + 1);
         BufMS[a] = h[j];
         BufSS[a] = (zS.hasHi ? zS.hiPx : h[j]);
         if(ShowMajor)
           {
            DrawMajor(false, j, h[j], a, time, h, l, c);
            DoAlert(5, "SELL (major swing high)", h[j], time[a], live);
           }
         m_bias = -1; m_legBar = j; m_legPx = h[j]; m_runB = 0; m_runS = 0;
         NewLeg(i, h, l);
         return;
        }
     }
   // ---- EARLY entry against the major leg (one candle after the internal break)
   if(MaxEarlyTries <= 0 || e_alive || e_tries >= MaxEarlyTries)
      return;
   if(m_bias < 0 && zE.hasHi)
     {
      if(zE.hiBar > m_legBar && e_extBar > zE.hiBar && (m_legPx - e_extPx) >= g_MinLegForEarly && cc > zE.hiPx)
        {
         BufEB[a] = e_extPx; BufSB[a] = e_extPx;
         e_alive = true; e_stop = e_extPx; e_tries++;
         if(ShowEarly)
           {
            DrawEarly(true, a, e_extPx, time, h, l, c);
            DoAlert(6, "EARLY BUY (leg low)", e_extPx, time[a], live);
           }
        }
     }
   else if(m_bias > 0 && zE.hasLo)
     {
      if(zE.loBar > m_legBar && e_extBar > zE.loBar && (e_extPx - m_legPx) >= g_MinLegForEarly && cc < zE.loPx)
        {
         BufES[a] = e_extPx; BufSS[a] = e_extPx;
         e_alive = true; e_stop = e_extPx; e_tries++;
         if(ShowEarly)
           {
            DrawEarly(false, a, e_extPx, time, h, l, c);
            DoAlert(7, "EARLY SELL (leg high)", e_extPx, time[a], live);
           }
        }
     }
  }

// a new major leg starts: its extreme restarts from the new major swing point
void NewLeg(int i, const double &h[], const double &l[])
  {
   int k;
   if(m_bias > 0) { k = ArrayMaximum(h, m_legBar, i - m_legBar + 1); e_extPx = h[k]; }
   else           { k = ArrayMinimum(l, m_legBar, i - m_legBar + 1); e_extPx = l[k]; }
   e_extBar = k;
   e_alive = false; e_tries = 0;
  }

void ZZReset(ZZ &z)
  {
   z.dir = 0; z.hp = 0; z.hb = 0; z.lp = 0; z.lb = 0;
   z.hasHi = false; z.hiPx = 0; z.hiBar = 0; z.hasLo = false; z.loPx = 0; z.loBar = 0;
  }

void ZZStep(ZZ &z, int i, double hh, double ll, double dev)
  {
   if(i == 0) { z.hp = hh; z.hb = 0; z.lp = ll; z.lb = 0; }
   if(z.dir >= 0 && hh > z.hp) { z.hp = hh; z.hb = i; }
   if(z.dir <= 0 && ll < z.lp) { z.lp = ll; z.lb = i; }
   if(z.dir == 0)
     {
      if(z.hp - ll >= dev && z.hb < i)      { z.hasHi = true; z.hiPx = z.hp; z.hiBar = z.hb; z.dir = -1; z.lp = ll; z.lb = i; }
      else if(hh - z.lp >= dev && z.lb < i) { z.hasLo = true; z.loPx = z.lp; z.loBar = z.lb; z.dir = 1;  z.hp = hh; z.hb = i; }
     }
   else if(z.dir == 1)
     {
      if(z.hp - ll >= dev && z.hb < i)      { z.hasHi = true; z.hiPx = z.hp; z.hiBar = z.hb; z.dir = -1; z.lp = ll; z.lb = i; }
     }
   else
     {
      if(hh - z.lp >= dev && z.lb < i)      { z.hasLo = true; z.loPx = z.lp; z.loBar = z.lb; z.dir = 1;  z.hp = hh; z.hb = i; }
     }
  }

void DrawEarly(bool buy, int a, double px, const datetime &time[], const double &high[], const double &low[], const double &close[])
  {
   color c = buy ? ColorSwingL : ColorSwingH;
   string id = g_pfx + "e" + IntegerToString(e_count++);
   int b0 = MathMax(0, a - 30);
   double rng = high[ArrayMaximum(high, b0, a - b0 + 1)] - low[ArrayMinimum(low, b0, a - b0 + 1)];
   double y = buy ? low[a] : high[a];
   Mark(id + "_ar", time[a], y, buy ? 233 : 234, c, buy ? ANCHOR_TOP : ANCHOR_BOTTOM, 2);
   if(ShowSignalLabels)
      Txt(id + "_lb", time[a], buy ? y - rng * 0.35 : y + rng * 0.35,
          StringFormat("early %s %s (stop %s)", buy ? "BUY" : "SELL", DoubleToString(close[a - 1], _Digits), DoubleToString(px, _Digits)),
          c, buy ? ANCHOR_LEFT_UPPER : ANCHOR_LEFT_LOWER);
  }

void AddHi() { ArrayResize(ph_bar, ph_n + 1, 1024); ArrayResize(ph_px, ph_n + 1, 1024); ph_bar[ph_n] = z_hiBar; ph_px[ph_n] = z_hiPx; ph_n++; }
void AddLo() { ArrayResize(pl_bar, pl_n + 1, 1024); ArrayResize(pl_px, pl_n + 1, 1024); pl_bar[pl_n] = z_loBar; pl_px[pl_n] = z_loPx; pl_n++; }

//+------------------------------------------------------------------+
//| Original (benchmark): decided on closed candle i, stamped on i+1 |
//+------------------------------------------------------------------+
void ProcessOriginal(int i, const double &h[], const double &l[], int rates_total, const datetime &time[])
  {
   if(i < SwingLength - 1)
      return;
   int prev = g_trend;
   double up = HighestH(h, i), lo = LowestL(l, i);
   if(h[i] == up) g_trend = 1;
   if(l[i] == lo) g_trend = 0;
   if(prev < 0 || g_trend == prev)
      return;
   int a = i + 1;
   bool live = (a == rates_total - 1);
   if(g_trend == 1)
     {
      BufOB[a] = lo;
      if(ShowOriginal) DoAlert(0, "BUY (original Swing L)", lo, time[a], live);
     }
   else
     {
      BufOS[a] = up;
      if(ShowOriginal) DoAlert(1, "SELL (original Swing H)", up, time[a], live);
     }
  }

//+------------------------------------------------------------------+
//| Fast (benchmark)                                                 |
//+------------------------------------------------------------------+
void ProcessFast(int i, const double &h[], const double &l[], const double &c[], int rates_total, const datetime &time[])
  {
   if(i < SwingLength)
      return;
   for(int d = 0; d < 2; d++)
     {
      bool trig;
      if(d == 0)
         trig = (l[i - 1] == LowestL(l, i - 1) && l[i] > LowestL(l, i));
      else
         trig = (h[i - 1] == HighestH(h, i - 1) && h[i] < HighestH(h, i));
      if(trig)
        {
         g_candBar[d] = i - 1;
         g_candPx[d] = (d == 0 ? l[i - 1] : h[i - 1]);
        }
      if(g_candBar[d] < 0)
         continue;
      double cp = g_candPx[d];
      if((d == 0 && l[i] < cp) || (d == 1 && h[i] > cp))
        {
         g_candBar[d] = -1;
         continue;
        }
      if(UseLightConfirm)
        {
         if(i - ConfirmCandles < 0) continue;
         bool ok;
         if(d == 0) ok = (c[i] > h[ArrayMaximum(h, i - ConfirmCandles, ConfirmCandles)]);
         else       ok = (c[i] < l[ArrayMinimum(l, i - ConfirmCandles, ConfirmCandles)]);
         if(!ok) continue;
        }
      if(!g_armedFlag[d] && (StrictAlternation || UseReArm))
        {
         bool far = false;
         if(!StrictAlternation)
            far = (d == 0 ? cp <= g_lastPx[d] - g_ReArmDistance : cp >= g_lastPx[d] + g_ReArmDistance);
         if(!far)
           {
            g_candBar[d] = -1;
            continue;
           }
        }
      int a = i + 1;
      bool live = (a == rates_total - 1);
      if(d == 0)
        {
         BufFB[a] = cp;
         if(ShowFast) DoAlert(2, "BUY (fast)", cp, time[a], live);
        }
      else
        {
         BufFS[a] = cp;
         if(ShowFast) DoAlert(3, "SELL (fast)", cp, time[a], live);
        }
      g_armedFlag[d] = false;
      g_lastPx[d] = cp;
      g_candBar[d] = -1;
      g_armedFlag[1 - d] = true;
     }
  }

//+------------------------------------------------------------------+
int OnCalculate(const int rates_total, const int prev_calculated,
                const datetime &time[], const double &open[], const double &high[],
                const double &low[], const double &close[], const long &tick_volume[],
                const long &volume[], const int &spread[])
  {
   ArraySetAsSeries(time, false); ArraySetAsSeries(high, false);
   ArraySetAsSeries(low, false);  ArraySetAsSeries(close, false);
   ArraySetAsSeries(BufOB, false); ArraySetAsSeries(BufOS, false);
   ArraySetAsSeries(BufFB, false); ArraySetAsSeries(BufFS, false);
   ArraySetAsSeries(BufMB, false); ArraySetAsSeries(BufMS, false);
   ArraySetAsSeries(BufEB, false); ArraySetAsSeries(BufES, false);
   ArraySetAsSeries(BufSB, false); ArraySetAsSeries(BufSS, false);

   if(rates_total < SwingLength + 2)
      return(0);

   int first = prev_calculated;
   if(prev_calculated <= 0 || g_next > rates_total ||
      (g_next > 0 && g_next - 1 < rates_total && time[g_next - 1] != g_nextTime))
     {
      ResetState();
      first = 0;
     }
   for(int b = (first > 0 ? first - 1 : 0); b < rates_total; b++)
     {
      if(b >= g_next + 1 || first == 0)
        {
         BufOB[b] = EMPTY_VALUE; BufOS[b] = EMPTY_VALUE;
         BufFB[b] = EMPTY_VALUE; BufFS[b] = EMPTY_VALUE;
         BufMB[b] = EMPTY_VALUE; BufMS[b] = EMPTY_VALUE;
         BufEB[b] = EMPTY_VALUE; BufES[b] = EMPTY_VALUE;
         BufSB[b] = EMPTY_VALUE; BufSS[b] = EMPTY_VALUE;
        }
     }
   for(int i = g_next; i <= rates_total - 2; i++)
     {
      ProcessMajor(i, high, low, close, rates_total, time);
      ProcessOriginal(i, high, low, rates_total, time);
      ProcessFast(i, high, low, close, rates_total, time);
      g_next = i + 1;
      g_nextTime = time[i];
     }
   if(ShowMajor)
      RefreshLive(rates_total, time, high, low);
   return(rates_total);
  }
//+------------------------------------------------------------------+
