//+------------------------------------------------------------------+
//|                                         MACD(drag_dashboard).mq5 |
//|  Multi-Symbol / Multi-Timeframe MACD Dashboard (Heatmap style)   |
//|  using Lime & Red trend/slope colors across M15, M30, H1, H4.    |
//+------------------------------------------------------------------+
#property copyright "MACD Dashboard"
#property link      "https://forex-station.com/post1295588053.html#p1295588053"
#property version   "1.00"
#property description "MACD Dashboard (M15, M30, H1, H4) - Draggable Heatmap with Current Pair Highlight"

#property indicator_chart_window
#property indicator_plots   0

//+------------------------------------------------------------------+
//| Mode Enumeration                                                 |
//+------------------------------------------------------------------+
enum enMacdMode
  {
   macd_signal = 0, // MACD Main vs Signal (OsMA)
   macd_zero   = 1  // MACD Main vs Zero
  };

//+------------------------------------------------------------------+
//| Input Parameters                                                 |
//+------------------------------------------------------------------+
input group "--- Dashboard Pairs & Timeframes ---"
input string             Symbols          = "AUDCAD;AUDCHF;AUDJPY;AUDNZD;AUDUSD;CADCHF;CADJPY;CHFJPY;EURAUD;EURCAD;EURCHF;EURGBP;EURJPY;EURNZD;EURUSD;GBPAUD;GBPCAD;GBPCHF;GBPJPY;GBPNZD;GBPUSD;NZDCAD;NZDCHF;NZDJPY;NZDUSD;USDCAD;USDCHF;USDJPY;XAUUSD;"; // Symbols (separated by ";")
input string             TimeFrames       = "M15;M30;H1;H4";        // Time frames (separated by ";")
input int                BarToTest        = 0;                      // Bar to test (0 = current bar, 1 = closed bar)
input int                InpCalcBars      = 1000;                   // History bars to calculate per symbol/TF
input bool               InpClickSwitch   = true;                   // Click cell/header to switch chart Symbol/TF

input group "--- MACD Settings ---"
input int                InpFastEMA       = 12;                     // Fast EMA Period (>= 1)
input int                InpSlowEMA       = 26;                     // Slow EMA Period (>= 1)
input int                InpSignalSMA     = 9;                      // Signal SMA Period (>= 1)
input ENUM_APPLIED_PRICE InpAppliedPrice  = PRICE_CLOSE;            // Applied Price
input enMacdMode         InpMacdMode      = macd_signal;            // Color Mode

input group "--- Color Settings (Lime & Red) ---"
input bool               InpUse4Colors    = true;                   // Use 4 colors (strong/weak)
input color              InpCandleUp      = clrLime;                // Strong Bullish (rising)
input color              InpCandleUpWeak  = C'0,145,0';             // Bullish Retracement (falling)
input color              InpCandleDn      = clrRed;                 // Strong Bearish (falling)
input color              InpCandleDnWeak  = C'155,0,0';             // Bearish Retracement (rising)
input color              InpCandleWt      = C'34,34,34';            // Neutral / Loading

input group "--- Dashboard Appearance ---"
input color              TextColor        = clrBlack;               // Color for button text
input color              BorderColor      = clrBlack;               // Color for button border
input color              FillColor        = clrSilver;              // Color for header/label background
input bool               InpHighlightCurr = true;                   // Highlight current chart symbol row
input color              CurrBgColor      = clrGold;                // Current symbol label background
input color              CurrTextColor    = clrBlack;               // Current symbol label text color
input color              CurrBorderColor  = clrGold;                // Current symbol row border color
input int                Window           = 0;                      // Window to use for display
input ENUM_BASE_CORNER   Corner           = CORNER_LEFT_LOWER;      // Corner for display
input int                XShift           = 0;                      // Horizontal shift
input int                YShift           = 0;                      // Vertical shift
input bool               InpDraggable     = true;                   // Draggable by title bar
input string             UniqueID         = "MACDDB";               // Indicator unique ID

//+------------------------------------------------------------------+
//| Global Variables                                                 |
//+------------------------------------------------------------------+
int             cpairsLen = 0;
int             ctimesLen = 0;
ENUM_TIMEFRAMES aTimes[];
string          cpairs[];
string          g_prefix  = "";
datetime        g_lastEvalBarTime[];
color           g_lastCellColor[];
bool            g_lastCellComplete[];
bool            g_warnedCell[];

//--- Dragging & hover state (article 18241 style)
int             g_panelX          = 0;
int             g_panelY          = 0;
bool            g_minimized       = false;
bool            g_panelDragging   = false;
bool            g_headerHovered   = false;
int             g_dragMouseX      = 0;
int             g_dragMouseY      = 0;
int             g_dragStartX      = 0;
int             g_dragStartY      = 0;
int             g_prevMouseState  = 0;
bool            g_origMouseScroll = true;
bool            g_mouseRefHeld    = false;
uint            g_dragOwnerId     = 0;
int             g_staleLockTicks  = 0;
ulong           g_lastTickCalcMs  = 0;

ENUM_TIMEFRAMES g_tfEnum[] =
  {
   PERIOD_M1, PERIOD_M2, PERIOD_M3, PERIOD_M4, PERIOD_M5, PERIOD_M6,
   PERIOD_M10, PERIOD_M12, PERIOD_M15, PERIOD_M20, PERIOD_M30,
   PERIOD_H1, PERIOD_H2, PERIOD_H3, PERIOD_H4, PERIOD_H6, PERIOD_H8, PERIOD_H12,
   PERIOD_D1, PERIOD_W1, PERIOD_MN1
  };
