//+------------------------------------------------------------------+
//|                                    Currency_Strength_Meter(sw).mq5 |
//|                                                       Teddy Meyn |
//+------------------------------------------------------------------+
//| Separate-window lines for the relative strength of the 8 major   |
//| currencies (USD EUR GBP JPY CHF CAD AUD NZD) built from the 28   |
//| major cross pairs, with an optional gold (XAU) line.             |
//|                                                                  |
//| Companion to Currency_Strength_Meter(dashboard).mq5 (main chart).|
//| Reads prices only; never opens, modifies or closes trades.       |
//+------------------------------------------------------------------+
#property copyright "Teddy Meyn (Separate Window © 2026, Forex-Station)"
#property link      "https://www.mql5.com/en/code/79618"
#property version   "1.00"
#property description "Separate-window Currency Strength lines (USD EUR GBP JPY CHF CAD AUD NZD + XAU)"
#property description "built from the 28 major pairs. Companion to Currency_Strength_Meter(dashboard)."
#property description "Reads prices only, never trades."

#property indicator_separate_window
#property indicator_buffers 18
#property indicator_plots   9
#property indicator_level1  0.0
#property indicator_levelcolor clrDimGray
#property indicator_levelstyle STYLE_DOT

//--- 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"
input string          InpPrefix     = "";          // Symbol prefix (e.g. "m.")
input string          InpSuffix     = "";          // Symbol suffix (e.g. ".pro", "m")
input bool            InpShowXAU    = true;        // Show gold (XAU) line from XAUUSD
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 "Lines"
input color           InpColUSD     = clrLime;         // USD colour
input color           InpColEUR     = clrDodgerBlue;   // EUR colour
input color           InpColGBP     = clrRed;          // GBP colour
input color           InpColJPY     = clrWhite;        // JPY colour
input color           InpColCHF     = clrHotPink;      // CHF colour
input color           InpColCAD     = clrOrange;       // CAD colour
input color           InpColAUD     = clrMediumOrchid; // AUD colour
input color           InpColNZD     = clrAqua;         // NZD colour
input color           InpColXAU     = clrGold;         // XAU colour
input bool            InpChartPairOnly = true;         // Show only chart symbol's 2 lines (e.g. EUR & USD)
input bool            InpHighlight  = true;            // Thicker lines for the chart symbol's currencies
input int             InpWidthNorm  = 1;               // Normal line width
input int             InpWidthHigh  = 3;               // Highlighted line width

//--- constants
#define NCUR   8
#define NPLOT  9
#define NPAIR  28
#define XAU    8

string g_cur[NPLOT] = {"USD","EUR","GBP","JPY","CHF","CAD","AUD","NZD","XAU"};

//--- the 28 major pairs: base and quote currency index into g_cur
string g_pairBase[NPAIR]  = {"EUR","GBP","AUD","NZD","USD","USD","USD",
                             "EUR","EUR","EUR","EUR","EUR","EUR",
                             "GBP","GBP","GBP","GBP","GBP",
                             "AUD","AUD","AUD","AUD",
                             "NZD","NZD","NZD",
                             "CAD","CAD","CHF"};
string g_pairQuote[NPAIR] = {"USD","USD","USD","USD","JPY","CHF","CAD",
                             "GBP","JPY","CHF","CAD","AUD","NZD",
                             "JPY","CHF","CAD","AUD","NZD",
                             "JPY","CHF","CAD","NZD",
                             "JPY","CHF","CAD",
                             "JPY","CHF","JPY"};

//--- per-symbol price storage (28 pairs + gold)
class CSeries
  {
public:
   string            name;      // full broker symbol name
   int               base;      // currency index of base
   int               quote;     // currency index of quote
   bool              available; // symbol exists at the broker
   bool              noHistory; // gave up waiting for history
   MqlRates          r[];       // rates, oldest first
  };
CSeries g_s[NPAIR+1];

//--- buffers: 9 plotted lines + 9 raw (unsmoothed) values
double g_plot0[],g_plot1[],g_plot2[],g_plot3[],g_plot4[],g_plot5[],g_plot6[],g_plot7[],g_plot8[];
double g_raw0[],g_raw1[],g_raw2[],g_raw3[],g_raw4[],g_raw5[],g_raw6[],g_raw7[],g_raw8[];

int    g_lookback, g_smooth, g_bars;
int    g_retries   = 0;       // history wait counter
bool   g_pending   = false;   // waiting for history
int    g_hlBase    = -1, g_hlQuote = -1;
bool   g_plotVisible[NPLOT];

