//+------------------------------------------------------------------+
//|                                  SemiHFT_GridBot_Unlock.mq4      |
//|  Reverse-engineered from a "Semi HFT Algo Trading bot" screen   |
//|  recording + annotated screenshots (NAS100 M1, then re-tuned    |
//|  live on XAUUSD).                                                |
//|                                                                  |
//|  STATE MACHINE:                                                  |
//|  PHASE 1 - SEED (flat): 3 pending levels each side, symmetric:  |
//|      Level1 (nearest)  lot = SeedLotNear                        |
//|      Level2/3          lot = SeedLotFar                         |
//|  PHASE 2 - BUMP: once one side's Level1 fills, the OPPOSITE     |
//|      side's Level2 pending lot is raised to RecoveryBumpLot.    |
//|  PHASE 3 - MARTINGALE: once either side reaches 2 fills, BOTH   |
//|      sides switch every still-pending level (2..5) to a         |
//|      doubling sequence off RecoveryBumpLot (x1,x2,x4,x8), and   |
//|      levels 4-5 are added. Already-filled levels are untouched. |
//|  BASKET TP/SL: floating P/L of everything this cycle is         |
//|      watched; hitting BasketTP_USD closes & cancels everything  |
//|      and a fresh SEED grid re-arms next tick.                   |
//|                                                                  |
//|  MULTI-SYMBOL SUPPORT (this revision):                          |
//|  NAS100/US100 (index CFDs) commonly have a much larger broker   |
//|  "stop level" (minimum distance for a pending order from        |
//|  price) than XAUUSD, and a different POINT size, so one set of  |
//|  lot/step inputs tuned for gold can silently fail to place any  |
//|  orders at all on an index. This version:                       |
//|    - keeps SEPARATE input blocks for XAUUSD and for NAS100/     |
//|      US100, auto-selected from the chart's symbol name (or      |
//|      forced via SymbolProfile),                                 |
//|    - widens the grid step automatically if it's narrower than   |
//|      the broker's MODE_STOPLEVEL for the current symbol, and    |
//|    - logs every failed OrderSend/OrderDelete/OrderClose with    |
//|      GetLastError() so a silent failure shows up in the Experts |
//|      log instead of just doing nothing.                         |
//|                                                                  |
//|  RISK WARNING: two-sided martingale grid, no built-in per-trade |
//|  stop loss. BasketSL_USD is OFF by default -- enable it and     |
//|  test on demo before running live, on either symbol.            |
//|                                                                  |
//|  MODIFICATIONS to the published source (strategy unchanged):     |
//|    0. TargetLot() extracted from ArmSeedGrid/ReconcileGrid; the  |
//|       SelfCheck() in OnInit asserts it, init fails on mismatch.  |
//|    1. Levels are identified by magic number (MagicNumber + 10/20 |
//|       + level), not by order comment. Start the EA flat.         |
//|    2. Basket close retries until flat (g_closing, RefreshRates)  |
//|       and never seeds a new grid over leftover orders.           |
//|    3. A pending level is re-placed only if its delete succeeded. |
//|    4. The base price is kept in a terminal global variable and   |
//|       used on restart instead of L1's open price.                |
//|                                                                  |
//|  UNLOCK VARIANT (this file), based on the replica above and on   |
//|  the original by Wasim (mql5.com/en/code/77546):                 |
//|    - Step sized per cycle: max(profile step, StepSpreadMult x    |
//|      spread, StepATRMult x ATR), frozen until the basket closes. |
//|      The basket target scales with it.                           |
//|    - Lock (levels 1..5 filled on both sides): one market order   |
//|      makes buy lots and sell lots exactly equal.                 |
//|    - Trend unlock: pending levels 6..9 on both sides, constant   |
//|      lot, widening gaps; the next pair is armed only after the   |
//|      previous pair has filled on both sides.                     |
//|    - After MaxUnlockAttempts pairs: stop adding, hold the flat   |
//|      book and raise Alert(). There is still no stop loss.        |
//|    - Optional seeding window: SeedStartHour/SeedEndHour (server  |
//|      time) limit when a NEW grid is seeded.                      |
//|    - Optional CloseOnLock: on lock the whole basket is closed at |
//|      once and a new grid is seeded (this is a structural stop).  |
//+------------------------------------------------------------------+
#property copyright "Wasim"
#property strict