string g_tfStr[] =
  {
   "M1", "M2", "M3", "M4", "M5", "M6",
   "M10", "M12", "M15", "M20", "M30",
   "H1", "H2", "H3", "H4", "H6", "H8", "H12",
   "D1", "W1", "MN"
  };

//+------------------------------------------------------------------+
//| Timeframe string conversions                                     |
//+------------------------------------------------------------------+
ENUM_TIMEFRAMES StringToTimeFrame(string tfs)
  {
   StringTrimLeft(tfs);
   StringTrimRight(tfs);
   StringToUpper(tfs);
   if(tfs == "MN1") tfs = "MN";

   for(int i = 0; i < ArraySize(g_tfStr); i++)
     {
      if(tfs == g_tfStr[i] || tfs == IntegerToString(PeriodSeconds(g_tfEnum[i]) / 60))
         return g_tfEnum[i];
     }
   return (ENUM_TIMEFRAMES)_Period;
  }

string TimeFrameToString(const ENUM_TIMEFRAMES tf)
  {
   for(int i = 0; i < ArraySize(g_tfEnum); i++)
     {
      if(tf == g_tfEnum[i])
         return g_tfStr[i];
     }
   return StringSubstr(EnumToString(tf), 7);
  }

void InvertStringArray(string &arr[])
  {
   string temp[];
   ArrayCopy(temp, arr);
   int s = ArraySize(arr);
   for(int i = 0; i < s; i++)
      arr[i] = temp[s - i - 1];
  }

void InvertTfArray(ENUM_TIMEFRAMES &arr[])
  {
   ENUM_TIMEFRAMES temp[];
   ArrayCopy(temp, arr);
   int s = ArraySize(arr);
   for(int i = 0; i < s; i++)
      arr[i] = temp[s - i - 1];
  }

//+------------------------------------------------------------------+
//| Create or update a dashboard button cell                         |
//+------------------------------------------------------------------+
void ButtonUpsert(const string           name,
                  const int              sub_window,
                  const int              x,
                  const int              y,
                  const int              width,
                  const int              height,
                  const ENUM_BASE_CORNER corner,
                  const string           text,
                  const string           font,
                  const int              font_size,
                  const color            clr,
                  const color            clrBorder,
                  const color            back_clr,
                  const bool             pressed_state = true)
  {
   if(ObjectFind(0, name) < 0)
     {
      ObjectCreate(0, name, OBJ_BUTTON, sub_window, 0, 0);
      ObjectSetInteger(0, name, OBJPROP_BORDER_TYPE, BORDER_FLAT);
      ObjectSetInteger(0, name, OBJPROP_BACK,        false);
      ObjectSetInteger(0, name, OBJPROP_SELECTABLE,  false);
      ObjectSetInteger(0, name, OBJPROP_SELECTED,    false);
      ObjectSetInteger(0, name, OBJPROP_HIDDEN,      true);
      ObjectSetInteger(0, name, OBJPROP_ZORDER,      10);
      ObjectSetInteger(0, name, OBJPROP_TIMEFRAMES,  OBJ_ALL_PERIODS);
     }

   ObjectSetInteger(0, name, OBJPROP_CORNER,       corner);
   ObjectSetInteger(0, name, OBJPROP_XDISTANCE,    x);
   ObjectSetInteger(0, name, OBJPROP_YDISTANCE,    y);
   ObjectSetInteger(0, name, OBJPROP_XSIZE,        width);
   ObjectSetInteger(0, name, OBJPROP_YSIZE,        height);
   ObjectSetString (0, name, OBJPROP_FONT,         font);
   ObjectSetInteger(0, name, OBJPROP_FONTSIZE,     font_size);
   ObjectSetInteger(0, name, OBJPROP_COLOR,        clr);
   ObjectSetInteger(0, name, OBJPROP_BGCOLOR,      back_clr);
   ObjectSetInteger(0, name, OBJPROP_BORDER_COLOR, clrBorder);
   ObjectSetInteger(0, name, OBJPROP_STATE,        pressed_state);
   ObjectSetString (0, name, OBJPROP_TEXT,         text);
  }

//+------------------------------------------------------------------+
//| MACD Math Helpers (matches MetaQuotes Examples\MACD.mq5)         |
//+------------------------------------------------------------------+
inline double RateAppliedPrice(const MqlRates &r)
  {
   switch(InpAppliedPrice)
     {
      case PRICE_OPEN:     return r.open;
      case PRICE_HIGH:     return r.high;
      case PRICE_LOW:      return r.low;
      case PRICE_MEDIAN:   return (r.high + r.low) * 0.5;
      case PRICE_TYPICAL:  return (r.high + r.low + r.close) / 3.0;
      case PRICE_WEIGHTED: return (r.high + r.low + 2.0 * r.close) * 0.25;
      case PRICE_CLOSE:
      default:             return r.close;
     }
  }

