//+------------------------------------------------------------------+
//|                                Gold_Strength(thick_histo)_BT.mq5 |
//|                                                       Teddy Meyn |
//+------------------------------------------------------------------+
//| XAUUSD-focused Currency Strength Meter in a separate window:     |
//| - XAU strength rendered as a 3D layered 4-color slope histogram  |
//|   (JackJill thick_histo style: outer/core/highlight layers)      |
//| - USD strength rendered as a one-color line overlay              |
//| - Customizable Gold zero reference line                          |
//| - On/Off toggle button with state persistence                    |
//|                                                                  |
//| Reads prices only; never opens, modifies or closes trades.       |
//+------------------------------------------------------------------+
#property copyright "Teddy Meyn (Gold 3D Thick Histo © 2026, Forex-Station)"
#property link      "https://www.mql5.com/en/code/79618"
#property version   "1.00"
#property description "XAUUSD Currency Strength: 3D 4-color slope thick histogram for Gold (XAU)"
#property description "with a one-color USD strength line in a separate window and On/Off toggle button."
#property description "Reads prices only, never trades."

#property indicator_separate_window
#property indicator_buffers 10
#property indicator_plots   5

//--- Plots 0, 1, 2: 3D XAU Histogram (Outer -> Core -> Inner Highlight)
#property indicator_type1   DRAW_COLOR_HISTOGRAM
#property indicator_width1  5
#property indicator_label1  "XAU Outer"

#property indicator_type2   DRAW_COLOR_HISTOGRAM
#property indicator_width2  3
#property indicator_label2  "XAU"

#property indicator_type3   DRAW_COLOR_HISTOGRAM
#property indicator_width3  1
#property indicator_label3  "XAU Highlight"

//--- Plot 3: Zero reference line
#property indicator_type4   DRAW_LINE
#property indicator_color4  clrGold
#property indicator_width4  1
#property indicator_label4  "Zero"

//--- Plot 4: USD strength (one-color line drawn on top)
#property indicator_type5   DRAW_LINE
#property indicator_color5  clrLime
#property indicator_style5  STYLE_SOLID
#property indicator_width5  2
#property indicator_label5  "USD"

//--- calculation method
enum ENUM_CSM_METHOD
  {
   CSM_PERCENT = 0, // Percent change over lookback
   CSM_ATR     = 1  // Change in ATR units over lookback
  };

//--- inputs
input group "--- Symbols (XAUUSD Only) ---"
input string          InpPrefix         = "";          // Symbol prefix (e.g. "m.")
input string          InpSuffix         = "";          // Symbol suffix (e.g. ".pro", "m")
input string          InpGoldSymbol     = "XAUUSD";    // Gold symbol name (without prefix/suffix)

input group "--- Calculation ---"
input ENUM_CSM_METHOD InpMethod         = CSM_PERCENT; // Method
input int             InpLookback       = 20;          // Lookback (bars)
input int             InpSmoothing      = 3;           // Smoothing period (1 = off)
input int             InpBars           = 500;         // Bars to calculate

input group "--- 3D Histogram Widths ---"
input int             InpHistOuterWidth = 5;           // Histogram outer width (1-5)
input int             InpHistCoreWidth  = 3;           // Histogram core width (1-5)
input int             InpHistInnerWidth = 1;           // Histogram highlight width (1-5)

input group "--- XAU 4-Color FX Slope Settings ---"
input bool            InpUse4Colors     = true;            // Use 4 colors (strong/retracement)
input color           InpCandleUp       = C'96,170,204';   // Strong Bullish (Above 0 & Rising)
input color           InpCandleUpWeak   = C'35,100,130';   // Bullish Retracement (Above 0 & Falling)
input color           InpCandleDn       = C'255,140,255';  // Strong Bearish (Below 0 & Falling)
input color           InpCandleDnWeak   = C'180,70,180';   // Bearish Retracement (Below 0 & Rising)
input color           InpCandleWt       = C'34,34,34';     // Neutral (Zero)

input group "--- USD Line (One Color) ---"
input bool            InpShowUSDLine    = true;        // Show USD Line
input color           InpColUSD         = clrLime;     // USD Line Color
input ENUM_LINE_STYLE InpUSDStyle       = STYLE_SOLID; // USD Line Style
input int             InpUSDWidth       = 2;           // USD Line Width (Dash/Dot require 1)