//--------------------------- SYMBOL PROFILE ---------------------------
enum ENUM_PROFILE { PROFILE_AUTO, PROFILE_XAUUSD, PROFILE_NAS100 };
input ENUM_PROFILE SymbolProfile   = PROFILE_AUTO;  // AUTO detects from chart symbol name

//--------------------------- XAUUSD SETTINGS ---------------------------
input string   ____Metals____      = "===== XAUUSD / metals =====";
input double   Metals_SeedLotNear     = 0.02;
input double   Metals_SeedLotFar      = 0.01;
input double   Metals_RecoveryBumpLot = 0.05;
input int      Metals_GridStepPoints  = 50;    // 50pt * 0.01 point = $0.50 spacing
input int      Metals_MaxSpreadPoints = 40;

//--------------------------- NAS100 / US100 SETTINGS --------------------
input string   ____Index____       = "===== NAS100 / US100 =====";
input double   Index_SeedLotNear      = 0.20;
input double   Index_SeedLotFar       = 0.10;
input double   Index_RecoveryBumpLot  = 0.50;
input int      Index_GridStepPoints   = 50;    // re-check against your broker's index POINT size
input int      Index_MaxSpreadPoints  = 150;   // indices typically quote wider spreads in points

//--------------------------- SHARED SETTINGS ---------------------------
input string   ____Shared____      = "===== Shared =====";
input int      MagicNumber         = 990111;
input double   MartingaleMultiplier= 2.0;      // Doubling factor once martingale phase activates
input double   BasketTP_USD        = 2.00;     // Close everything when basket floating profit >= this
input double   BasketSL_USD        = 0;        // 0 = disabled. Emergency close if floating loss <= -this
input int      Slippage            = 5;
input bool     LogOrderErrors      = true;     // Print GetLastError() detail on any failed order

//--------------------------- UNLOCK VARIANT SETTINGS -------------------
input string   ____Unlock____      = "===== Step sizing / trend unlock =====";
input double   StepSpreadMult      = 2.0;      // Step >= this x spread at seed. 0 = off
input double   StepATRMult         = 0.0;      // Step >= this x ATR(M1). 0 = off
input int      StepATRPeriod       = 60;       // ATR period, M1 bars
input double   UnlockLot           = 0.0;      // Unlock leg lot. 0 = same as the level-5 lot
input double   UnlockDistanceSteps = 1.0;      // Gap from level 5 to first unlock level, in steps
input double   UnlockWiden         = 1.5;      // Each later unlock gap = previous x this
input int      MaxUnlockAttempts   = 4;        // Unlock pairs per basket, 0..4. 0 = off
input int      SeedStartHour       = 0;        // Seed new grids from this server hour (0..23)
input int      SeedEndHour         = 24;       // ...up to this server hour, exclusive (1..24). Start 0, end 24 = always
input bool     CloseOnLock         = false;    // Close the whole basket when all 5 levels are filled on both sides

#define MAXLEV 5
#define UNLOCK_MAX 4
#define RETRY_SECONDS 60   // pause after a rejected order before sending another

//--------------------------- GLOBALS ---------------------------------
double point;
int    digits;
double g_basePrice     = 0;
bool   g_gridActive    = false;
bool   g_closing       = false;   // basket close in progress: retry until flat

double g_SeedLotNear, g_SeedLotFar, g_RecoveryBumpLot;
int    g_GridStepPoints, g_MaxSpreadPoints;