//+------------------------------------------------------------------+
//| Compute MACD cell color for a single (symbol, timeframe)         |
//+------------------------------------------------------------------+
color EvaluateCellColor(const string sym, const ENUM_TIMEFRAMES tf, datetime &barTimeOut, bool &isCompleteOut)
  {
   barTimeOut    = 0;
   isCompleteOut = false;
   int barShift = MathMax(0, BarToTest);
   int maxPeriod = MathMax(InpFastEMA, InpSlowEMA);
   int minSpan   = maxPeriod + InpSignalSMA + 2;
   int needBars  = MathMax(InpCalcBars, minSpan * 5) + barShift + 5;

   ResetLastError();
   MqlRates rates[];
   ArraySetAsSeries(rates, false);
   int n = CopyRates(sym, tf, 0, needBars, rates);
   if(n <= 0)
     {
      int avail = iBars(sym, tf);
      if(avail > 0)
         n = CopyRates(sym, tf, 0, MathMin(needBars, avail), rates);
     }
   if(n < minSpan + barShift)
      return InpCandleWt;

   int evalIdx = n - 1 - barShift;
   if(evalIdx < InpSignalSMA)
      return InpCandleWt;

   barTimeOut    = rates[evalIdx].time;
   isCompleteOut = (n >= needBars);

   double alphaFast = 2.0 / (InpFastEMA + 1.0);
   double alphaSlow = 2.0 / (InpSlowEMA + 1.0);

   double macdBuf[];
   ArrayResize(macdBuf, evalIdx + 1);

   double fastEma = RateAppliedPrice(rates[0]);
   double slowEma = fastEma;
   macdBuf[0]     = 0.0;

   for(int i = 1; i <= evalIdx; i++)
     {
      double src = RateAppliedPrice(rates[i]);
      fastEma    = fastEma + alphaFast * (src - fastEma);
      slowEma    = slowEma + alphaSlow * (src - slowEma);
      macdBuf[i] = fastEma - slowEma;
     }

   double valCur  = macdBuf[evalIdx];
   double valPrev = macdBuf[evalIdx - 1];

   if(InpMacdMode == macd_signal)
     {
      double sumCur = 0.0, sumPrev = 0.0;
      for(int j = 0; j < InpSignalSMA; j++)
        {
         sumCur  += macdBuf[evalIdx - j];
         sumPrev += macdBuf[evalIdx - 1 - j];
        }
      double sigCur  = sumCur  / InpSignalSMA;
      double sigPrev = sumPrev / InpSignalSMA;
      valCur  = macdBuf[evalIdx]     - sigCur;
      valPrev = macdBuf[evalIdx - 1] - sigPrev;
     }

   bool rising  = (valCur > valPrev);
   bool falling = (valCur < valPrev);

   if(valCur > 0.0)
      return (InpUse4Colors && falling) ? InpCandleUpWeak : InpCandleUp;
   if(valCur < 0.0)
      return (InpUse4Colors && rising)  ? InpCandleDnWeak : InpCandleDn;

   return InpCandleWt;
  }

//+------------------------------------------------------------------+
//| Layout & Drag Helpers                                            |
//+------------------------------------------------------------------+
void GetLayoutShifts(int &xshift, int &nxshift)
  {
   bool isRight = (Corner == CORNER_RIGHT_LOWER || Corner == CORNER_RIGHT_UPPER);
   xshift  = isRight ? 49 : 0;
   nxshift = isRight ? 66 : 0;
  }

void GetHeaderDimensions(int &outTotalW, int &outTitleX, int &outTitleY, int &outTitleW,
                         int &outBtnX, int &outBtnY, int &outBtnW,
                         int &outCloseX, int &outCloseY, int &outCloseW)
  {
   bool isRight = (Corner == CORNER_RIGHT_LOWER || Corner == CORNER_RIGHT_UPPER);

   outBtnW   = 18;
   outCloseW = 18;
   int gap   = 1;
   int gridW = ctimesLen * 50 - 1;

   if(g_minimized)
     {
      outTotalW = MathMax(180, MathMin(230, gridW));
      outTitleW = outTotalW - (outBtnW + gap + outCloseW + gap);
      outTitleY = g_panelY + 15;
      outBtnY   = outTitleY;
      outCloseY = outTitleY;
      if(isRight)
        {
         outCloseX = g_panelX + 2 + outCloseW;
         outBtnX   = outCloseX + gap + outBtnW;
         outTitleX = g_panelX + 2 + outTotalW;
        }
      else
        {
         outTitleX = g_panelX + 2;
         outBtnX   = outTitleX + outTitleW + gap;
         outCloseX = outBtnX + outBtnW + gap;
        }
      return;
     }

   bool spanFull = (ctimesLen < 3);
   outTotalW = spanFull ? (66 + 1 + gridW) : gridW;
   outTitleW = outTotalW - (outBtnW + gap + outCloseW + gap);
   outTitleY = g_panelY + 30 + cpairsLen * 15;
   outBtnY   = outTitleY;
   outCloseY = outTitleY;

   if(isRight)
     {
      int baseRightOffset = spanFull ? 2 : 69;
      int baseLeftOffset  = 68 + ctimesLen * 50;
      outCloseX = g_panelX + baseRightOffset + outCloseW;
      outBtnX   = outCloseX + gap + outBtnW;
      outTitleX = g_panelX + baseLeftOffset;
     }
   else
     {
      outTitleX = spanFull ? (g_panelX + 2) : (g_panelX + 69);
      outBtnX   = outTitleX + outTitleW + gap;
      outCloseX = outBtnX + outBtnW + gap;
     }
  }

void ClampPanelPosition()
  {
   if(cpairsLen <= 0 || ctimesLen <= 0)
      return;

   int chartW = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS, Window);
   int chartH = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, Window);
   if(chartW <= 0 || chartH <= 0)
      return;

   int minTotalW        = MathMax(180, MathMin(230, ctimesLen * 50 - 1));
   int panelRightOffset = g_minimized ? (2 + minTotalW) : (68 + ctimesLen * 50);
   int minX = -2;
   int maxX = MathMax(minX, chartW - panelRightOffset);
   g_panelX = MathMax(minX, MathMin(g_panelX, maxX));

   bool isLower = (Corner == CORNER_LEFT_LOWER || Corner == CORNER_RIGHT_LOWER);
   if(isLower)
     {
      int minY = -1;
      int maxY = g_minimized
                 ? MathMax(minY, chartH - 15)
                 : MathMax(minY, chartH - (30 + cpairsLen * 15));
      g_panelY = MathMax(minY, MathMin(g_panelY, maxY));
     }
   else
     {
      int minY = -15;
      int maxY = g_minimized
                 ? MathMax(minY, chartH - 29)
                 : MathMax(minY, chartH - (44 + cpairsLen * 15));
      g_panelY = MathMax(minY, MathMin(g_panelY, maxY));
     }
  }

