//+------------------------------------------------------------------+
//|                                Gold_Strength(gradient_histo).mq5 |
//|                                                       Teddy Meyn |
//+------------------------------------------------------------------+
//| XAUUSD-focused Currency Strength Meter in a separate window:     |
//| - XAU strength rendered as a 4-color slope gradient histogram    |
//|   (JMACD_histo style: Above0 Rising, Above0 Falling,             |
//|   Below0 Falling, Below0 Rising)                                 |
//| - USD strength rendered as a one-color line overlay              |
//|                                                                  |
//| Reads prices only; never opens, modifies or closes trades.       |
//+------------------------------------------------------------------+
#property copyright "Teddy Meyn (Gold Histogram Mod © 2026, Forex-Station)"
#property link      "https://www.mql5.com/en/code/79618"
#property version   "1.00"
#property description "XAUUSD Currency Strength: 4-color slope gradient histogram for Gold (XAU)"
#property description "with a one-color USD strength line in a separate window."
#property description "Reads prices only, never trades."

#property indicator_separate_window
#property indicator_buffers 4
#property indicator_plots   2

//--- Plot 0: XAU strength (auto-scaling + DataWindow; visual bars via gradient bitmaps)
#property indicator_type1   DRAW_HISTOGRAM
#property indicator_color1  clrNONE
#property indicator_width1  1
#property indicator_label1  "XAU"

//--- Plot 1: USD strength (one-color line)
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrDodgerBlue
#property indicator_style2  STYLE_SOLID
#property indicator_width2  2
#property indicator_label2  "USD"

//--- Zero reference level
#property indicator_level1      0.0
#property indicator_levelcolor  clrDimGray
#property indicator_levelstyle  STYLE_DOT
#property indicator_levelwidth  1

//--- 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 "--- USD Line (One Color) ---"
input bool            InpShowUSDLine    = true;          // Show USD Line
input color           InpColUSD         = clrDodgerBlue; // 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 "--- XAU Histogram Outline Settings ---"
input bool            InpAutoAroundLine = false;         // Auto Draw Line Around Histogram
input int             InpValueColor     = 4;             // Level Draw Line Around Histogram (pixels)
input bool            InpAroundLine     = true;          // Draw Line Around Histogram

input group "--- XAU 1: Above Zero & Rising (Bullish Acceleration) ---"
input color           InpLo0            = C'0,139,139';      // Top Gradient (DarkCyan)
input color           InpHi0            = clrWhiteSmoke;     // Bottom Gradient (WhiteSmoke)
input color           InpLn0            = clrLime;           // Outline Color (Lime)
input int             InpOp0            = 160;               // Start Opaque (0..255)
input int             InpOP0            = 48;                // End Opaque (0..255)

input group "--- XAU 2: Above Zero & Falling (Bullish Deceleration) ---"
input color           InpLo1            = C'46,139,87';      // Top Gradient (SeaGreen)
input color           InpHi1            = clrWhiteSmoke;     // Bottom Gradient (WhiteSmoke)
input color           InpLn1            = clrMediumSeaGreen; // Outline Color (MediumSeaGreen)
input int             InpOp1            = 130;               // Start Opaque (0..255)
input int             InpOP1            = 40;                // End Opaque (0..255)

input group "--- XAU 3: Below Zero & Falling (Bearish Acceleration) ---"
input color           InpLo2            = C'236,0,130';      // Peak Gradient (Deep Pink)
input color           InpHi2            = clrWhiteSmoke;     // Zero Line Gradient (WhiteSmoke)
input color           InpLn2            = clrLightCoral;     // Outline Color (LightCoral)
input int             InpOp2            = 144;               // Start Opaque (0..255)
input int             InpOP2            = 64;                // End Opaque (0..255)

input group "--- XAU 4: Below Zero & Rising (Bearish Deceleration) ---"
input color           InpLo3            = C'186,85,211';     // Peak Gradient (MediumOrchid)
input color           InpHi3            = clrWhiteSmoke;     // Zero Line Gradient (WhiteSmoke)
input color           InpLn3            = clrPlum;           // Outline Color (Plum)
input int             InpOp3            = 130;               // Start Opaque (0..255)
input int             InpOP3            = 48;                // End Opaque (0..255)

//--- constants: the 7 USD major pairs + Gold (all that affect USD & XAU strength)
#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];