int    g_cycleStepPoints = 0;     // step frozen for the current basket
int    g_maxUnlock       = 0;     // MaxUnlockAttempts clamped to 0..UNLOCK_MAX
int    g_lockStage       = -1;    // unlock pairs armed for this basket, -1 = not locked
bool   g_holdAlerted     = false; // hold alert already raised for this basket
datetime g_retryAfter    = 0;     // no new order is sent before this time

//+------------------------------------------------------------------+
int OnInit()
  {
   point  = MarketInfo(Symbol(), MODE_POINT);
   digits = (int)MarketInfo(Symbol(), MODE_DIGITS);

   ApplyProfile();
   g_maxUnlock       = (int)MathMax(0, MathMin(UNLOCK_MAX, MaxUnlockAttempts));
   g_cycleStepPoints = g_GridStepPoints;
   if(!SelfCheck()) return(INIT_FAILED);

   if(CountOurOrders() > 0)
     {
      g_gridActive = true;
      if(GlobalVariableCheck(StepGVName())) g_cycleStepPoints = (int)GlobalVariableGet(StepGVName());
      g_basePrice  = GlobalVariableCheck(BaseGVName()) ? GlobalVariableGet(BaseGVName()) : RecoverBasePrice();
     }
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Pick XAUUSD vs NAS100/US100 settings, by name or by forced input |
//+------------------------------------------------------------------+
void ApplyProfile()
  {
   ENUM_PROFILE p = SymbolProfile;

   if(p == PROFILE_AUTO)
     {
      string s = Symbol();
      StringToUpper(s);
      if(StringFind(s, "XAU") >= 0)
         p = PROFILE_XAUUSD;
      else if(StringFind(s, "100") >= 0 || StringFind(s, "NAS") >= 0 ||
              StringFind(s, "USTEC") >= 0 || StringFind(s, "NDX") >= 0)
         p = PROFILE_NAS100;
      else
         p = PROFILE_XAUUSD; // fallback
     }

   if(p == PROFILE_NAS100)
     {
      g_SeedLotNear     = Index_SeedLotNear;
      g_SeedLotFar      = Index_SeedLotFar;
      g_RecoveryBumpLot = Index_RecoveryBumpLot;
      g_GridStepPoints  = Index_GridStepPoints;
      g_MaxSpreadPoints = Index_MaxSpreadPoints;
      Print("SemiHFT_GridBot: using NAS100/US100 profile for symbol ", Symbol());
     }
   else
     {
      g_SeedLotNear     = Metals_SeedLotNear;
      g_SeedLotFar      = Metals_SeedLotFar;
      g_RecoveryBumpLot = Metals_RecoveryBumpLot;
      g_GridStepPoints  = Metals_GridStepPoints;
      g_MaxSpreadPoints = Metals_MaxSpreadPoints;
      Print("SemiHFT_GridBot: using XAUUSD/metals profile for symbol ", Symbol());
     }

   // Respect the broker's minimum pending-order distance for THIS symbol.
   // Indices commonly need a much bigger stop level than metals -- if our
   // configured step is narrower than that, every OrderSend would just
   // fail silently, which is the classic "EA does nothing on NAS100" bug.
   int stopLevel = (int)MarketInfo(Symbol(), MODE_STOPLEVEL);
   int freezeLevel = (int)MarketInfo(Symbol(), MODE_FREEZELEVEL);
   int minRequired = (int)MathMax(stopLevel, freezeLevel) + 5; // +5pt safety buffer
   if(g_GridStepPoints < minRequired)
     {
      Print("SemiHFT_GridBot: GridStepPoints ", g_GridStepPoints,
            " is tighter than broker stop/freeze level for ", Symbol(),
            " (needs >= ", minRequired, "). Widening automatically.");
      g_GridStepPoints = minRequired;
     }
  }

//+------------------------------------------------------------------+
//| Lot for one level; single rule shared by seed and reconcile      |
//+------------------------------------------------------------------+
double TargetLot(int lvl, bool martingale, int fillsOtherSide)
  {
   if(lvl > MAXLEV) return(UnlockLot > 0 ? UnlockLot : g_RecoveryBumpLot * MathPow(MartingaleMultiplier, MAXLEV - 2));
   if(lvl == 1) return(g_SeedLotNear);
   if(martingale) return(g_RecoveryBumpLot * MathPow(MartingaleMultiplier, lvl - 2));
   if(lvl == 2 && fillsOtherSide >= 1) return(g_RecoveryBumpLot);
   return(g_SeedLotFar);
  }

//+------------------------------------------------------------------+
//| Self-check of TargetLot, called once from OnInit                 |
//+------------------------------------------------------------------+
bool SelfCheck()
  {
   double m = MartingaleMultiplier;
   bool ok = TargetLot(1, false, 0) == g_SeedLotNear
          && TargetLot(2, false, 0) == g_SeedLotFar
          && TargetLot(3, false, 1) == g_SeedLotFar
          && TargetLot(2, false, 1) == g_RecoveryBumpLot
          && TargetLot(1, true, 1)  == g_SeedLotNear
          && TargetLot(2, true, 0)  == g_RecoveryBumpLot
          && MathAbs(TargetLot(5, true, 0) - g_RecoveryBumpLot * m * m * m) < 1e-9;
   double u = UnlockLot > 0 ? UnlockLot : g_RecoveryBumpLot * m * m * m;
   ok = ok && MathAbs(TargetLot(6, true, 0) - u) < 1e-9
           && MathAbs(TargetLot(9, false, 0) - u) < 1e-9;
   ok = ok && LevelOffset(5) == 5
           && MathAbs(LevelOffset(6) - (5 + UnlockDistanceSteps)) < 1e-9
           && MathAbs(LevelOffset(7) - (LevelOffset(6) + UnlockDistanceSteps * UnlockWiden)) < 1e-9;
   for(int n = 2; n <= MAXLEV + UNLOCK_MAX; n++) ok = ok && LevelOffset(n) > LevelOffset(n - 1);
   ok = ok && SeedStartHour >= 0 && SeedStartHour <= 23 && SeedEndHour >= 1 && SeedEndHour <= 24 && SeedStartHour != SeedEndHour
           && InSeedWindow(0, 0, 24) && InSeedWindow(23, 0, 24)
           && InSeedWindow(7, 0, 8) && !InSeedWindow(8, 0, 8)
           && InSeedWindow(23, 22, 6) && InSeedWindow(5, 22, 6) && !InSeedWindow(6, 22, 6) && !InSeedWindow(12, 22, 6);
   if(!ok) Print("SemiHFT_GridBot: self-check FAILED (lot rule, unlock geometry or seed hours inputs)");
   return(ok);
  }

//+------------------------------------------------------------------+
void OnTick()
  {
   if(g_closing) CloseBasket(); else ManageBasket();
   if(g_closing) return;   // leftovers remain: retry next tick, never seed over them

   if(!g_gridActive)
      ArmSeedGrid();
   else
      ReconcileGrid();
  }

//+------------------------------------------------------------------+
string LevelTag(bool isBuy, int lvl)
  {
   return (isBuy ? "B" : "S") + IntegerToString(lvl);
  }

//+------------------------------------------------------------------+
//| Level identity: each level has its own magic number, so it does  |
//| not depend on the broker preserving the order comment            |
//+------------------------------------------------------------------+
int LevelMagic(bool isBuy, int lvl)
  {
   return(MagicNumber + (isBuy ? 10 : 20) + lvl);
  }

//+------------------------------------------------------------------+
//| Distance of a level from the base price, in steps. Levels 1..5   |
//| are 1..5 steps out; unlock levels 6..9 follow the widening gaps  |
//+------------------------------------------------------------------+
double LevelOffset(int lvl)
  {
   if(lvl <= MAXLEV) return(lvl);
   double off = MAXLEV, gap = UnlockDistanceSteps;
   for(int n = MAXLEV + 1; n <= lvl; n++) { off += gap; gap *= UnlockWiden; }
   return(off);
  }

//+------------------------------------------------------------------+
//| Price of a level for the current basket (uses the frozen step)   |
//+------------------------------------------------------------------+
double LevelPrice(bool isBuy, int lvl)
  {
   return(NormalizeDouble(g_basePrice + (isBuy ? 1 : -1) * LevelOffset(lvl) * g_cycleStepPoints * point, digits));
  }

//+------------------------------------------------------------------+
//| Seeding window: may a new grid be seeded at this server hour     |
//+------------------------------------------------------------------+
// True if server hour h is inside the seeding window [startH, endH).
// startH > endH means the window wraps past midnight (e.g. 22 -> 6).
bool InSeedWindow(int h, int startH, int endH)
  {
   if(startH <= endH) return(h >= startH && h < endH);
   return(h >= startH || h < endH);
  }

//+------------------------------------------------------------------+
//| True if the selected order is ours. Call after OrderSelect       |
//+------------------------------------------------------------------+
bool IsOurs()
  {
   if(OrderSymbol() != Symbol()) return(false);
   int d = OrderMagicNumber() - MagicNumber;
   return(d >= 10 && d <= 29);   // buy levels 0..9 = 10..19, sell levels 0..9 = 20..29
  }

//+------------------------------------------------------------------+
int GetLevelInfo(bool isBuy, int lvl, int &ticket, double &lot)
  {
   for(int i = 0; i < OrdersTotal(); i++)
     {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if(!IsOurs()) continue;
      if(OrderMagicNumber() != LevelMagic(isBuy, lvl)) continue;

      ticket = OrderTicket();
      lot    = OrderLots();
      int t  = OrderType();
      if(t == OP_BUY || t == OP_SELL) return(2);
      if(t == OP_BUYSTOP || t == OP_SELLSTOP) return(1);
     }
   return(0);
  }

//+------------------------------------------------------------------+
int CountOurOrders()
  {
   int cnt = 0;
   for(int i = 0; i < OrdersTotal(); i++)
     {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if(!IsOurs()) continue;
      cnt++;
     }
   return cnt;
  }

//+------------------------------------------------------------------+
//| Terminal global variable that holds the grid base price          |
//+------------------------------------------------------------------+
string BaseGVName()
  {
   return("SHFT_" + Symbol() + "_" + IntegerToString(MagicNumber) + "_base");
  }

//+------------------------------------------------------------------+
//| Terminal global variable that holds the step of the open basket  |
//+------------------------------------------------------------------+
string StepGVName()
  {
   return("SHFT_" + Symbol() + "_" + IntegerToString(MagicNumber) + "_step");
  }

//+------------------------------------------------------------------+
double RecoverBasePrice()
  {
   for(int i = 0; i < OrdersTotal(); i++)
     {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if(!IsOurs()) continue;
      if(OrderMagicNumber() == LevelMagic(true, 1)) return(OrderOpenPrice() - g_cycleStepPoints * point);
      if(OrderMagicNumber() == LevelMagic(false, 1)) return(OrderOpenPrice() + g_cycleStepPoints * point);
     }
   return((Bid + Ask) / 2.0);
  }

//+------------------------------------------------------------------+
double BasketFloatingProfit()
  {
   double total = 0;
   for(int i = 0; i < OrdersTotal(); i++)
     {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if(!IsOurs()) continue;
      if(OrderType() == OP_BUY || OrderType() == OP_SELL)
         total += OrderProfit() + OrderSwap() + OrderCommission();
     }
   return total;
  }

//+------------------------------------------------------------------+
void CloseBasket()
  {
   g_closing = true;
   for(int i = OrdersTotal() - 1; i >= 0; i--)
     {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if(!IsOurs()) continue;

      RefreshRates();
      int type = OrderType();
      bool ok;
      if(type == OP_BUY)
         ok = OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, clrRed);
      else if(type == OP_SELL)
         ok = OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, clrRed);
      else
         ok = OrderDelete(OrderTicket());

      if(!ok) LogOrderError("CloseBasket", OrderTicket());
     }
   if(CountOurOrders() == 0) { g_closing = false; g_gridActive = false; }
  }