input group "--- Zero Line ---"
input bool            InpShowZeroLine   = true;        // Show Zero Reference Line
input color           InpZeroColor      = clrGold;     // Zero line color
input int             InpZeroWidth      = 1;           // Zero line width (1-5)

//--- Toggle Button Settings
input group "=== Toggle Button Settings ==="
input int             btn_Subwindow        = 0;                   // Subwindow for button (0=Main, -1=Indicator SW)
input ENUM_BASE_CORNER btn_corner          = CORNER_LEFT_UPPER;   // Button Corner
input string          btn_text             = "Gold2: ON";         // Button Text
input string          btn_Font             = "Arial";             // Button Font
input int             btn_FontSize         = 9;                   // Button Font Size
input color           btn_text_ON_color    = clrLime;             // Text Color ON
input color           btn_text_OFF_color   = clrRed;              // Text Color OFF
input color           btn_background_color = clrDimGray;          // Button Background Color
input color           btn_border_color     = clrBlack;            // Button Border Color
input int             button_x             = 20;                  // Button X Position
input int             button_y             = 80;                  // Button Y Position
input int             btn_Width            = 80;                  // Button Width
input int             btn_Height           = 20;                  // Button Height
input string          UniqueButtonID       = "GThickHistoBT";     // Unique Button ID

//--- constants: the 7 USD major pairs + Gold
#define NUSDPAIR 7
#define GOLDIDX  7

string g_usdBase[NUSDPAIR]  = {"EUR","GBP","AUD","NZD","USD","USD","USD"};
string g_usdQuote[NUSDPAIR] = {"USD","USD","USD","USD","JPY","CHF","CAD"};

//--- per-symbol price storage (7 USD pairs + Gold)
class CSeries
  {
public:
   string            name;      // full broker symbol name
   bool              usdIsBase; // true for USDJPY/USDCHF/USDCAD
   bool              available; // symbol exists at broker
   bool              noHistory; // gave up waiting for history
   MqlRates          r[];       // rates, oldest first
  };
CSeries g_s[NUSDPAIR + 1];

//--- plot buffers
double g_histDark[],  g_histDarkCol[];   // Plot 0
double g_histBase[],  g_histBaseCol[];   // Plot 1
double g_histLight[], g_histLightCol[];  // Plot 2
double g_zeroBuf[];                      // Plot 3
double g_usdPlot[];                      // Plot 4

//--- calculation buffers
double g_xauRaw[], g_usdRaw[];

//--- runtime state
int    g_lookback, g_smooth, g_bars;
int    g_retries = 0;
bool   g_pending = false;

//--- button state tracking variables
bool   IndicatorEnabled = true;
bool   IndicatorHidden  = false;
int    g_btnWindow      = 0;
string ToggleButtonName = "";
string g_gvHidden       = "";
string IndicatorName    = "";
string IndicatorObjPrefix = "";
string buttonId         = "";

//+------------------------------------------------------------------+
//| Utility: Blend two colors by a given ratio (for 3D shading)      |
//+------------------------------------------------------------------+
color BlendColor(color c,color blendWith,double ratio)
  {
   int r1 = (int)(c & 0x0000FF);
   int g1 = (int)((c & 0x00FF00) >> 8);
   int b1 = (int)((c & 0xFF0000) >> 16);
   int r2 = (int)(blendWith & 0x0000FF);
   int g2 = (int)((blendWith & 0x00FF00) >> 8);
   int b2 = (int)((blendWith & 0xFF0000) >> 16);

   int r = (int)MathRound(r1 + (r2 - r1) * ratio);
   int g = (int)MathRound(g1 + (g2 - g1) * ratio);
   int b = (int)MathRound(b1 + (b2 - b1) * ratio);
   return (color)(r | (g << 8) | (b << 16));
  }

int ClampWidth(const int w)
  {
   return (int)MathMin(MathMax(w, 1), 5);
  }