void RepositionDashboardObjects()
  {
   if(cpairsLen <= 0 || ctimesLen <= 0)
      return;

   int totalW = 0, titleX = 0, titleY = 0, titleW = 0;
   int btnX = 0, btnY = 0, btnW = 0;
   int closeX = 0, closeY = 0, closeW = 0;
   GetHeaderDimensions(totalW, titleX, titleY, titleW, btnX, btnY, btnW, closeX, closeY, closeW);

   string titleName = g_prefix + "title";
   if(ObjectFind(0, titleName) >= 0)
     {
      ObjectSetInteger(0, titleName, OBJPROP_XDISTANCE, titleX);
      ObjectSetInteger(0, titleName, OBJPROP_YDISTANCE, titleY);
     }

   string btnName = g_prefix + "btn_min";
   if(ObjectFind(0, btnName) >= 0)
     {
      ObjectSetInteger(0, btnName, OBJPROP_XDISTANCE, btnX);
      ObjectSetInteger(0, btnName, OBJPROP_YDISTANCE, btnY);
     }

   string closeName = g_prefix + "btn_close";
   if(ObjectFind(0, closeName) >= 0)
     {
      ObjectSetInteger(0, closeName, OBJPROP_XDISTANCE, closeX);
      ObjectSetInteger(0, closeName, OBJPROP_YDISTANCE, closeY);
     }

   if(g_minimized)
      return;

   int xshift = 0, nxshift = 0;
   GetLayoutShifts(xshift, nxshift);

   for(int i = 0; i < cpairsLen; i++)
     {
      string sName = g_prefix + "s_" + IntegerToString(i);
      ObjectSetInteger(0, sName, OBJPROP_XDISTANCE, g_panelX + nxshift + 2);
      ObjectSetInteger(0, sName, OBJPROP_YDISTANCE, g_panelY + 30 + i * 15);
     }

   for(int t = 0; t < ctimesLen; t++)
     {
      string hName = g_prefix + "h_" + IntegerToString(t);
      ObjectSetInteger(0, hName, OBJPROP_XDISTANCE, g_panelX + xshift + t * 50 + 69);
      ObjectSetInteger(0, hName, OBJPROP_YDISTANCE, g_panelY + 15);
     }

   for(int i = 0; i < cpairsLen; i++)
     {
      for(int t = 0; t < ctimesLen; t++)
        {
         string cellName = g_prefix + "c_" + IntegerToString(t) + "_" + IntegerToString(i);
         ObjectSetInteger(0, cellName, OBJPROP_XDISTANCE, g_panelX + xshift + t * 50 + 69);
         ObjectSetInteger(0, cellName, OBJPROP_YDISTANCE, g_panelY + 30 + i * 15);
        }
     }
  }

void GetHeaderScreenRect(int &left, int &top, int &right, int &bottom)
  {
   string titleName = g_prefix + "title";
   if(ObjectFind(0, titleName) < 0)
     {
      left = top = right = bottom = -1;
      return;
     }

   int xd = (int)ObjectGetInteger(0, titleName, OBJPROP_XDISTANCE);
   int yd = (int)ObjectGetInteger(0, titleName, OBJPROP_YDISTANCE);
   int w  = (int)ObjectGetInteger(0, titleName, OBJPROP_XSIZE);
   int h  = (int)ObjectGetInteger(0, titleName, OBJPROP_YSIZE);

   int chartW = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS, Window);
   int chartH = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, Window);
   bool isRight = (Corner == CORNER_RIGHT_LOWER || Corner == CORNER_RIGHT_UPPER);
   bool isLower = (Corner == CORNER_LEFT_LOWER  || Corner == CORNER_RIGHT_LOWER);

   left   = isRight ? (chartW - xd) : xd;
   right  = left + w;
   top    = isLower ? (chartH - yd) : yd;
   bottom = top + h;
  }

color AdjustShade(const color baseClr, const int delta)
  {
   int r = MathMax(0, MathMin(255, (int)(baseClr & 0x0000FF) + delta));
   int g = MathMax(0, MathMin(255, (int)((baseClr & 0x00FF00) >> 8) + delta));
   int b = MathMax(0, MathMin(255, (int)((baseClr & 0xFF0000) >> 16) + delta));
   return (color)((b << 16) | (g << 8) | r);
  }

void UpdateHeaderAppearance()
  {
   string titleName = g_prefix + "title";
   if(ObjectFind(0, titleName) < 0)
      return;

   color bg = FillColor;
   if(g_panelDragging)
      bg = AdjustShade(FillColor, 28);
   else if(g_headerHovered)
      bg = AdjustShade(FillColor, 16);

   ObjectSetInteger(0, titleName, OBJPROP_BGCOLOR, bg);
  }

string PositionGvPrefix()
  {
   return "MACDDashPos_" + IntegerToString(ChartID()) + "_" + UniqueID + "_";
  }

void SavePanelPosition()
  {
   string p = PositionGvPrefix();
   GlobalVariableSet(p + "X",      (double)g_panelX);
   GlobalVariableSet(p + "Y",      (double)g_panelY);
   GlobalVariableSet(p + "InitX",  (double)XShift);
   GlobalVariableSet(p + "InitY",  (double)YShift);
   GlobalVariableSet(p + "Corner", (double)Corner);
   GlobalVariableSet(p + "Min",    g_minimized ? 1.0 : 0.0);
  }