//+------------------------------------------------------------------+
void ManageBasket()
  {
   if(CountOurOrders() == 0) { g_gridActive = false; return; }

   double pl = BasketFloatingProfit();

   double tp = BasketTP_USD * g_cycleStepPoints / g_GridStepPoints;   // target scales with the cycle's step
   if(BasketTP_USD > 0 && pl >= tp)
     {
      Print("Basket TP hit: ", pl, " -> closing all & starting again");
      CloseBasket();
      return;
     }
   if(BasketSL_USD > 0 && pl <= -MathAbs(BasketSL_USD))
     {
      Print("Basket SL hit: ", pl, " -> closing all (safety stop)");
      CloseBasket();
      return;
     }
  }

//+------------------------------------------------------------------+
double NormalizeLot(double lots)
  {
   double lotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
   double minLot   = MarketInfo(Symbol(), MODE_MINLOT);
   double maxLot   = MarketInfo(Symbol(), MODE_MAXLOT);
   lots = MathRound(lots / lotStep) * lotStep;
   if(lots < minLot) lots = minLot;
   if(lots > maxLot) lots = maxLot;
   return(NormalizeDouble(lots, 2));
  }

//+------------------------------------------------------------------+
void LogOrderError(string context, int ticketOrZero)
  {
   if(!LogOrderErrors) return;
   Print("SemiHFT_GridBot ERROR in ", context, " ticket=", ticketOrZero,
         " err=", GetLastError(), " (", Symbol(), ")");
  }