//+------------------------------------------------------------------+
//| Helper: Reliably find indicator subwindow number                 |
//+------------------------------------------------------------------+
int GetIndicatorSubwindow()
  {
   int sub = ChartWindowFind();
   if(sub > 0)
      return sub;

   if(IndicatorName != "")
     {
      sub = ChartWindowFind(0, IndicatorName);
      if(sub > 0)
         return sub;
     }

   int total = (int)ChartGetInteger(0, CHART_WINDOWS_TOTAL);
   for(int w = 1; w < total; w++)
     {
      int total_ind = ChartIndicatorsTotal(0, w);
      for(int i = 0; i < total_ind; i++)
        {
         if(StringFind(ChartIndicatorName(0, w, i), "Gold Strength") >= 0)
            return w;
        }
     }
   return -1;
  }

//+------------------------------------------------------------------+
//| Helper to resolve button text based on state                     |
//+------------------------------------------------------------------+
string GetButtonText(bool isEnabled)
  {
   string t = btn_text;
   if(isEnabled)
     {
      if(StringFind(t, "OFF") >= 0)      StringReplace(t, "OFF", "ON");
      else if(StringFind(t, "Off") >= 0) StringReplace(t, "Off", "On");
      else if(StringFind(t, "off") >= 0) StringReplace(t, "off", "on");
     }
   else
     {
      if(StringFind(t, "ON") >= 0)       StringReplace(t, "ON", "OFF");
      else if(StringFind(t, "On") >= 0)  StringReplace(t, "On", "Off");
      else if(StringFind(t, "on") >= 0)  StringReplace(t, "on", "off");
     }
   return t;
  }

//+------------------------------------------------------------------+
//| Apply Plot Visibility Based on IndicatorHidden State             |
//+------------------------------------------------------------------+
void ApplyPlotsStyle()
  {
   if(IndicatorHidden)
     {
      for(int p = 0; p < 5; p++)
        {
         PlotIndexSetInteger(p, PLOT_DRAW_TYPE, DRAW_NONE);
         PlotIndexSetInteger(p, PLOT_SHOW_DATA, false);
        }
     }
   else
     {
      // Restore 3D XAU histogram
      for(int p = 0; p < 3; p++)
        {
         PlotIndexSetInteger(p, PLOT_DRAW_TYPE, DRAW_COLOR_HISTOGRAM);
         PlotIndexSetInteger(p, PLOT_SHOW_DATA, (p == 1)); // Core layer only
        }

      // Restore Zero reference line
      PlotIndexSetInteger(3, PLOT_DRAW_TYPE, InpShowZeroLine ? DRAW_LINE : DRAW_NONE);
      PlotIndexSetInteger(3, PLOT_SHOW_DATA, false);

      // Restore USD line
      PlotIndexSetInteger(4, PLOT_DRAW_TYPE, InpShowUSDLine ? DRAW_LINE : DRAW_NONE);
      PlotIndexSetInteger(4, PLOT_SHOW_DATA, InpShowUSDLine);
     }
  }

//+------------------------------------------------------------------+
//| Update Toggle Button Appearance                                  |
//+------------------------------------------------------------------+
void UpdateToggleButton()
  {
   if(ObjectFind(0, buttonId) < 0) return;

   IndicatorEnabled = !IndicatorHidden;

   string labelText = GetButtonText(IndicatorEnabled);
   color  textColor = IndicatorEnabled ? btn_text_ON_color : btn_text_OFF_color;

   ObjectSetString (0, buttonId, OBJPROP_TEXT,         labelText);
   ObjectSetString (0, buttonId, OBJPROP_FONT,         btn_Font);
   ObjectSetInteger(0, buttonId, OBJPROP_FONTSIZE,     btn_FontSize);
   ObjectSetInteger(0, buttonId, OBJPROP_COLOR,        textColor);
   ObjectSetInteger(0, buttonId, OBJPROP_BGCOLOR,      btn_background_color);
   ObjectSetInteger(0, buttonId, OBJPROP_BORDER_COLOR, btn_border_color);
   ObjectSetInteger(0, buttonId, OBJPROP_CORNER,       btn_corner);
   ObjectSetInteger(0, buttonId, OBJPROP_XDISTANCE,    button_x);
   ObjectSetInteger(0, buttonId, OBJPROP_XSIZE,        btn_Width);
   ObjectSetInteger(0, buttonId, OBJPROP_YSIZE,        btn_Height);
   ObjectSetInteger(0, buttonId, OBJPROP_STATE,        IndicatorEnabled);
   ObjectSetInteger(0, buttonId, OBJPROP_ZORDER,       100);

   ChartRedraw(0);
  }