//--- buffers: 2 plotted buffers + 2 raw calculation buffers
double g_xauPlot[], g_usdPlot[];
double g_xauRaw[],  g_usdRaw[];

//--- gradient palette for the 4 slope states
struct Gradient
  {
   uint R[2], G[2], B[2], O[2], Line;
  };
Gradient g_storage[4];

//--- runtime state
int      g_lookback, g_smooth, g_bars;
int      g_retries     = 0;
bool     g_pending     = false;
long     g_chart_id    = 0;
int      g_subwin      = -1;
int      g_scale       = 0;
bool     g_initialized = false;
bool     g_needFull    = true;
datetime g_lastBarTime = 0;
int      g_ratesTotal  = 0;
string   g_short       = "";
string   g_prefix      = "";
string   g_resNames[];

//+------------------------------------------------------------------+
//| Helper: Find our separate subwindow reliably                     |
//+------------------------------------------------------------------+
int GetIndicatorSubwindow()
  {
   int sub = ChartWindowFind();
   if(sub > 0) return sub;
   if(g_short != "")
     {
      sub = ChartWindowFind(0, g_short);
      if(sub > 0) return sub;
     }
   return sub;
  }

void EnsurePrefix()
  {
   if(g_subwin <= 0)
      g_subwin = GetIndicatorSubwindow();
   string newPfx = "GCSM_SW_" + IntegerToString(g_chart_id) + "_W" + IntegerToString(MathMax(1, g_subwin)) + "_";
   if(g_prefix != "" && g_prefix != newPfx)
      DeleteIndicatorObjects();
   g_prefix = newPfx;
  }

void InitGradientSlot(const int slot,
                      const color lo,const color hi,const color ln,
                      const int opStart,const int opEnd)
  {
   g_storage[slot].R[0] = lo & 0xFF;
   g_storage[slot].G[0] = (lo >> 8)  & 0xFF;
   g_storage[slot].B[0] = (lo >> 16) & 0xFF;
   g_storage[slot].O[0] = (uint)MathMin(MathMax(opStart, 0), 255);

   g_storage[slot].R[1] = hi & 0xFF;
   g_storage[slot].G[1] = (hi >> 8)  & 0xFF;
   g_storage[slot].B[1] = (hi >> 16) & 0xFF;
   g_storage[slot].O[1] = (uint)MathMin(MathMax(opEnd, 0), 255);

   g_storage[slot].Line = (uint)ln;
  }

//+------------------------------------------------------------------+
//| Helper: Scale & Coordinate Conversion                            |
//+------------------------------------------------------------------+
void UpdateScale()
  {
   int chartScale = (int)ChartGetInteger(0, CHART_SCALE);
   switch(chartScale)
     {
      case 5:  g_scale = 3; break;
      case 4:  g_scale = 2; break;
      case 3:  g_scale = 1; break;
      case 2:  g_scale = 1; break;
      default: g_scale = 0; break;
     }
  }

int PriceToY(const double price,const double pMin,const double pMax,const int height)
  {
   if(pMax <= pMin || height <= 0) return 0;
   double ratio = (pMax - price) / (pMax - pMin);
   return (int)(ratio * (double)height);
  }

//+------------------------------------------------------------------+
//| Determine 4-color slope state:                                   |
//| 0: Above Zero & Rising  (Bullish Acceleration)                   |
//| 1: Above Zero & Falling (Bullish Deceleration)                   |
//| 2: Below Zero & Falling (Bearish Acceleration)                   |
//| 3: Below Zero & Rising  (Bearish Deceleration)                   |
//+------------------------------------------------------------------+
int GetHistState(const double val,const double prevVal)
  {
   double prev = (prevVal == EMPTY_VALUE) ? val : prevVal;
   if(val >= 0.0)
      return (val >= prev) ? 0 : 1;
   return (val < prev) ? 2 : 3;
  }