//+------------------------------------------------------------------+
//| A rejected OrderSend: log it and pause new orders, so a rejection |
//| (for example not enough margin) is not repeated on every tick    |
//+------------------------------------------------------------------+
void SendFailed(string context)
  {
   LogOrderError(context, 0);
   g_retryAfter = TimeCurrent() + RETRY_SECONDS;
  }

//+------------------------------------------------------------------+
//| Place (or resize) a level. If the market has already passed the  |
//| intended stop price -- common on fast-moving indices like USTEC  |
//| when several ticks/levels get skipped between reconcile calls -- |
//| a Buy/Sell Stop there would be rejected with error 130 forever.  |
//| In that case, fill it at market instead: the level's condition   |
//| ("price traded through here") has effectively already been met.  |
//+------------------------------------------------------------------+
void SafePlaceLevel(bool isBuy, int lvl, double lot, double price, string context)
  {
   if(TimeCurrent() < g_retryAfter) return;

   int stopLevel = (int)MarketInfo(Symbol(), MODE_STOPLEVEL);
   double buffer = MathMax(stopLevel, 1) * point;

   bool passed;
   if(isBuy)
      passed = (price <= Ask + buffer);   // Buy Stop must sit above Ask
   else
      passed = (price >= Bid - buffer);   // Sell Stop must sit below Bid

   int t;
   if(!passed)
     {
      int ordType = isBuy ? OP_BUYSTOP : OP_SELLSTOP;
      t = OrderSend(Symbol(), ordType, lot, price, Slippage, 0, 0,
                    LevelTag(isBuy, lvl), LevelMagic(isBuy, lvl), 0, isBuy ? clrBlue : clrRed);
      if(t < 0) SendFailed(context + " (stop) " + LevelTag(isBuy, lvl));
     }
   else
     {
      // Level already breached by price movement -> treat as triggered, fill at market
      double execPrice = isBuy ? Ask : Bid;
      int ordType = isBuy ? OP_BUY : OP_SELL;
      t = OrderSend(Symbol(), ordType, lot, execPrice, Slippage, 0, 0,
                    LevelTag(isBuy, lvl), LevelMagic(isBuy, lvl), 0, isBuy ? clrBlue : clrRed);
      if(t < 0)
         SendFailed(context + " (market fallback) " + LevelTag(isBuy, lvl));
      else
         Print("SemiHFT_GridBot: ", LevelTag(isBuy, lvl), " target ", price,
               " already passed by price -> filled at market ", execPrice, " instead");
     }
  }