//+------------------------------------------------------------------+
//| Create Toggle Button                                             |
//+------------------------------------------------------------------+
void CreateToggleButton()
  {
   g_btnWindow = (btn_Subwindow < 0) ? GetIndicatorSubwindow() : btn_Subwindow;
   if(g_btnWindow < 0)
      return; // Subwindow not yet assigned during OnInit; retry in OnCalculate

   if(ObjectFind(0, buttonId) < 0)
     {
      int y_pos = button_y;
      int obj_total = ObjectsTotal(0, g_btnWindow, OBJ_BUTTON);
      bool collision = true;
      while(collision)
        {
         collision = false;
         for(int i = 0; i < obj_total; i++)
           {
            string name = ObjectName(0, i, g_btnWindow, OBJ_BUTTON);
            if(name == buttonId) continue;
            if((ENUM_BASE_CORNER)ObjectGetInteger(0, name, OBJPROP_CORNER) != btn_corner) continue;
            if(ObjectGetInteger(0, name, OBJPROP_XDISTANCE) == button_x &&
               ObjectGetInteger(0, name, OBJPROP_YDISTANCE) == y_pos)
              {
               y_pos += btn_Height + 4;
               collision = true;
               break;
              }
           }
        }

      ObjectCreate(0, buttonId, OBJ_BUTTON, g_btnWindow, 0, 0);

      ObjectSetInteger(0, buttonId, OBJPROP_CORNER,       btn_corner);
      ObjectSetInteger(0, buttonId, OBJPROP_XDISTANCE,    button_x);
      ObjectSetInteger(0, buttonId, OBJPROP_YDISTANCE,    y_pos);
      ObjectSetInteger(0, buttonId, OBJPROP_XSIZE,        btn_Width);
      ObjectSetInteger(0, buttonId, OBJPROP_YSIZE,        btn_Height);
      ObjectSetString (0, buttonId, OBJPROP_FONT,         btn_Font);
      ObjectSetInteger(0, buttonId, OBJPROP_FONTSIZE,     btn_FontSize);
      ObjectSetInteger(0, buttonId, OBJPROP_BGCOLOR,      btn_background_color);
      ObjectSetInteger(0, buttonId, OBJPROP_BORDER_COLOR, btn_border_color);
      ObjectSetInteger(0, buttonId, OBJPROP_BORDER_TYPE,  BORDER_RAISED);
      ObjectSetInteger(0, buttonId, OBJPROP_SELECTABLE,   false);
      ObjectSetInteger(0, buttonId, OBJPROP_HIDDEN,       true);
      ObjectSetInteger(0, buttonId, OBJPROP_TIMEFRAMES,   OBJ_ALL_PERIODS);
      ObjectSetInteger(0, buttonId, OBJPROP_ZORDER,       100);
     }

   UpdateToggleButton();
  }

//+------------------------------------------------------------------+
//| Ensure all buttons on chart have higher ZORDER                   |
//+------------------------------------------------------------------+
void BringButtonsToFront()
  {
   int total = ObjectsTotal(0, -1, OBJ_BUTTON);
   for(int i = 0; i < total; i++)
     {
      string name = ObjectName(0, i, -1, OBJ_BUTTON);
      if(name != "")
        {
         if(ObjectGetInteger(0, name, OBJPROP_ZORDER) < 100)
            ObjectSetInteger(0, name, OBJPROP_ZORDER, 100);
        }
     }
  }

//+------------------------------------------------------------------+
//| Toggle Indicator Visibility                                      |
//+------------------------------------------------------------------+
void ToggleIndicatorVisibility()
  {
   IndicatorHidden  = !IndicatorHidden;
   IndicatorEnabled = !IndicatorHidden;

   if(g_gvHidden != "")
      GlobalVariableSet(g_gvHidden, IndicatorHidden ? 1.0 : 0.0);

   ApplyPlotsStyle();
   UpdateToggleButton();
   BringButtonsToFront();
   ChartRedraw(0);
  }