//+------------------------------------------------------------------+
//| Fill pixel buffer with vertical gradient & optional outline      |
//+------------------------------------------------------------------+
void FillMap(uint &MapStorage[],const int iX,const int iY,const Gradient &gColor,const bool invert=false)
  {
   if(iX < 1 || iY < 1) return;
   ArrayResize(MapStorage, iX * iY);

   uint bStart = invert ? gColor.B[1] : gColor.B[0];
   uint bEnd   = invert ? gColor.B[0] : gColor.B[1];
   uint gStart = invert ? gColor.G[1] : gColor.G[0];
   uint gEnd   = invert ? gColor.G[0] : gColor.G[1];
   uint rStart = invert ? gColor.R[1] : gColor.R[0];
   uint rEnd   = invert ? gColor.R[0] : gColor.R[1];
   uint oStart = invert ? gColor.O[1] : gColor.O[0];
   uint oEnd   = invert ? gColor.O[0] : gColor.O[1];

   double dB = (bEnd != bStart && iY > 1) ? ((double)bEnd - (double)bStart) / (double)iY : 0.0;
   double dG = (gEnd != gStart && iY > 1) ? ((double)gEnd - (double)gStart) / (double)iY : 0.0;
   double dR = (rEnd != rStart && iY > 1) ? ((double)rEnd - (double)rStart) / (double)iY : 0.0;
   double dO = (oEnd != oStart && iY > 1) ? ((double)oEnd - (double)oStart) / (double)iY : 0.0;

   bool drawAroundLine = InpAroundLine;
   if(InpAutoAroundLine && iX < InpValueColor)
      drawAroundLine = false;

   if(drawAroundLine && iY >= 2 && iX >= 2)
     {
      for(int i = iY - 2; i > 0; i--)
        {
         uint  bVal = (uint)(bStart + (dB != 0.0 ? (double)i * dB : 0.0));
         uint  gVal = (uint)(gStart + (dG != 0.0 ? (double)i * dG : 0.0));
         uint  rVal = (uint)(rStart + (dR != 0.0 ? (double)i * dR : 0.0));
         uchar oVal = (uchar)(oStart + (dO != 0.0 ? (double)i * dO : 0.0));

         color bodyColor = (color)((bVal << 16) | (gVal << 8) | rVal);
         uint  bodyPixel = ColorToARGB(bodyColor, oVal);
         ArrayFill(MapStorage, iX * i, iX, bodyPixel);

         uint linePixel = ColorToARGB((color)gColor.Line, oVal);
         MapStorage[iX * i]          = linePixel;
         MapStorage[iX * i + iX - 1] = linePixel;
        }

      uint topLinePixel = ColorToARGB((color)gColor.Line, (uchar)oStart);
      ArrayFill(MapStorage, 0, iX, topLinePixel);

      uint botLinePixel = ColorToARGB((color)gColor.Line, (uchar)oEnd);
      ArrayFill(MapStorage, iX * (iY - 1), iX, botLinePixel);
     }
   else
     {
      for(int i = 0; i < iY; i++)
        {
         uint  bVal = (uint)(bStart + (dB != 0.0 ? (double)i * dB : 0.0));
         uint  gVal = (uint)(gStart + (dG != 0.0 ? (double)i * dG : 0.0));
         uint  rVal = (uint)(rStart + (dR != 0.0 ? (double)i * dR : 0.0));
         uchar oVal = (uchar)(oStart + (dO != 0.0 ? (double)i * dO : 0.0));

         color bodyColor = (color)((bVal << 16) | (gVal << 8) | rVal);
         uint  bodyPixel = ColorToARGB(bodyColor, oVal);
         ArrayFill(MapStorage, iX * i, iX, bodyPixel);
        }
     }
  }

void TrackResource(const string resName)
  {
   int n = ArraySize(g_resNames);
   for(int i=0;i<n;i++) if(g_resNames[i]==resName) return;
   ArrayResize(g_resNames, n + 1);
   g_resNames[n] = resName;
  }

void DeleteIndicatorObjects()
  {
   if(g_prefix != "")
      ObjectsDeleteAll(0, g_prefix);
   int n = ArraySize(g_resNames);
   for(int i=0;i<n;i++)
      ResourceFree(g_resNames[i]);
   ArrayFree(g_resNames);
  }