//+------------------------------------------------------------------+
//| PHASE 1: flat -> lay the symmetric seed ladder                   |
//+------------------------------------------------------------------+
void ArmSeedGrid()
  {
   if(!InSeedWindow(TimeHour(TimeCurrent()), SeedStartHour, SeedEndHour)) return;
   double spread = (Ask - Bid) / point;
   if(spread > g_MaxSpreadPoints) return;

   g_cycleStepPoints = g_GridStepPoints;
   if(StepSpreadMult > 0)
      g_cycleStepPoints = (int)MathMax(g_cycleStepPoints, MathCeil(StepSpreadMult * MathRound(spread)));
   if(StepATRMult > 0)
      g_cycleStepPoints = (int)MathMax(g_cycleStepPoints, MathCeil(StepATRMult * iATR(Symbol(), PERIOD_M1, StepATRPeriod, 1) / point));
   GlobalVariableSet(StepGVName(), g_cycleStepPoints);
   g_lockStage   = -1;
   g_holdAlerted = false;
   Comment("");

   g_basePrice = (Bid + Ask) / 2.0;
   GlobalVariableSet(BaseGVName(), g_basePrice);

   for(int lvl = 1; lvl <= 3; lvl++)
     {
      double lot = TargetLot(lvl, false, 0);

      double buyPrice = LevelPrice(true, lvl);
      SafePlaceLevel(true, lvl, NormalizeLot(lot), buyPrice, "ArmSeedGrid");

      double sellPrice = LevelPrice(false, lvl);
      SafePlaceLevel(false, lvl, NormalizeLot(lot), sellPrice, "ArmSeedGrid");
     }

   g_gridActive = true;
  }

