//+------------------------------------------------------------------+
//|                                   Gold_Strength(thick_histo).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                          |
//|                                                                  |
//| 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."
#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)

//--- 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;

//+------------------------------------------------------------------+
//| 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);
  }

//+------------------------------------------------------------------+
//| 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);
     }

   IndicatorSetString(INDICATOR_SHORTNAME,
                      StringFormat("Gold Strength (%d, %s, XAU 3D / USD Line)",
                                   g_lookback, InpMethod == CSM_PERCENT ? "%" : "ATR"));
   IndicatorSetInteger(INDICATOR_DIGITS, 3);

   EventSetTimer(2);
   return INIT_SUCCEEDED;
  }

//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   EventKillTimer();
  }

//+------------------------------------------------------------------+
//| 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)
     {
      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;
  }
//+------------------------------------------------------------------+