//+------------------------------------------------------------------+
//| Helpers to address the buffers by index                          |
//+------------------------------------------------------------------+
void SetPlot(int c,int i,double v)
  {
   switch(c)
     {
      case 0: g_plot0[i]=v; return; case 1: g_plot1[i]=v; return; case 2: g_plot2[i]=v; return;
      case 3: g_plot3[i]=v; return; case 4: g_plot4[i]=v; return; case 5: g_plot5[i]=v; return;
      case 6: g_plot6[i]=v; return; case 7: g_plot7[i]=v; return;
     }
   g_plot8[i]=v;
  }
double GetRaw(int c,int i)
  {
   switch(c)
     {
      case 0: return g_raw0[i]; case 1: return g_raw1[i]; case 2: return g_raw2[i];
      case 3: return g_raw3[i]; case 4: return g_raw4[i]; case 5: return g_raw5[i];
      case 6: return g_raw6[i]; case 7: return g_raw7[i];
     }
   return g_raw8[i];
  }
void SetRaw(int c,int i,double v)
  {
   switch(c)
     {
      case 0: g_raw0[i]=v; return; case 1: g_raw1[i]=v; return; case 2: g_raw2[i]=v; return;
      case 3: g_raw3[i]=v; return; case 4: g_raw4[i]=v; return; case 5: g_raw5[i]=v; return;
      case 6: g_raw6[i]=v; return; case 7: g_raw7[i]=v; return;
     }
   g_raw8[i]=v;
  }

int CurIndex(string c)
  {
   for(int i=0;i<NPLOT;i++) if(g_cur[i]==c) return i;
   return -1;
  }

color CurColor(int c)
  {
   switch(c)
     {
      case 0: return InpColUSD; case 1: return InpColEUR; case 2: return InpColGBP;
      case 3: return InpColJPY; case 4: return InpColCHF; case 5: return InpColCAD;
      case 6: return InpColAUD; case 7: return InpColNZD;
     }
   return InpColXAU;
  }