//+------------------------------------------------------------------+
//| Place or resize one level (shared by the ladder and unlock legs) |
//+------------------------------------------------------------------+
void EnsureLevel(bool isBuy, int lvl, double targetLot)
  {
   int ticket; double lot;
   int status = GetLevelInfo(isBuy, lvl, ticket, lot);
   if(status == 2) return;

   double price = LevelPrice(isBuy, lvl);
   if(status == 0)
      SafePlaceLevel(isBuy, lvl, targetLot, price, "ReconcileGrid place");
   else if(MathAbs(lot - targetLot) > 0.0000001)
     {
      if(OrderDelete(ticket))
         SafePlaceLevel(isBuy, lvl, targetLot, price, "ReconcileGrid replace");
      else
         LogOrderError("ReconcileGrid delete " + LevelTag(isBuy, lvl), ticket);
     }
  }

//+------------------------------------------------------------------+
//| Total filled lots of one side, all our levels including level 0  |
//+------------------------------------------------------------------+
double SideLots(bool isBuy)
  {
   double total = 0;
   for(int i = 0; i < OrdersTotal(); i++)
     {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if(!IsOurs()) continue;
      if(OrderType() == (isBuy ? OP_BUY : OP_SELL)) total += OrderLots();
     }
   return(total);
  }

//+------------------------------------------------------------------+
//| Locked book: one market order on the lighter side so buys and    |
//| sells match exactly. Retried every tick until it succeeds        |
//+------------------------------------------------------------------+
void EqualizeBook()
  {
   if(TimeCurrent() < g_retryAfter) return;

   double diff    = SideLots(true) - SideLots(false);
   double lotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
   double lots    = NormalizeDouble(MathFloor(MathAbs(diff) / lotStep + 0.000001) * lotStep, 2);
   if(lots < MarketInfo(Symbol(), MODE_MINLOT)) return;

   bool isBuy = (diff < 0);   // lighter side
   RefreshRates();
   int t = OrderSend(Symbol(), isBuy ? OP_BUY : OP_SELL, lots, isBuy ? Ask : Bid, Slippage, 0, 0,
                     LevelTag(isBuy, 0), LevelMagic(isBuy, 0), 0, isBuy ? clrBlue : clrRed);
   if(t < 0)
      SendFailed("EqualizeBook " + LevelTag(isBuy, 0));
   else
      Print("SemiHFT_GridBot: book locked, exact-flat ", LevelTag(isBuy, 0), " ", DoubleToString(lots, 2), " lots");
  }