void ClearSavedPanelPosition()
  {
   string p = PositionGvPrefix();
   GlobalVariableDel(p + "X");
   GlobalVariableDel(p + "Y");
   GlobalVariableDel(p + "InitX");
   GlobalVariableDel(p + "InitY");
   GlobalVariableDel(p + "Corner");
   GlobalVariableDel(p + "Min");
  }

string DragLockKey()
  {
   return StringFormat("MT5_DRAG_ACTIVE_%I64d", ChartID());
  }

void AllocDragOwnerId()
  {
   string seqKey = "MT5_DRAG_OWNER_SEQ";
   uint seq = GlobalVariableCheck(seqKey) ? (uint)GlobalVariableGet(seqKey) : 100U;
   seq++;
   if(seq < 100U)
      seq = 100U;
   GlobalVariableSet(seqKey, (double)seq);
   GlobalVariableTemp(seqKey);
   g_dragOwnerId    = seq;
   g_staleLockTicks = 0;
  }

void AcquireDragLock()
  {
   string lockKey = DragLockKey();
   GlobalVariableSet(lockKey, (double)g_dragOwnerId);
   GlobalVariableTemp(lockKey);
   g_staleLockTicks = 0;
  }

void ReleaseDragLock(const bool force = false)
  {
   string lockKey = DragLockKey();
   if(!GlobalVariableCheck(lockKey))
      return;
   if(force || (uint)GlobalVariableGet(lockKey) == g_dragOwnerId)
      GlobalVariableDel(lockKey);
  }

string MouseMoveRefKey()
  {
   return StringFormat("MT5_DRAG_MM_REF_%I64d", ChartID());
  }

int CountAllChartIndicators()
  {
   int total   = 0;
   int windows = (int)ChartGetInteger(0, CHART_WINDOWS_TOTAL);
   for(int w = 0; w < windows; w++)
      total += ChartIndicatorsTotal(0, w);
   return total;
  }

void AcquireMouseMoveRef()
  {
   if(!InpDraggable || g_mouseRefHeld)
      return;
   ChartSetInteger(0, CHART_EVENT_MOUSE_MOVE, true);
   string refKey = MouseMoveRefKey();
   int    curRef = GlobalVariableCheck(refKey) ? MathMax(0, (int)GlobalVariableGet(refKey)) : 0;
   GlobalVariableSet(refKey, (double)(curRef + 1));
   GlobalVariableTemp(refKey);
   g_mouseRefHeld = true;
  }

void ReleaseMouseMoveRef(const int reason)
  {
   if(!g_mouseRefHeld)
      return;
   g_mouseRefHeld = false;
   string refKey  = MouseMoveRefKey();
   int    nextRef = GlobalVariableCheck(refKey) ? MathMax(0, (int)GlobalVariableGet(refKey) - 1) : 0;
   if(nextRef > 0)
     {
      GlobalVariableSet(refKey, (double)nextRef);
      GlobalVariableTemp(refKey);
     }
   else
     {
      GlobalVariableDel(refKey);
      if(reason == REASON_REMOVE && CountAllChartIndicators() <= 1)
         ChartSetInteger(0, CHART_EVENT_MOUSE_MOVE, false);
     }
  }

void EnsureMouseMoveEnabled()
  {
   if(InpDraggable && !(bool)ChartGetInteger(0, CHART_EVENT_MOUSE_MOVE))
      ChartSetInteger(0, CHART_EVENT_MOUSE_MOVE, true);
  }

void RemoveSelf()
  {
   if(g_panelDragging)
     {
      g_panelDragging = false;
      ChartSetInteger(0, CHART_MOUSE_SCROLL, g_origMouseScroll);
     }
   ReleaseDragLock(false);
   ClearSavedPanelPosition();
   ObjectsDeleteAll(0, g_prefix);
   ChartRedraw(0);

   int sub_window = (Window >= 0) ? Window : 0;
   int total = ChartIndicatorsTotal(0, sub_window);
   for(int k = total - 1; k >= 0; k--)
     {
      string sname = ChartIndicatorName(0, sub_window, k);
      if(sname == UniqueID)
        {
         ChartIndicatorDelete(0, sub_window, sname);
         return;
        }
     }
   ChartIndicatorDelete(0, sub_window, UniqueID);
  }