void ResolveSubwindowScale(const int startShift,const int endShift,const int rates_total,
                           double &pMin,double &pMax)
  {
   pMin = ChartGetDouble(0, CHART_PRICE_MIN, g_subwin);
   pMax = ChartGetDouble(0, CHART_PRICE_MAX, g_subwin);
   if(pMax > pMin) return;

   double minV = 0.0, maxV = 0.0;
   for(int s = startShift; s <= endShift; s++)
     {
      int idx = rates_total - 1 - s;
      if(idx < 0 || idx >= rates_total) continue;
      if(g_xauPlot[idx] != EMPTY_VALUE)
        {
         if(g_xauPlot[idx] < minV) minV = g_xauPlot[idx];
         if(g_xauPlot[idx] > maxV) maxV = g_xauPlot[idx];
        }
      if(InpShowUSDLine && g_usdPlot[idx] != EMPTY_VALUE)
        {
         if(g_usdPlot[idx] < minV) minV = g_usdPlot[idx];
         if(g_usdPlot[idx] > maxV) maxV = g_usdPlot[idx];
        }
     }
   if(maxV <= minV)
     {
      minV = -0.05;
      maxV =  0.05;
     }
   double pad = (maxV - minV) * 0.05;
   pMin = minV - pad;
   pMax = maxV + pad;
  }

bool DrawSingleBar(const int shift,const int barIdx,const datetime barTime,const int barLength,
                   const double midChartPrice,const double pMin,const double pMax,const int subwinHeight)
  {
   int total = ArraySize(g_xauPlot);
   if(barIdx < 0 || barIdx >= total) return false;

   double xau = g_xauPlot[barIdx];
   if(xau == EMPTY_VALUE) return false;

   int Cx = 0, dummyY = 0;
   if(!ChartTimePriceToXY(0, 0, barTime, midChartPrice, Cx, dummyY)) return false;
   if(Cx <= 0 || barLength <= 0) return false;

   int barWidth = barLength - g_scale;
   if(barWidth < 1) barWidth = 1;

   int CyZero = PriceToY(0.0, pMin, pMax, subwinHeight);
   int CyVal  = PriceToY(xau, pMin, pMax, subwinHeight);

   int yTop      = MathMin(CyZero, CyVal);
   int yBot      = MathMax(CyZero, CyVal);
   int barHeight = yBot - yTop;
   if(barHeight < 1) barHeight = 1;

   if(yTop < 0)
     {
      barHeight += yTop;
      yTop = 0;
     }
   if(yTop + barHeight > subwinHeight)
      barHeight = subwinHeight - yTop;
   if(barHeight < 1) return false;

   double prevVal   = (barIdx > 0) ? g_xauPlot[barIdx - 1] : xau;
   int    state     = GetHistState(xau, prevVal);
   bool   invertGrd = (xau < 0.0);

   uint MapStorage[];
   FillMap(MapStorage, barWidth, barHeight, g_storage[state], invertGrd);

   string objName = g_prefix + IntegerToString(shift);
   string resName = "::" + g_prefix + "Maps_" + IntegerToString(shift);

   ResourceFree(resName);
   if(!ResourceCreate(resName, MapStorage, barWidth, barHeight, 0, 0, 0, COLOR_FORMAT_ARGB_NORMALIZE))
      return false;
   TrackResource(resName);

   if(ObjectFind(0, objName) < 0)
      ObjectCreate(0, objName, OBJ_BITMAP_LABEL, g_subwin, 0, 0);

   ObjectSetString (0, objName, OBJPROP_BMPFILE, 0, resName);
   ObjectSetInteger(0, objName, OBJPROP_CORNER,     CORNER_LEFT_UPPER);
   ObjectSetInteger(0, objName, OBJPROP_XDISTANCE,  Cx - barWidth / 2);
   ObjectSetInteger(0, objName, OBJPROP_YDISTANCE,  yTop);
   ObjectSetInteger(0, objName, OBJPROP_BACK,       true);
   ObjectSetInteger(0, objName, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, objName, OBJPROP_SELECTED,   false);
   ObjectSetInteger(0, objName, OBJPROP_HIDDEN,     true);
   return true;
  }