//+------------------------------------------------------------------+
//| Initialisation                                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   g_lookback = MathMax(1, InpLookback);
   g_smooth   = MathMax(1, InpSmoothing);
   g_bars     = MathMax(50, InpBars);

   //--- bind buffers
   SetIndexBuffer(0,g_plot0,INDICATOR_DATA);  SetIndexBuffer(1,g_plot1,INDICATOR_DATA);
   SetIndexBuffer(2,g_plot2,INDICATOR_DATA);  SetIndexBuffer(3,g_plot3,INDICATOR_DATA);
   SetIndexBuffer(4,g_plot4,INDICATOR_DATA);  SetIndexBuffer(5,g_plot5,INDICATOR_DATA);
   SetIndexBuffer(6,g_plot6,INDICATOR_DATA);  SetIndexBuffer(7,g_plot7,INDICATOR_DATA);
   SetIndexBuffer(8,g_plot8,INDICATOR_DATA);
   SetIndexBuffer(9,g_raw0,INDICATOR_CALCULATIONS);  SetIndexBuffer(10,g_raw1,INDICATOR_CALCULATIONS);
   SetIndexBuffer(11,g_raw2,INDICATOR_CALCULATIONS); SetIndexBuffer(12,g_raw3,INDICATOR_CALCULATIONS);
   SetIndexBuffer(13,g_raw4,INDICATOR_CALCULATIONS); SetIndexBuffer(14,g_raw5,INDICATOR_CALCULATIONS);
   SetIndexBuffer(15,g_raw6,INDICATOR_CALCULATIONS); SetIndexBuffer(16,g_raw7,INDICATOR_CALCULATIONS);
   SetIndexBuffer(17,g_raw8,INDICATOR_CALCULATIONS);

   //--- currencies of the chart symbol (for highlighting & 2-line filter)
   string s    = _Symbol;
   string pfx  = InpPrefix;
   string gSym = InpGoldSymbol;
   StringToUpper(s);
   StringToUpper(pfx);
   StringToUpper(gSym);
   if(StringLen(pfx)>0 && StringFind(s,pfx)==0) s = StringSubstr(s,StringLen(pfx));
   if(StringLen(gSym)>0 && StringFind(s,gSym)==0)
     {
      g_hlBase  = XAU;
      g_hlQuote = 0;
     }
   else
     {
      g_hlBase  = CurIndex(StringSubstr(s,0,3));
      g_hlQuote = CurIndex(StringSubstr(s,3,3));
      if(g_hlBase<0 || g_hlQuote<0)
        {
         string bCur = SymbolInfoString(_Symbol,SYMBOL_CURRENCY_BASE);
         string qCur = SymbolInfoString(_Symbol,SYMBOL_CURRENCY_PROFIT);
         StringToUpper(bCur);
         StringToUpper(qCur);
         if(g_hlBase<0)  g_hlBase  = (StringLen(gSym)>=3 && bCur==StringSubstr(gSym,0,3)) ? XAU : CurIndex(bCur);
         if(g_hlQuote<0) g_hlQuote = CurIndex(qCur);
        }
     }

   //--- plot styling
   bool hasChartCur = (g_hlBase>=0 || g_hlQuote>=0);
   for(int c=0;c<NPLOT;c++)
     {
      bool xauDisabled = (c==XAU && !InpShowXAU);
      bool pairMatch   = (c==g_hlBase || c==g_hlQuote);
      bool showPlot    = !xauDisabled && (!InpChartPairOnly || !hasChartCur || pairMatch);
      g_plotVisible[c] = showPlot;

      bool hl = InpHighlight && pairMatch;
      PlotIndexSetInteger(c,PLOT_DRAW_TYPE,showPlot ? DRAW_LINE : DRAW_NONE);
      PlotIndexSetInteger(c,PLOT_LINE_COLOR,CurColor(c));
      PlotIndexSetInteger(c,PLOT_LINE_WIDTH,hl ? InpWidthHigh : InpWidthNorm);
      PlotIndexSetInteger(c,PLOT_LINE_STYLE,STYLE_SOLID);
      PlotIndexSetString(c,PLOT_LABEL,g_cur[c]);
      PlotIndexSetDouble(c,PLOT_EMPTY_VALUE,EMPTY_VALUE);
      PlotIndexSetInteger(c,PLOT_SHOW_DATA,showPlot);
     }

   //--- resolve symbols
   for(int p=0;p<NPAIR;p++)
     {
      g_s[p].name  = InpPrefix + g_pairBase[p] + g_pairQuote[p] + InpSuffix;
      g_s[p].base  = CurIndex(g_pairBase[p]);
      g_s[p].quote = CurIndex(g_pairQuote[p]);
     }
   g_s[NPAIR].name  = InpPrefix + InpGoldSymbol + InpSuffix;
   g_s[NPAIR].base  = XAU;
   g_s[NPAIR].quote = 0;
   for(int k=0;k<=NPAIR;k++)
     {
      bool custom=false;
      g_s[k].available = (k<NPAIR || InpShowXAU) && SymbolExist(g_s[k].name,custom);
      g_s[k].noHistory = false;
      if(g_s[k].available) SymbolSelect(g_s[k].name,true);
     }

   string pairTag = "";
   if(InpChartPairOnly && hasChartCur)
     {
      if(g_hlBase>=0 && g_hlQuote>=0 && g_hlBase!=g_hlQuote)
         pairTag = ", " + g_cur[g_hlBase] + "/" + g_cur[g_hlQuote];
      else if(g_hlBase>=0)
         pairTag = ", " + g_cur[g_hlBase];
      else if(g_hlQuote>=0)
         pairTag = ", " + g_cur[g_hlQuote];
     }
   IndicatorSetString(INDICATOR_SHORTNAME, StringFormat("Currency Strength (%d, %s%s)", g_lookback, InpMethod==CSM_PERCENT ? "%" : "ATR", pairTag));
   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)
     {
      for(int c=0;c<NPLOT;c++)
        {
         PlotIndexSetInteger(c,PLOT_DRAW_BEGIN,first+g_smooth);
         for(int i=0;i<rates_total;i++) { SetPlot(c,i,EMPTY_VALUE); SetRaw(c,i,EMPTY_VALUE); }
        }
     }

   int need = (rates_total-start) + g_lookback + 50;
   bool ready = true;
   for(int k=0;k<=NPAIR;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 sum[NCUR]; int cnt[NCUR];
      ArrayInitialize(sum,0.0); ArrayInitialize(cnt,0);
      for(int p=0;p<NPAIR;p++)
        {
         double chg;
         if(!PairChange(p,time[i],chg)) continue;
         sum[g_s[p].base]  += chg; cnt[g_s[p].base]++;
         sum[g_s[p].quote] -= chg; cnt[g_s[p].quote]++;
        }
      for(int c=0;c<NCUR;c++) SetRaw(c,i,cnt[c]>0 ? sum[c]/cnt[c] : EMPTY_VALUE);

      double g;
      if(InpShowXAU && cnt[0]>0 && PairChange(NPAIR,time[i],g)) SetRaw(XAU,i,g + sum[0]/cnt[0]);
      else SetRaw(XAU,i,EMPTY_VALUE);
     }

   for(int c=0;c<NPLOT;c++)
     {
      if(!g_plotVisible[c])
        {
         for(int i=start;i<rates_total;i++) SetPlot(c,i,EMPTY_VALUE);
         continue;
        }
      for(int i=start;i<rates_total;i++)
        {
         double s=0.0; int n=0;
         for(int m=i-g_smooth+1;m<=i;m++)
           {
            if(m<first) continue;
            double v=GetRaw(c,m);
            if(v==EMPTY_VALUE) continue;
            s+=v; n++;
           }
         SetPlot(c,i,(n==g_smooth) ? s/n : EMPTY_VALUE);
        }
     }

   return rates_total;
  }
//+------------------------------------------------------------------+