//+------------------------------------------------------------------+
//| Build and update the dashboard grid                              |
//+------------------------------------------------------------------+
void UpdateDashboard(const bool forceFull = false)
  {
   if(cpairsLen <= 0 || ctimesLen <= 0)
      return;

   int totalW = 0, titleX = 0, titleY = 0, titleW = 0;
   int btnX = 0, btnY = 0, btnW = 0;
   int closeX = 0, closeY = 0, closeW = 0;
   GetHeaderDimensions(totalW, titleX, titleY, titleW, btnX, btnY, btnW, closeX, closeY, closeW);

   string titleName  = g_prefix + "title";
   string btnName    = g_prefix + "btn_min";
   string closeName  = g_prefix + "btn_close";
   bool   needHeader = (forceFull || ObjectFind(0, titleName) < 0 || ObjectFind(0, btnName) < 0 || ObjectFind(0, closeName) < 0);

   if(needHeader)
     {
      string title = StringFormat(" MACD (%d,%d,%d)", InpFastEMA, InpSlowEMA, InpSignalSMA);
      ButtonUpsert(titleName, Window,
                   titleX, titleY, titleW, 14, Corner,
                   title, "Arial", 9, TextColor, BorderColor, FillColor);
      if(InpDraggable)
         ObjectSetString(0, titleName, OBJPROP_TOOLTIP, "Drag to move dashboard");
      UpdateHeaderAppearance();

      ButtonUpsert(btnName, Window,
                   btnX, btnY, btnW, 14, Corner,
                   g_minimized ? "+" : "-", "Arial Bold", 9,
                   TextColor, BorderColor, FillColor, false);
      ObjectSetString(0, btnName, OBJPROP_TOOLTIP,
                      g_minimized ? "Maximize Dashboard" : "Minimize Dashboard");

      ButtonUpsert(closeName, Window,
                   closeX, closeY, closeW, 14, Corner,
                   "x", "Arial Bold", 9,
                   clrWhite, BorderColor, C'168,40,40', false);
      ObjectSetString(0, closeName, OBJPROP_TOOLTIP, "Close Dashboard");
     }

   if(g_minimized)
     {
      if(needHeader)
         ChartRedraw(0);
      return;
     }

   int xshift = 0, nxshift = 0;
   GetLayoutShifts(xshift, nxshift);

   //--- Row headers (Symbols) & Column headers (Timeframes)
   bool rebuildGrid = forceFull || (ObjectFind(0, g_prefix + "s_0") < 0);
   if(rebuildGrid)
     {
      for(int i = 0; i < cpairsLen; i++)
        {
         bool   isCur   = (InpHighlightCurr && StringCompare(cpairs[i], _Symbol, false) == 0);
         string rowFont = isCur ? "Arial Bold" : "Arial";
         color  rowTxt  = isCur ? CurrTextColor : TextColor;
         color  rowBg   = isCur ? CurrBgColor   : FillColor;
         ButtonUpsert(g_prefix + "s_" + IntegerToString(i), Window,
                      g_panelX + nxshift + 2, g_panelY + 30 + i * 15, 66, 14, Corner,
                      cpairs[i], rowFont, 9, rowTxt, BorderColor, rowBg);
        }

      for(int t = 0; t < ctimesLen; t++)
         ButtonUpsert(g_prefix + "h_" + IntegerToString(t), Window,
                      g_panelX + xshift + t * 50 + 69, g_panelY + 15, 49, 14, Corner,
                      TimeFrameToString(aTimes[t]), "Arial", 9, TextColor, BorderColor, FillColor);
     }

   //--- Cells: only recalculate & update when bar time changes (no tick flicker)
   bool anyChanged = rebuildGrid;
   for(int i = 0; i < cpairsLen; i++)
     {
      for(int t = 0; t < ctimesLen; t++)
        {
         int cellIdx = i * ctimesLen + t;
         datetime latestTime = iTime(cpairs[i], aTimes[t], MathMax(0, BarToTest));

         if(!rebuildGrid && g_lastCellComplete[cellIdx] && BarToTest > 0 && latestTime > 0 && latestTime == g_lastEvalBarTime[cellIdx])
            continue;

         datetime evalTime = 0;
         bool     isComplete = false;
         color cellColor = EvaluateCellColor(cpairs[i], aTimes[t], evalTime, isComplete);
         if(evalTime > 0)
           {
            g_lastEvalBarTime[cellIdx]  = evalTime;
            g_lastCellComplete[cellIdx] = isComplete;
           }
         else if(!g_warnedCell[cellIdx])
           {
            g_warnedCell[cellIdx] = true;
            PrintFormat("MACD(drag_dashboard): waiting for %s %s history (iBars=%d, err=%d)",
                        cpairs[i], TimeFrameToString(aTimes[t]), iBars(cpairs[i], aTimes[t]), GetLastError());
           }

         string cellName = g_prefix + "c_" + IntegerToString(t) + "_" + IntegerToString(i);
         if(rebuildGrid || ObjectFind(0, cellName) < 0 || g_lastCellColor[cellIdx] != cellColor)
           {
            g_lastCellColor[cellIdx] = cellColor;
            bool  isCur   = (InpHighlightCurr && StringCompare(cpairs[i], _Symbol, false) == 0);
            color cellBrd = isCur ? CurrBorderColor : BorderColor;
            ButtonUpsert(cellName, Window,
                         g_panelX + xshift + t * 50 + 69, g_panelY + 30 + i * 15, 49, 14, Corner,
                         " ", "Arial", 10, cellColor, cellBrd, cellColor);
            if(isCur)
               ObjectSetInteger(0, cellName, OBJPROP_ZORDER, 11);
            anyChanged = true;
           }
        }
     }

   if(anyChanged)
      ChartRedraw(0);
  }

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
   g_mouseRefHeld = false;
   if(InpFastEMA < 1 || InpSlowEMA < 1 || InpSignalSMA < 1)
     {
      PrintFormat("MACD(drag_dashboard): Fast/Slow/Signal periods must be >= 1.");
      return(INIT_PARAMETERS_INCORRECT);
     }

   g_prefix = UniqueID + "_" + IntegerToString(ChartID()) + "_";

   //--- Parse Symbols list
   string symStr = Symbols;
   StringTrimLeft(symStr);
   StringTrimRight(symStr);
   if(StringLen(symStr) > 0 && StringSubstr(symStr, StringLen(symStr) - 1, 1) != ";")
      symStr += ";";
   StringReplace(symStr, "current", _Symbol);

   ArrayResize(cpairs, 0);
   int s = 0;
   int pos = StringFind(symStr, ";", s);
   while(pos >= 0)
     {
      string sym = StringSubstr(symStr, s, pos - s);
      StringTrimLeft(sym);
      StringTrimRight(sym);
      if(sym != "")
        {
         bool duplicate = false;
         for(int k = 0; k < ArraySize(cpairs); k++)
           {
            if(cpairs[k] == sym)
              {
               duplicate = true;
               break;
              }
           }
         if(!duplicate)
           {
            if(SymbolInfoInteger(sym, SYMBOL_EXIST))
               SymbolSelect(sym, true);
            int sz = ArraySize(cpairs);
            ArrayResize(cpairs, sz + 1);
            cpairs[sz] = sym;
           }
        }
      s   = pos + 1;
      pos = StringFind(symStr, ";", s);
     }
   if(Corner == CORNER_LEFT_LOWER || Corner == CORNER_RIGHT_LOWER)
      InvertStringArray(cpairs);
   cpairsLen = ArraySize(cpairs);

   //--- Parse TimeFrames list
   string tfStr = TimeFrames;
   StringTrimLeft(tfStr);
   StringTrimRight(tfStr);
   if(StringLen(tfStr) > 0 && StringSubstr(tfStr, StringLen(tfStr) - 1, 1) != ";")
      tfStr += ";";

   ArrayResize(aTimes, 0);
   s   = 0;
   pos = StringFind(tfStr, ";", s);
   while(pos >= 0)
     {
      string tfToken = StringSubstr(tfStr, s, pos - s);
      StringTrimLeft(tfToken);
      StringTrimRight(tfToken);
      if(tfToken != "")
        {
         ENUM_TIMEFRAMES tf = StringToTimeFrame(tfToken);
         int sz = ArraySize(aTimes);
         ArrayResize(aTimes, sz + 1);
         aTimes[sz] = tf;
        }
      s   = pos + 1;
      pos = StringFind(tfStr, ";", s);
     }
   if(Corner == CORNER_RIGHT_UPPER || Corner == CORNER_RIGHT_LOWER)
      InvertTfArray(aTimes);
   ctimesLen = ArraySize(aTimes);

   int totalCells = cpairsLen * ctimesLen;
   ArrayResize(g_lastEvalBarTime,  totalCells);
   ArrayResize(g_lastCellColor,    totalCells);
   ArrayResize(g_lastCellComplete, totalCells);
   ArrayResize(g_warnedCell,       totalCells);
   ArrayInitialize(g_lastEvalBarTime,  0);
   ArrayInitialize(g_lastCellColor,    clrNONE);
   ArrayInitialize(g_lastCellComplete, false);
   ArrayInitialize(g_warnedCell,       false);

   //--- Pre-warm history requests for all symbol/TF pairs
   int minSpan  = MathMax(InpFastEMA, InpSlowEMA) + InpSignalSMA + 2;
   int warmBars = MathMax(InpCalcBars, minSpan * 5) + MathMax(0, BarToTest) + 5;
   MqlRates warm[];
   for(int i = 0; i < cpairsLen; i++)
      for(int t = 0; t < ctimesLen; t++)
         CopyRates(cpairs[i], aTimes[t], 0, warmBars, warm);

   g_panelX          = XShift;
   g_panelY          = YShift;
   g_minimized       = false;
   g_panelDragging   = false;
   g_headerHovered   = false;
   g_prevMouseState  = 0;
   g_origMouseScroll = (bool)ChartGetInteger(0, CHART_MOUSE_SCROLL);
   AllocDragOwnerId();

   string p = PositionGvPrefix();
   if(GlobalVariableCheck(p + "InitX") && GlobalVariableCheck(p + "InitY") &&
      GlobalVariableCheck(p + "Corner") &&
      (int)GlobalVariableGet(p + "InitX") == XShift &&
      (int)GlobalVariableGet(p + "InitY") == YShift &&
      (int)GlobalVariableGet(p + "Corner") == (int)Corner)
     {
      if(InpDraggable && GlobalVariableCheck(p + "X") && GlobalVariableCheck(p + "Y"))
        {
         g_panelX = (int)GlobalVariableGet(p + "X");
         g_panelY = (int)GlobalVariableGet(p + "Y");
        }
      if(GlobalVariableCheck(p + "Min"))
         g_minimized = (GlobalVariableGet(p + "Min") > 0.5);
     }
   ClampPanelPosition();
   AcquireMouseMoveRef();

   IndicatorSetString(INDICATOR_SHORTNAME, UniqueID);
   ObjectsDeleteAll(0, g_prefix);

   UpdateDashboard(true);
   EventSetTimer(2);

   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   EventKillTimer();
   ReleaseMouseMoveRef(reason);
   if(g_panelDragging)
     {
      g_panelDragging = false;
      ChartSetInteger(0, CHART_MOUSE_SCROLL, g_origMouseScroll);
     }
   ReleaseDragLock(false);
   if(reason != REASON_CHARTCHANGE && reason != REASON_RECOMPILE)
      ClearSavedPanelPosition();
   if(g_prefix != "")
      ObjectsDeleteAll(0, g_prefix);
   ChartRedraw(0);
  }