//+------------------------------------------------------------------+
//| Resolve Broker Symbol Prefix/Suffix (handles XAUUSD variants)    |
//+------------------------------------------------------------------+
void ResolveBrokerAffixes(string &pfx,string &sfx)
  {
   pfx = InpPrefix;
   sfx = InpSuffix;
   if(pfx != "" || sfx != "") return;

   bool custom = false;
   if(SymbolExist(InpGoldSymbol, custom)) return;

   string sym  = _Symbol;
   string gSym = InpGoldSymbol;
   string uSym = sym, uGold = gSym;
   StringToUpper(uSym);
   StringToUpper(uGold);

   int pos = StringFind(uSym, uGold);
   if(pos >= 0)
     {
      pfx = StringSubstr(sym, 0, pos);
      sfx = StringSubstr(sym, pos + StringLen(gSym));
      if(SymbolExist(pfx + "EURUSD" + sfx, custom))
         return;
      pfx = "";
      sfx = "";
     }
  }

//+------------------------------------------------------------------+
//| Initialisation                                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   g_lookback = MathMax(1, InpLookback);
   g_smooth   = MathMax(1, InpSmoothing);
   g_bars     = MathMax(50, InpBars);
   g_retries  = 0;
   g_pending  = false;

   //--- bind buffers (plots 0..4 followed by calculation buffers)
   SetIndexBuffer(0, g_histDark,     INDICATOR_DATA);
   SetIndexBuffer(1, g_histDarkCol,  INDICATOR_COLOR_INDEX);
   SetIndexBuffer(2, g_histBase,     INDICATOR_DATA);
   SetIndexBuffer(3, g_histBaseCol,  INDICATOR_COLOR_INDEX);
   SetIndexBuffer(4, g_histLight,    INDICATOR_DATA);
   SetIndexBuffer(5, g_histLightCol, INDICATOR_COLOR_INDEX);
   SetIndexBuffer(6, g_zeroBuf,      INDICATOR_DATA);
   SetIndexBuffer(7, g_usdPlot,      INDICATOR_DATA);
   SetIndexBuffer(8, g_xauRaw,       INDICATOR_CALCULATIONS);
   SetIndexBuffer(9, g_usdRaw,       INDICATOR_CALCULATIONS);

   ArraySetAsSeries(g_histDark,     false);
   ArraySetAsSeries(g_histDarkCol,  false);
   ArraySetAsSeries(g_histBase,     false);
   ArraySetAsSeries(g_histBaseCol,  false);
   ArraySetAsSeries(g_histLight,    false);
   ArraySetAsSeries(g_histLightCol, false);
   ArraySetAsSeries(g_zeroBuf,      false);
   ArraySetAsSeries(g_usdPlot,      false);
   ArraySetAsSeries(g_xauRaw,       false);
   ArraySetAsSeries(g_usdRaw,       false);

   //--- 3D FX palette: 0=strong bull, 1=neutral, 2=strong bear, 3=weak bull, 4=weak bear
   color baseColors[5] = {InpCandleUp, InpCandleWt, InpCandleDn,
                          InpCandleUpWeak, InpCandleDnWeak};

   for(int p=0; p<3; p++)
     {
      PlotIndexSetInteger(p, PLOT_COLOR_INDEXES, 5);
      PlotIndexSetDouble (p, PLOT_EMPTY_VALUE,   EMPTY_VALUE);
      PlotIndexSetInteger(p, PLOT_SHOW_DATA,     (p == 1)); // show core XAU only
     }

   for(int c=0; c<5; c++)
     {
      color base  = baseColors[c];
      color dark  = BlendColor(base, clrBlack, 0.4); // 40% darker outer edge
      color light = BlendColor(base, clrWhite, 0.6); // 60% lighter core highlight

      PlotIndexSetInteger(0, PLOT_LINE_COLOR, c, dark);
      PlotIndexSetInteger(1, PLOT_LINE_COLOR, c, base);
      PlotIndexSetInteger(2, PLOT_LINE_COLOR, c, light);
     }

   PlotIndexSetInteger(0, PLOT_LINE_WIDTH, ClampWidth(InpHistOuterWidth));
   PlotIndexSetInteger(1, PLOT_LINE_WIDTH, ClampWidth(InpHistCoreWidth));
   PlotIndexSetInteger(2, PLOT_LINE_WIDTH, ClampWidth(InpHistInnerWidth));

   //--- Zero reference line
   PlotIndexSetInteger(3, PLOT_DRAW_TYPE,   InpShowZeroLine ? DRAW_LINE : DRAW_NONE);
   PlotIndexSetInteger(3, PLOT_LINE_COLOR,  0, InpZeroColor);
   PlotIndexSetInteger(3, PLOT_LINE_WIDTH,  ClampWidth(InpZeroWidth));
   PlotIndexSetDouble (3, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(3, PLOT_SHOW_DATA,   false);

   //--- USD one-color line
   int usdWidth = ClampWidth(InpUSDWidth);
   if(InpUSDStyle != STYLE_SOLID && usdWidth > 1)
      usdWidth = 1;
   PlotIndexSetInteger(4, PLOT_DRAW_TYPE,   InpShowUSDLine ? DRAW_LINE : DRAW_NONE);
   PlotIndexSetInteger(4, PLOT_LINE_COLOR,  0, InpColUSD);
   PlotIndexSetInteger(4, PLOT_LINE_STYLE,  InpUSDStyle);
   PlotIndexSetInteger(4, PLOT_LINE_WIDTH,  usdWidth);
   PlotIndexSetString (4, PLOT_LABEL,       "USD");
   PlotIndexSetDouble (4, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(4, PLOT_SHOW_DATA,   InpShowUSDLine);

   //--- resolve the 7 USD pairs + Gold
   string pfx = "", sfx = "";
   ResolveBrokerAffixes(pfx, sfx);

   for(int p=0; p<NUSDPAIR; p++)
     {
      g_s[p].name      = pfx + g_usdBase[p] + g_usdQuote[p] + sfx;
      g_s[p].usdIsBase = (g_usdBase[p] == "USD");
     }
   g_s[GOLDIDX].name      = pfx + InpGoldSymbol + sfx;
   g_s[GOLDIDX].usdIsBase = false;

   for(int k=0; k<=NUSDPAIR; k++)
     {
      bool custom = false;
      g_s[k].available = SymbolExist(g_s[k].name, custom);
      g_s[k].noHistory = false;
      if(g_s[k].available) SymbolSelect(g_s[k].name, true);
     }

   string short_name = StringFormat("Gold Strength BT (%d, %s, XAU 3D / USD Line)",
                                    g_lookback, InpMethod == CSM_PERCENT ? "%" : "ATR");
   IndicatorSetString(INDICATOR_SHORTNAME, short_name);
   IndicatorSetInteger(INDICATOR_DIGITS, 3);

   //--- button IDs and persistence setup
   IndicatorObjPrefix = "__" + btn_text + "__";
   buttonId           = IndicatorObjPrefix + UniqueButtonID;
   ToggleButtonName   = buttonId;
   IndicatorName      = short_name;
   string btn_g_prefix = "GThickHisto_BT_" + UniqueButtonID + "_";
   g_gvHidden         = btn_g_prefix + IntegerToString(ChartID()) + "_Hidden";

   //--- clean up any old duplicate or phantom buttons
   int total_objs = ObjectsTotal(0, -1, OBJ_BUTTON);
   for(int i = total_objs - 1; i >= 0; i--)
     {
      string bName = ObjectName(0, i, -1, OBJ_BUTTON);
      if(StringFind(bName, UniqueButtonID) >= 0 || StringFind(bName, "GThickHisto_BT") >= 0)
        {
         if(bName != buttonId)
            ObjectDelete(0, bName);
        }
     }

   //--- when parameters are changed by user, clear old global variable
   bool isParamChange = (UninitializeReason() == REASON_PARAMETERS);
   if(isParamChange && g_gvHidden != "")
     {
      GlobalVariableDel(g_gvHidden);
     }

   //--- restore toggle state across timeframe/symbol changes
   bool hasSavedState = false;
   bool savedHidden   = false;

   if(!isParamChange)
     {
      if(ObjectFind(0, buttonId) >= 0)
        {
         string btnTxt = ObjectGetString(0, buttonId, OBJPROP_TEXT);
         if(StringFind(btnTxt, "OFF") >= 0 || StringFind(btnTxt, "Off") >= 0 || StringFind(btnTxt, "off") >= 0)
            savedHidden = true;
         else if(StringFind(btnTxt, "ON") >= 0 || StringFind(btnTxt, "On") >= 0 || StringFind(btnTxt, "on") >= 0)
            savedHidden = false;
         hasSavedState = true;
        }

      if(!hasSavedState && GlobalVariableCheck(g_gvHidden))
        {
         savedHidden   = (GlobalVariableGet(g_gvHidden) > 0.5);
         hasSavedState = true;
        }
     }

   if(hasSavedState)
      IndicatorHidden = savedHidden;
   else if(StringFind(btn_text, "OFF") >= 0 || StringFind(btn_text, "Off") >= 0 || StringFind(btn_text, "off") >= 0)
      IndicatorHidden = true;
   else
      IndicatorHidden = false;

   IndicatorEnabled = !IndicatorHidden;

   if(g_gvHidden != "")
      GlobalVariableSet(g_gvHidden, IndicatorHidden ? 1.0 : 0.0);

   ApplyPlotsStyle();
   CreateToggleButton();
   BringButtonsToFront();

   EventSetTimer(2);
   return INIT_SUCCEEDED;
  }

//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   EventKillTimer();

   if(reason == REASON_REMOVE || reason == REASON_CHARTCLOSE || reason == REASON_PARAMETERS)
     {
      ObjectDelete(0, buttonId);
      ObjectDelete(0, ToggleButtonName);
      if(g_gvHidden != "")
         GlobalVariableDel(g_gvHidden);
     }

   ChartRedraw(0);
  }