void DrawFirst(const datetime barTime,const datetime prevTime,const int rates_total)
  {
   EnsurePrefix();
   if(g_subwin <= 0) return;

   int subwinHeight = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, g_subwin);
   if(subwinHeight <= 0) return;

   double pMin = 0.0, pMax = 0.0;
   ResolveSubwindowScale(0, MathMin(rates_total - 1, 100), rates_total, pMin, pMax);

   double chartMin = ChartGetDouble(0, CHART_PRICE_MIN, 0);
   double chartMax = ChartGetDouble(0, CHART_PRICE_MAX, 0);
   double midChartPrice = (chartMax > chartMin) ? (chartMin + chartMax) * 0.5 : 0.0;

   int Cx = 0, CxP = 0, dummyY = 0;
   if(!ChartTimePriceToXY(0, 0, barTime,  midChartPrice, Cx,  dummyY)) return;
   if(!ChartTimePriceToXY(0, 0, prevTime, midChartPrice, CxP, dummyY)) return;

   int barLength = Cx - CxP;
   if(barLength <= 0) return;

   if(DrawSingleBar(0, rates_total - 1, barTime, barLength, midChartPrice, pMin, pMax, subwinHeight))
      ChartRedraw(0);
  }

bool DrawFull(const int rates_total)
  {
   EnsurePrefix();
   if(g_subwin <= 0) return false;

   UpdateScale();
   int subwinHeight = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, g_subwin);
   if(subwinHeight <= 0) return false;

   int FVB = (int)ChartGetInteger(0, CHART_FIRST_VISIBLE_BAR);
   int VB  = (int)ChartGetInteger(0, CHART_VISIBLE_BARS);
   if(FVB < 0 || VB <= 0) return false;

   int vB         = FVB - VB;
   int startShift = (vB < 0) ? 0 : vB;
   int endShift   = FVB + 3;

   datetime times[];
   ArraySetAsSeries(times, true);
   int copied = CopyTime(_Symbol, _Period, 0, endShift + 3, times);
   if(copied <= 1) return false;

   int timeOffset = 0;
   if(g_lastBarTime > 0 && times[0] > g_lastBarTime)
     {
      while(timeOffset < copied - 1 && times[timeOffset] > g_lastBarTime)
         timeOffset++;
     }

   if(endShift >= copied - 1) endShift = copied - 2;
   if(startShift > endShift)  return false;

   double pMin = 0.0, pMax = 0.0;
   ResolveSubwindowScale(startShift, endShift, rates_total, pMin, pMax);

   double chartMin = ChartGetDouble(0, CHART_PRICE_MIN, 0);
   double chartMax = ChartGetDouble(0, CHART_PRICE_MAX, 0);
   double midChartPrice = (chartMax > chartMin) ? (chartMin + chartMax) * 0.5 : 0.0;

   DeleteIndicatorObjects();

   int lastBarLength = 0;
   int barsDrawn     = 0;

   for(int shift = startShift; shift <= endShift; shift++)
     {
      int alignedShift = shift - timeOffset;
      int barIdx = rates_total - 1 - alignedShift;
      if(alignedShift < 0 || barIdx < 0 || barIdx >= rates_total) continue;
      if(g_xauPlot[barIdx] == EMPTY_VALUE)                         continue;

      int Cx = 0, CxP = 0, dummyY = 0;
      if(!ChartTimePriceToXY(0, 0, times[shift], midChartPrice, Cx, dummyY)) continue;

      int barLength = 0;
      if(ChartTimePriceToXY(0, 0, times[shift + 1], midChartPrice, CxP, dummyY) && Cx > 0 && CxP > 0)
        {
         barLength = Cx - CxP;
         if(barLength > 0) lastBarLength = barLength;
        }
      else if(Cx > 0 && lastBarLength > 0)
        {
         barLength = lastBarLength;
        }
      else
         continue;

      if(DrawSingleBar(shift, barIdx, times[shift], barLength, midChartPrice, pMin, pMax, subwinHeight))
         barsDrawn++;
     }

   ChartRedraw(0);
   return (barsDrawn > 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;

   // Auto-detect prefix/suffix from chart _Symbol if attached directly to Gold (e.g. XAUUSDm, XAUUSD.pro)
   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_chart_id    = ChartID();
   g_lookback    = MathMax(1, InpLookback);
   g_smooth      = MathMax(1, InpSmoothing);
   g_bars        = MathMax(50, InpBars);
   g_retries     = 0;
   g_pending     = false;
   g_initialized = false;
   g_needFull    = true;
   g_lastBarTime = 0;
   g_prefix      = "";
   ArrayFree(g_resNames);

   //--- bind buffers
   SetIndexBuffer(0, g_xauPlot, INDICATOR_DATA);
   SetIndexBuffer(1, g_usdPlot, INDICATOR_DATA);
   SetIndexBuffer(2, g_xauRaw,  INDICATOR_CALCULATIONS);
   SetIndexBuffer(3, g_usdRaw,  INDICATOR_CALCULATIONS);

   //--- Plot 0: XAU (bounds/DataWindow only; 4-color gradient histogram bars rendered via bitmaps)
   PlotIndexSetInteger(0, PLOT_DRAW_TYPE,   DRAW_HISTOGRAM);
   PlotIndexSetInteger(0, PLOT_LINE_COLOR,  clrNONE);
   PlotIndexSetInteger(0, PLOT_LINE_WIDTH,  1);
   PlotIndexSetString (0, PLOT_LABEL,       "XAU");
   PlotIndexSetDouble (0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(0, PLOT_SHOW_DATA,   true);

   //--- Plot 1: USD (one-color line)
   int usdWidth = InpUSDWidth;
   if(InpUSDStyle != STYLE_SOLID && usdWidth > 1)
      usdWidth = 1; // MT5 requires width = 1 to render dash/dot styles
   PlotIndexSetInteger(1, PLOT_DRAW_TYPE,   InpShowUSDLine ? DRAW_LINE : DRAW_NONE);
   PlotIndexSetInteger(1, PLOT_LINE_COLOR,  InpColUSD);
   PlotIndexSetInteger(1, PLOT_LINE_STYLE,  InpUSDStyle);
   PlotIndexSetInteger(1, PLOT_LINE_WIDTH,  usdWidth);
   PlotIndexSetString (1, PLOT_LABEL,       "USD");
   PlotIndexSetDouble (1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(1, PLOT_SHOW_DATA,   InpShowUSDLine);

   //--- initialize 4-color slope gradient states
   InitGradientSlot(0, InpLo0, InpHi0, InpLn0, InpOp0, InpOP0);
   InitGradientSlot(1, InpLo1, InpHi1, InpLn1, InpOp1, InpOP1);
   InitGradientSlot(2, InpLo2, InpHi2, InpLn2, InpOp2, InpOP2);
   InitGradientSlot(3, InpLo3, InpHi3, InpLn3, InpOp3, InpOP3);

   //--- 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);
     }

   g_short = StringFormat("Gold Strength (%d, %s, XAU Histo / USD Line)",
                          g_lookback, InpMethod == CSM_PERCENT ? "%" : "ATR");
   IndicatorSetString(INDICATOR_SHORTNAME, g_short);
   IndicatorSetInteger(INDICATOR_DIGITS, 3);

   g_subwin = GetIndicatorSubwindow();
   EnsurePrefix();
   UpdateScale();

   EventSetTimer(2);
   return INIT_SUCCEEDED;
  }

//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   EventKillTimer();
   DeleteIndicatorObjects();
   ChartRedraw(0);
  }