//+------------------------------------------------------------------+
//| Timer event: update cells as closed bars / history arrive        |
//+------------------------------------------------------------------+
void OnTimer()
  {
   EnsureMouseMoveEnabled();
   if(g_minimized || g_panelDragging)
      return;
   UpdateDashboard(false);
  }

//+------------------------------------------------------------------+
//| Chart event: dragging, hover effects & click-to-switch           |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
   if(id == CHARTEVENT_CHART_CHANGE && InpDraggable)
     {
      int oldX = g_panelX;
      int oldY = g_panelY;
      ClampPanelPosition();
      if(g_panelX != oldX || g_panelY != oldY)
        {
         RepositionDashboardObjects();
         SavePanelPosition();
         ChartRedraw(0);
        }
      return;
     }

   if(id == CHARTEVENT_MOUSE_MOVE && InpDraggable)
     {
      int  mouseX     = (int)lparam;
      int  winOffsetY = (Window > 0) ? (int)ChartGetInteger(0, CHART_WINDOW_YDISTANCE, Window) : 0;
      int  mouseY     = (int)dparam - winOffsetY;
      int  mouseState = (int)StringToInteger(sparam);
      bool leftDown   = ((mouseState & 1) != 0);
      bool prevDown   = ((g_prevMouseState & 1) != 0);

      string lockKey  = DragLockKey();
      bool   isLocked = GlobalVariableCheck(lockKey);

      if(!leftDown && !g_panelDragging)
        {
         if(isLocked)
           {
            g_staleLockTicks++;
            if(g_staleLockTicks >= 3)
              {
               GlobalVariableDel(lockKey);
               isLocked         = false;
               g_staleLockTicks = 0;
              }
           }
         else
            g_staleLockTicks = 0;
        }
      else
         g_staleLockTicks = 0;

      int hLeft = 0, hTop = 0, hRight = 0, hBottom = 0;
      GetHeaderScreenRect(hLeft, hTop, hRight, hBottom);
      bool overHeader = (mouseX >= hLeft && mouseX <= hRight &&
                         mouseY >= hTop  && mouseY <= hBottom);

      bool wantHover = overHeader && (!isLocked || g_panelDragging);
      if(wantHover != g_headerHovered)
        {
         g_headerHovered = wantHover;
         UpdateHeaderAppearance();
         ChartRedraw(0);
        }

      if(!prevDown && leftDown && overHeader && !isLocked)
        {
         AcquireDragLock();
         g_panelDragging   = true;
         g_dragMouseX      = mouseX;
         g_dragMouseY      = mouseY;
         g_dragStartX      = g_panelX;
         g_dragStartY      = g_panelY;
         g_origMouseScroll = (bool)ChartGetInteger(0, CHART_MOUSE_SCROLL);
         ChartSetInteger(0, CHART_MOUSE_SCROLL, false);
         UpdateHeaderAppearance();
         ChartRedraw(0);
        }
      else if(g_panelDragging && leftDown)
        {
         int dx = mouseX - g_dragMouseX;
         int dy = mouseY - g_dragMouseY;
         bool isRight = (Corner == CORNER_RIGHT_LOWER || Corner == CORNER_RIGHT_UPPER);
         bool isLower = (Corner == CORNER_LEFT_LOWER  || Corner == CORNER_RIGHT_LOWER);

         g_panelX = isRight ? (g_dragStartX - dx) : (g_dragStartX + dx);
         g_panelY = isLower ? (g_dragStartY - dy) : (g_dragStartY + dy);
         ClampPanelPosition();
         RepositionDashboardObjects();
         ChartRedraw(0);
        }
      else if(g_panelDragging && !leftDown)
        {
         g_panelDragging = false;
         ReleaseDragLock(true);
         ChartSetInteger(0, CHART_MOUSE_SCROLL, g_origMouseScroll);
         SavePanelPosition();
         UpdateHeaderAppearance();
         ChartRedraw(0);
        }

      g_prevMouseState = mouseState;
      return;
     }

   if(id != CHARTEVENT_OBJECT_CLICK)
      return;

   if(StringFind(sparam, g_prefix) != 0)
      return;

   string suffix = StringSubstr(sparam, StringLen(g_prefix));

   if(suffix == "btn_close")
     {
      RemoveSelf();
      return;
     }

   if(suffix == "btn_min")
     {
      ObjectSetInteger(0, sparam, OBJPROP_STATE, false);
      if(g_panelDragging)
        {
         g_panelDragging = false;
         ReleaseDragLock(true);
         ChartSetInteger(0, CHART_MOUSE_SCROLL, g_origMouseScroll);
        }
      g_headerHovered = false;
      g_minimized     = !g_minimized;
      ObjectsDeleteAll(0, g_prefix);
      ClampPanelPosition();
      SavePanelPosition();
      UpdateDashboard(true);
      return;
     }

   // Keep button visually flat/pressed like a heatmap cell
   ObjectSetInteger(0, sparam, OBJPROP_STATE, true);

   if(!InpClickSwitch)
      return;

   if(StringFind(suffix, "s_") == 0)
     {
      int idx = (int)StringToInteger(StringSubstr(suffix, 2));
      if(idx >= 0 && idx < cpairsLen)
         ChartSetSymbolPeriod(0, cpairs[idx], _Period);
     }
   else if(StringFind(suffix, "h_") == 0)
     {
      int idx = (int)StringToInteger(StringSubstr(suffix, 2));
      if(idx >= 0 && idx < ctimesLen)
         ChartSetSymbolPeriod(0, _Symbol, aTimes[idx]);
     }
   else if(StringFind(suffix, "c_") == 0)
     {
      string parts[];
      if(StringSplit(StringSubstr(suffix, 2), '_', parts) == 2)
        {
         int t = (int)StringToInteger(parts[0]);
         int i = (int)StringToInteger(parts[1]);
         if(i >= 0 && i < cpairsLen && t >= 0 && t < ctimesLen)
            ChartSetSymbolPeriod(0, cpairs[i], aTimes[t]);
        }
     }
  }

//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
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[])
  {
   EnsureMouseMoveEnabled();
   if(g_minimized || g_panelDragging)
      return(rates_total);

   if(prev_calculated == rates_total)
     {
      if(BarToTest > 0)
         return(rates_total);
      ulong nowMs = GetTickCount64();
      if(nowMs - g_lastTickCalcMs < 250)
         return(rates_total);
      g_lastTickCalcMs = nowMs;
     }

   UpdateDashboard(prev_calculated <= 0);
   return(rates_total);
  }
//+------------------------------------------------------------------+