//+------------------------------------------------------------------+
//| Chart event handler: toggle button click                         |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
   if(id == CHARTEVENT_OBJECT_CLICK)
     {
      string altId = "_" + UniqueButtonID + IndicatorObjPrefix + "_BT_";
      if(sparam == buttonId || sparam == ToggleButtonName || sparam == altId)
        {
         ToggleIndicatorVisibility();
         return;
        }
     }

   if(id == CHARTEVENT_CHART_CHANGE)
     {
      BringButtonsToFront();
     }
  }

//+------------------------------------------------------------------+
//| Timer: force a recalculation while history is loading            |
//+------------------------------------------------------------------+
void OnTimer()
  {
   if(g_pending && g_retries <= 30)
      ChartSetSymbolPeriod(0, _Symbol, _Period);
  }

//+------------------------------------------------------------------+
//| Load 'count' latest bars of series k                             |
//+------------------------------------------------------------------+
bool LoadSeries(int k,int count)
  {
   if(!g_s[k].available || g_s[k].noHistory) return true;
   ArraySetAsSeries(g_s[k].r, false);
   int got = CopyRates(g_s[k].name, _Period, 0, count, g_s[k].r);
   bool synced = (bool)SeriesInfoInteger(g_s[k].name, _Period, SERIES_SYNCHRONIZED);
   if(got > g_lookback + 1 && (got >= count || synced)) return true;
   if(g_retries > 30) { g_s[k].noHistory = true; ArrayFree(g_s[k].r); return true; }
   return false;
  }