//+------------------------------------------------------------------+
//| 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);

   int first = MathMax(0, rates_total - g_bars);
   int start = (prev_calculated == 0) ? first : MathMax(first, prev_calculated - 1);

   if(prev_calculated == 0)
     {
      g_needFull = true;
      PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, first + g_smooth);
      PlotIndexSetInteger(1, PLOT_DRAW_BEGIN, first + g_smooth);
      for(int i=0;i<rates_total;i++)
        {
         g_xauPlot[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; 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; 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++; }
        }
      g_usdPlot[i] = (nUsd == g_smooth) ? (sUsd / nUsd) : EMPTY_VALUE;
      g_xauPlot[i] = (nXau == g_smooth) ? (sXau / nXau) : EMPTY_VALUE;
     }

   g_initialized = true;
   g_ratesTotal  = rates_total;

   datetime curBarTime  = time[rates_total - 1];
   datetime prevBarTime = (rates_total >= 2) ? time[rates_total - 2] : 0;

   if(g_needFull || g_lastBarTime != curBarTime)
     {
      g_lastBarTime = curBarTime;
      if(DrawFull(rates_total))
         g_needFull = false;
     }
   else
     {
      DrawFirst(curBarTime, prevBarTime, rates_total);
     }

   return rates_total;
  }

//+------------------------------------------------------------------+
//| Chart Events: redraw bitmap histogram on zoom/scroll/resize      |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
  {
   if(id == CHARTEVENT_CHART_CHANGE && g_initialized && g_ratesTotal > 0)
      DrawFull(g_ratesTotal);
  }
//+------------------------------------------------------------------+