//+------------------------------------------------------------------+
//| All unlock attempts used: stop adding, tell the human            |
//+------------------------------------------------------------------+
void HoldAlert()
  {
   g_holdAlerted = true;
   string msg = "SemiHFT_GridBot " + Symbol() + ": unlock attempts exhausted (" + IntegerToString(g_maxUnlock) +
                "), holding flat book. Buy lots " + DoubleToString(SideLots(true), 2) +
                ", sell lots " + DoubleToString(SideLots(false), 2) +
                ", floating P/L " + DoubleToString(BasketFloatingProfit(), 2) + ". Manual decision needed.";
   Alert(msg);
   Comment(msg);
  }

//+------------------------------------------------------------------+
//| PHASE 2/3: every tick, self-heal the pending ladder               |
//+------------------------------------------------------------------+
void ReconcileGrid()
  {
   int ticket; double lot;

   int buyFills = 0, sellFills = 0;
   for(int lvl = 1; lvl <= MAXLEV; lvl++)
     {
      if(GetLevelInfo(true,  lvl, ticket, lot) == 2) buyFills++;
      if(GetLevelInfo(false, lvl, ticket, lot) == 2) sellFills++;
     }

   bool martingale = (buyFills >= 2 || sellFills >= 2);
   int  maxLevelToEnsure = martingale ? MAXLEV : 3;

   for(int side = 0; side < 2; side++)
     {
      bool isBuy          = (side == 0);
      int  fillsOtherSide = isBuy ? sellFills : buyFills;

      for(int lvl = 1; lvl <= maxLevelToEnsure; lvl++)
        {
         EnsureLevel(isBuy, lvl, NormalizeLot(TargetLot(lvl, martingale, fillsOtherSide)));
        }
     }

   if(buyFills < MAXLEV || sellFills < MAXLEV) return;   // not locked

   // LOCKED: every ladder level is filled on both sides
   if(CloseOnLock)
     {
      Print("SemiHFT_GridBot: LOCK, CloseOnLock -> closing basket at floating ", DoubleToString(BasketFloatingProfit(), 2));
      CloseBasket();
      return;
     }
   int ub = 0, us = 0;   // filled unlock levels per side
   for(int n = MAXLEV + 1; n <= MAXLEV + UNLOCK_MAX; n++)
     {
      if(GetLevelInfo(true,  n, ticket, lot) == 2) ub++;
      if(GetLevelInfo(false, n, ticket, lot) == 2) us++;
     }

   if(ub == us) EqualizeBook();   // while ub != us the imbalance is the open unlock leg

   int pairs = (int)MathMin(MathMin(ub, us) + 1, g_maxUnlock);
   if(pairs != g_lockStage)
     {
      g_lockStage = pairs;
      Print("SemiHFT_GridBot: LOCK stage ", pairs, "/", g_maxUnlock, " floating ", DoubleToString(BasketFloatingProfit(), 2));
     }
   for(int k = 1; k <= pairs; k++)
     {
      EnsureLevel(true,  MAXLEV + k, NormalizeLot(TargetLot(MAXLEV + k, true, 0)));
      EnsureLevel(false, MAXLEV + k, NormalizeLot(TargetLot(MAXLEV + k, true, 0)));
     }

   if(ub == g_maxUnlock && us == g_maxUnlock && !g_holdAlerted) HoldAlert();
  }
//+------------------------------------------------------------------+