//+------------------------------------------------------------------+
int FindBar(int k,datetime t)
  {
   int n = ArraySize(g_s[k].r);
   if(n == 0 || g_s[k].r[0].time > t) return -1;
   int lo = 0, hi = n - 1;
   while(lo < hi)
     {
      int mid = (lo + hi + 1) / 2;
      if(g_s[k].r[mid].time <= t) lo = mid; else hi = mid - 1;
     }
   return lo;
  }

//+------------------------------------------------------------------+
bool PairChange(int k,datetime t,double &chg)
  {
   if(!g_s[k].available || g_s[k].noHistory) return false;
   int j = FindBar(k, t);
   int L = g_lookback;
   if(j < L) return false;
   double c0 = g_s[k].r[j - L].close, c1 = g_s[k].r[j].close;
   if(c0 <= 0.0) return false;
   if(InpMethod == CSM_PERCENT)
     {
      chg = (c1 - c0) / c0 * 100.0;
      return true;
     }
   double sum = 0.0;
   for(int m = j - L + 1; m <= j; m++)
     {
      double pc = g_s[k].r[m - 1].close;
      sum += MathMax(g_s[k].r[m].high, pc) - MathMin(g_s[k].r[m].low, pc);
     }
   double atr = sum / L;
   if(atr <= 0.0) return false;
   chg = (c1 - c0) / atr;
   return true;
  }

//+------------------------------------------------------------------+
//| Main calculation                                                 |
//+------------------------------------------------------------------+
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[])
  {
   if(rates_total < g_lookback + 2) return 0;
   ArraySetAsSeries(time, false);

   if(ObjectFind(0, buttonId) < 0)
     {
      CreateToggleButton();
      BringButtonsToFront();
     }

   int first = MathMax(0, rates_total - g_bars);
   int start = (prev_calculated == 0) ? first : MathMax(first, prev_calculated - 1);

   if(prev_calculated == 0)
     {
      int drawBegin = first + g_smooth;
      for(int p=0; p<5; p++)
         PlotIndexSetInteger(p, PLOT_DRAW_BEGIN, drawBegin);

      for(int i=0; i<rates_total; i++)
        {
         g_histDark[i]  = EMPTY_VALUE; g_histDarkCol[i]  = 1;
         g_histBase[i]  = EMPTY_VALUE; g_histBaseCol[i]  = 1;
         g_histLight[i] = EMPTY_VALUE; g_histLightCol[i] = 1;
         g_zeroBuf[i]   = EMPTY_VALUE;
         g_usdPlot[i]   = EMPTY_VALUE;
         g_xauRaw[i]    = EMPTY_VALUE;
         g_usdRaw[i]    = EMPTY_VALUE;
        }
     }

   int need = (rates_total - start) + g_lookback + 50;
   bool ready = true;
   for(int k=0; k<=NUSDPAIR; k++)
      if(!LoadSeries(k, need)) ready = false;
   if(!ready)
     {
      g_pending = true; g_retries++;
      return 0;
     }
   g_pending = false;

   for(int i = start; i < rates_total && !IsStopped(); i++)
     {
      double usdSum = 0.0;
      int    usdCnt = 0;
      for(int p=0; p<NUSDPAIR; p++)
        {
         double chg;
         if(!PairChange(p, time[i], chg)) continue;
         usdSum += g_s[p].usdIsBase ? chg : -chg;
         usdCnt++;
        }

      double rawUsd = (usdCnt > 0) ? (usdSum / usdCnt) : EMPTY_VALUE;
      g_usdRaw[i] = rawUsd;

      double g;
      if(rawUsd != EMPTY_VALUE && PairChange(GOLDIDX, time[i], g))
         g_xauRaw[i] = g + rawUsd;
      else
         g_xauRaw[i] = EMPTY_VALUE;
     }

   for(int i = start; i < rates_total && !IsStopped(); i++)
     {
      double sUsd = 0.0, sXau = 0.0;
      int    nUsd = 0,   nXau = 0;
      for(int m = i - g_smooth + 1; m <= i; m++)
        {
         if(m < first) continue;
         double vu = g_usdRaw[m];
         if(vu != EMPTY_VALUE) { sUsd += vu; nUsd++; }
         double vx = g_xauRaw[m];
         if(vx != EMPTY_VALUE) { sXau += vx; nXau++; }
        }

      double usdVal = (nUsd == g_smooth) ? (sUsd / nUsd) : EMPTY_VALUE;
      double xauVal = (nXau == g_smooth) ? (sXau / nXau) : EMPTY_VALUE;

      g_usdPlot[i] = usdVal;
      g_zeroBuf[i] = (i >= first + g_smooth - 1) ? 0.0 : EMPTY_VALUE;

      if(xauVal == EMPTY_VALUE)
        {
         g_histDark[i]  = EMPTY_VALUE; g_histDarkCol[i]  = 1;
         g_histBase[i]  = EMPTY_VALUE; g_histBaseCol[i]  = 1;
         g_histLight[i] = EMPTY_VALUE; g_histLightCol[i] = 1;
         continue;
        }

      double prevXau = (i > first) ? g_histBase[i - 1] : EMPTY_VALUE;
      bool   rising  = (prevXau != EMPTY_VALUE && xauVal > prevXau);
      bool   falling = (prevXau != EMPTY_VALUE && xauVal < prevXau);

      int colIdx = 1;
      if(xauVal > 0.0)
         colIdx = (InpUse4Colors && falling) ? 3 : 0;
      else if(xauVal < 0.0)
         colIdx = (InpUse4Colors && rising)  ? 4 : 2;

      g_histDark[i]  = xauVal; g_histDarkCol[i]  = colIdx;
      g_histBase[i]  = xauVal; g_histBaseCol[i]  = colIdx;
      g_histLight[i] = xauVal; g_histLightCol[i] = colIdx;
     }

   return rates_total;
  }
//+------------------------------------------------------------------+
