//+------------------------------------------------------------------+
//|                                                     XU-MA v3.mq5 |
//|   MQL5 port of the MQL4 indicator "XU-MA v3" (XARD UNIVERSE)     |
//|   Moving averages replaced by the Jurik filter (mladen)          |
//|   TREND / SIGNAL lines selectable on a higher timeframe (MTF)    |
//+------------------------------------------------------------------+
#property link        "https://forex-station.com/viewtopic.php?p=1295409935#p1295409935"
#property version     "3.00"
#property description "[XU-MA v3] + MACD-histogram colour match arrows"
#property description "THIS IS A FREE INDICATOR"
#property description " "
#property description "Welcome to XARD UNIVERSE"
#property description "Let light shine out of darkness and illuminate your world"
#property description "and with this freedom leave behind your cave of denial"

#property indicator_chart_window
#property indicator_buffers 27
#property indicator_plots   9

// plot 0 : candle wick   (high/low,  3 colours)   buffers 0,1,2
// plot 1 : candle body   (open/close,3 colours)   buffers 3,4,5
// plot 2 : daily/weekly open line                 buffer  6
// plot 3 : TREND background line                  buffer  7
// plot 4 : TREND line (up/down colour)            buffers 8,9
// plot 5 : SIGNAL background line                 buffer  10
// plot 6 : SIGNAL line (up/down colour)           buffers 11,12
// plot 7 : MATCH arrow UP   (histogram blue + candle blue)   buffer 13
// plot 8 : MATCH arrow DOWN (histogram red  + candle red )   buffer 14
// calc   : trend, signal, xtrend, xage                       buffers 15,16,17,18
// calc   : histogram colour engine (xuSig, EMAs, ZigZag, Jurik MACD) buffers 19..26
#property indicator_type1 DRAW_COLOR_HISTOGRAM2
#property indicator_type2 DRAW_COLOR_HISTOGRAM2
#property indicator_type3 DRAW_LINE
#property indicator_type4 DRAW_LINE
#property indicator_type5 DRAW_COLOR_LINE
#property indicator_type6 DRAW_LINE
#property indicator_type7 DRAW_COLOR_LINE
#property indicator_type8 DRAW_ARROW
#property indicator_type9 DRAW_ARROW

#define ID "XUMA_"

//--- applied prices of the histogram colour engine (same list as the MACD indicator)
enum enPrices
  {
   pr_close,      // Close
   pr_open,       // Open
   pr_high,       // High
   pr_low,        // Low
   pr_median,     // Median
   pr_typical,    // Typical
   pr_weighted,   // Weighted
   pr_average,    // Average (high+low+open+close)/4
   pr_medianb,    // Average median body (open+close)/2
   pr_tbiased,    // Trend biased price
   pr_haclose,    // Heiken ashi close
   pr_haopen ,    // Heiken ashi open
   pr_hahigh,     // Heiken ashi high
   pr_halow,      // Heiken ashi low
   pr_hamedian,   // Heiken ashi median
   pr_hatypical,  // Heiken ashi typical
   pr_haweighted, // Heiken ashi weighted
   pr_haaverage,  // Heiken ashi average
   pr_hamedianb,  // Heiken ashi median body
   pr_hatbiased   // Heiken ashi trend biased price
  };

enum ENUM_ZZ_MODE
  {
   ZZ_MODE_DEPTH = 0,   // Depth ZigZag
   ZZ_MODE_JURIK = 1    // Jurik MACD centre-line fixation
  };

enum ENUM_ARROW_TYPE
  {
   ARW_233_234 = 0,     // Arrow style 1 (233 / 234)
   ARW_225_226 = 1,     // Arrow style 2 (225 / 226)
   ARW_241_242 = 2,     // Arrow style 3 (241 / 242)
   ARW_217_218 = 3,     // Arrow style 4 (217 / 218)
   ARW_CIRCLE  = 4,     // Circle (108)
   ARW_DOT     = 5,     // Dot (159)
   ARW_CUSTOM  = 6      // Custom Wingdings codes (see below)
  };

//+------------------------------------------------------------------+
input group "<<<==== [01] Candle Settings ====>>>"
input bool            showCANDLES = true;
input int             cWick       = 1;
input color           CandleUp    = C'96,170,204';
input color           CandleWt    = clrWhite;
input color           CandleDn    = C'255,140,255';

input group "<<<==== [02] Openline Settings ====>>>"
input bool            showDOP     = false;
input int             DOPwidth    = 5;
input ENUM_TIMEFRAMES DOPtf       = PERIOD_D1;
input color           DOPclr      = C'60,60,60';

input group "<<<==== [03] TREND Settings ====>>>"
input bool              showTREND  = false;
input color             TRENDupclr = clrBlue;
input color             TRENDdnclr = clrCrimson;
input color             Tbgdclr    = C'100,130,160';
input ENUM_TIMEFRAMES   TRENDtf    = PERIOD_H1;        // TREND timeframe (current = chart)
input int               TRENDper   = 7;
input int               TRENDshft  = 0;
input double            TRENDphase = 0;          // Jurik phase (-100 .. +100)
input ENUM_APPLIED_PRICE TRENDtype = PRICE_MEDIAN;
input int               TRENDwidth = 7;

input group "<<<==== [04] SIGNAL Settings ====>>>"
input bool              showSIGNAL  = false;
input color             SIGNALupclr = clrBlue;
input color             SIGNALdnclr = clrCrimson;
input color             Sbgdclr     = C'100,130,160';
input ENUM_TIMEFRAMES   SIGNALtf    = PERIOD_H1;      // SIGNAL timeframe (current = chart)
input int               SIGNALper   = 3;
input int               SIGNALshft  = 0;
input double            SIGNALphase = 0;         // Jurik phase (-100 .. +100)
input ENUM_APPLIED_PRICE SIGNALtype = PRICE_MEDIAN;
input int               SIGNALwidth = 4;

input group "<<<==== [05] BGDzones Settings ====>>>"
input bool            showBGDzones = true;
input color           ColorUp      = C'53,72,110';
input color           ColorDown    = C'120,63,82';
input color           ColorWait    = C'91,103,112';
input int             ZonesMaxBars = 5000;      // limit zones to last N bars (0 = all)

input group "<<<==== [06] BOXtxt Settings ====>>>"
input bool            showBOXtxt  = false;
input bool            showSig     = false;
input color           clrW        = clrGray;
input color           clrB        = clrDeepSkyBlue;
input color           clrS        = clrOrchid;
input int             moveTxtLR   = 0;
input int             moveTxtUD   = 0;

input group "<<<==== [07] Alert Settings ====>>>"
input bool            AlertsOn        = false;
input bool            AlertsOnCurrent = true;
input bool            AlertsMessage   = true;
input bool            AlertsSound     = false;
input bool            alertsNotify    = true;
input bool            AlertsEmail     = false;
input string          soundfile       = "alert1.wav";

input group "<<<==== [08] MTF Settings ====>>>"
input bool            MTFclosedBar    = false;     // use last CLOSED higher-TF bar (no repaint)

input group "<<<==== [09] Period Scaling ====>>>"
input bool            ScalePerByTF    = false;     // true = multiply TRENDper/SIGNALper by M1:5 M5:3 M15:4 M30:2 H1:1

input group "<<<==== [11] HTF EMA Candle Filter ====>>>"
// price ABOVE the EMA -> candles that would be CandleDn (red)  are painted CandleWt (white)
// price BELOW the EMA -> candles that would be CandleUp (blue) are painted CandleWt (white)
input bool              EMAFilterOn      = true;
input ENUM_TIMEFRAMES   EMAFilterTF      = PERIOD_H1;   // EMA timeframe (current = chart)
input int               EMAFilterPer     = 50;          // EMA period
input ENUM_APPLIED_PRICE EMAFilterPrice  = PRICE_CLOSE; // EMA applied price
input bool              EMAFilterClosed  = false;       // true = use last CLOSED higher-TF EMA value (no repaint)

input group "<<<==== [12] Histogram colour engine (from color MACD 3D XU MA) ====>>>"
// The MACD sub-window histogram is blue / red / white. Its colour is rebuilt here, bar by bar, with
// exactly the same logic (EMA fast/slow + ZigZag or Jurik MACD centre line) so it can be compared with the candle.
input bool            AutoEMA_TF      = false;          // Auto EMA time frame from chart (H4>D1, H1>H4, M15>H1, M5>M15, M1>M5)
input ENUM_TIMEFRAMES EMA4_TF         = PERIOD_H4;      // Fast EMA time frame (manual)
input int             EMA4per         = 1;              // Fast EMA period
input ENUM_TIMEFRAMES EMAper_TF       = PERIOD_H4;      // Slow EMA time frame (manual)
input int             EMAper          = 4;              // Slow EMA period
input ENUM_ZZ_MODE    ZZ_Mode         = ZZ_MODE_JURIK;  // Flip source (Depth ZigZag / Jurik MACD centre line)
input int             ZZ_Depth        = 176;            // Depth ZigZag depth (used in Depth mode)
input ENUM_TIMEFRAMES JurikTF         = PERIOD_H4;      // Jurik MACD time frame
input int             JurikFast       = 2;              // Jurik MACD fast period
input int             JurikSlow       = 26;             // Jurik MACD slow period
input double          JurikPhase      = 0;              // Jurik smoothing phase (-100..100)
input enPrices        JurikPrice      = pr_close;       // Jurik MACD applied price

input group "<<<==== [13] Histogram / Candle MATCH arrows ====>>>"
// histogram BLUE + candle BLUE  -> UP   arrow on the FIRST candle of the match (below the candle)
// histogram RED  + candle RED   -> DOWN arrow on the FIRST candle of the match (above the candle)
input bool            ShowMatchArrows = true;           // Draw the match arrows (also switches the histogram engine on/off)
input ENUM_ARROW_TYPE ArrowType       = ARW_233_234;    // Arrow type
input int             ArrowCodeUp     = 233;            // Custom Wingdings code UP   (used when type = Custom)
input int             ArrowCodeDn     = 234;            // Custom Wingdings code DOWN (used when type = Custom)
input int             ArrowSize       = 3;              // Arrow size (1-5)
input int             ArrowOffsetPx   = 10;             // Distance from the candle (pixels)
input color           ArrowUpClr      = clrDodgerBlue;  // UP arrow colour
input color           ArrowDnClr      = clrRed;         // DOWN arrow colour

input group "<<<==== [10] Logging ====>>>"
input bool            LogFlips        = false;     // print every flip to the Experts tab

//+------------------------------------------------------------------+
//| Jurik filter (mladen) - one instance keeps the state of one line |
//| Same maths as iSmooth() of "Jurik filter.mq5", state stored in a |
//| flat array: 10 values per bar, the filter output is slot 4       |
//+------------------------------------------------------------------+
#define JK_BSMAX  5
#define JK_BSMIN  6
#define JK_VOLTY  7
#define JK_VSUM   8
#define JK_AVOLTY 9
#define JK_OUT    4

class CJurik
  {
private:
   double m_w[];

public:
   void Reset() { ArrayFree(m_w); }

   //--- compute bar r (must be called in ascending bar order)
   double Calc(const int r,double price,const double length,const double phase,const int bars)
     {
      if(ArraySize(m_w)!=bars*10) ArrayResize(m_w,bars*10,10*512);
      //--- bad input (EMPTY_VALUE / NaN / 0 from a half-synchronised bar) must never enter the recursion:
      //    one NaN in this IIR filter would stay in every later bar until the terminal is restarted
      if(price==EMPTY_VALUE || price==0.0 || !MathIsValidNumber(price))
         price=(r>0 && MathIsValidNumber(m_w[(r-1)*10+JK_OUT]))?m_w[(r-1)*10+JK_OUT]:0.0;

      int o=r*10;
      if(r==0)
        {
         for(int k=0;k<7;k++)  m_w[o+k]=price;
         for(int k=7;k<10;k++) m_w[o+k]=0;
         return(price);
        }
      int p=o-10;                                   // previous bar

      double len1   = MathMax(MathLog(MathSqrt(0.5*(length-1)))/MathLog(2.0)+2.0,0);
      double pow1   = MathMax(len1-2.0,0.5);
      double del1   = price-m_w[p+JK_BSMAX];
      double del2   = price-m_w[p+JK_BSMIN];
      double div    = 1.0/(10.0+10.0*(MathMin(MathMax(length-10,0),100))/100);
      int    forBar = (int)MathMin(r,10);

      double vol=0;
      if(MathAbs(del1)>MathAbs(del2)) vol=MathAbs(del1);
      if(MathAbs(del1)<MathAbs(del2)) vol=MathAbs(del2);
      m_w[o+JK_VOLTY]=vol;
      m_w[o+JK_VSUM ]=m_w[p+JK_VSUM]+(vol-m_w[(r-forBar)*10+JK_VOLTY])*div;

      m_w[o+JK_AVOLTY]=m_w[p+JK_AVOLTY]+(2.0/(MathMax(4.0*length,30)+1.0))*(m_w[o+JK_VSUM]-m_w[p+JK_AVOLTY]);
      double dVolty;
      if(m_w[o+JK_AVOLTY]>0) dVolty=m_w[o+JK_VOLTY]/m_w[o+JK_AVOLTY]; else dVolty=0;
      if(dVolty>MathPow(len1,1.0/pow1)) dVolty=MathPow(len1,1.0/pow1);
      if(dVolty<1)                      dVolty=1.0;

      double pow2=MathPow(dVolty,pow1);
      double len2=MathSqrt(0.5*(length-1))*len1;
      double Kv  =MathPow(len2/(len2+1),MathSqrt(pow2));

      if(del1>0) m_w[o+JK_BSMAX]=price; else m_w[o+JK_BSMAX]=price-Kv*del1;
      if(del2<0) m_w[o+JK_BSMIN]=price; else m_w[o+JK_BSMIN]=price-Kv*del2;

      double R    =MathMax(MathMin(phase,100),-100)/100.0+1.5;
      double beta =0.45*(length-1)/(0.45*(length-1)+2);
      double alpha=MathPow(beta,pow2);

      m_w[o+0]=price+alpha*(m_w[p+0]-price);
      m_w[o+1]=(price-m_w[o+0])*(1-beta)+beta*m_w[p+1];
      m_w[o+2]=(m_w[o+0]+R*m_w[o+1]);
      m_w[o+3]=(m_w[o+2]-m_w[p+4])*MathPow((1-alpha),2)+MathPow(alpha,2)*m_w[p+3];
      m_w[o+4]=(m_w[p+4]+m_w[o+3]);

      //--- self-heal: if anything went non-finite, restart the filter from the current price
      bool bad=false;
      for(int k=0;k<10;k++) if(!MathIsValidNumber(m_w[o+k])) { bad=true; break; }
      if(bad)
        {
         for(int k=0;k<7;k++)  m_w[o+k]=price;
         for(int k=7;k<10;k++) m_w[o+k]=0;
        }
      return(m_w[o+JK_OUT]);
     }

   //--- filter value of bar idx (EMPTY_VALUE outside the calculated range)
   double Get(const int idx,const int bars) const
     {
      if(idx<0 || idx>=bars || ArraySize(m_w)<(idx+1)*10) return(EMPTY_VALUE);
      return(m_w[idx*10+JK_OUT]);
     }
  };

//+------------------------------------------------------------------+
//| Price selected by ENUM_APPLIED_PRICE                             |
//+------------------------------------------------------------------+
double AppPrice(const ENUM_APPLIED_PRICE t,const double o,const double h,const double l,const double c)
  {
   switch(t)
     {
      case PRICE_OPEN:     return(o);
      case PRICE_HIGH:     return(h);
      case PRICE_LOW:      return(l);
      case PRICE_MEDIAN:   return((h+l)/2.0);
      case PRICE_TYPICAL:  return((h+l+c)/3.0);
      case PRICE_WEIGHTED: return((h+l+c+c)/4.0);
      default:             return(c);
     }
  }

//+------------------------------------------------------------------+
//| Binary searches on ascending time arrays                         |
//+------------------------------------------------------------------+
int BsFirstGE(const datetime &a[],const int n,const datetime v)   // first idx with a[idx]>=v (n if none)
  {
   int lo=0,hi=n;
   while(lo<hi) { int mid=(lo+hi)>>1; if(a[mid]<v) lo=mid+1; else hi=mid; }
   return(lo);
  }
int BsLastLE(const datetime &a[],const int n,const datetime v)    // last idx with a[idx]<=v (-1 if none)
  {
   int lo=0,hi=n;
   while(lo<hi) { int mid=(lo+hi)>>1; if(a[mid]<=v) lo=mid+1; else hi=mid; }
   return(lo-1);
  }

//+------------------------------------------------------------------+
//| One line (High / Low / applied price Jurik filters) calculated   |
//| on its own timeframe and mapped onto the chart bars              |
//+------------------------------------------------------------------+
class CMtfJurik
  {
private:
   ENUM_TIMEFRAMES    m_tf;
   int                m_len;
   double             m_phase;
   ENUM_APPLIED_PRICE m_price;
   bool               m_closed;
   CJurik             m_jh,m_jl,m_jt;
   datetime           m_time[];            // times of the higher-TF bars
   int                m_n;                 // higher-TF bars calculated
   datetime           m_first;             // time of the oldest higher-TF bar
   double             m_mh[],m_ml[],m_mt[];// values mapped to chart bars

public:
   void Init(const ENUM_TIMEFRAMES tf,const int len,const double phase,
             const ENUM_APPLIED_PRICE price,const bool closedOnly)
     {
      m_tf=tf; m_len=len; m_phase=phase; m_price=price; m_closed=closedOnly; m_n=0; m_first=0;
      //--- OnInit runs again when an input is changed but the globals survive: drop ALL old state
      m_jh.Reset(); m_jl.Reset(); m_jt.Reset();
      ArrayFree(m_time); ArrayFree(m_mh); ArrayFree(m_ml); ArrayFree(m_mt);
     }

   //--- returns the first chart bar whose mapped values were (re)written, -1 if data not ready
   int Update(const int total,const int prev,const datetime &ctime[],
              const double &copen[],const double &chigh[],const double &clow[],const double &cclose[])
     {
      //--- line on the chart timeframe: use the chart arrays directly (no Bars()/Copy*() synchronisation
      //    that can leave every candle white while it is "not ready")
      bool same=(m_tf==_Period);
      int n=same?total:Bars(_Symbol,m_tf);
      if(!same)
        {
         int maxb=(int)TerminalInfoInteger(TERMINAL_MAXBARS);   // Copy*() cannot return more than this
         if(maxb>0 && n>maxb) n=maxb;
        }
      if(n<=0) return(-1);
      datetime ft[1];
      if(same) ft[0]=ctime[0];
      else if(CopyTime(_Symbol,m_tf,n-1,1,ft)!=1) return(-1);

      //--- recalculate from the last known higher-TF bar (or everything after a reset / history change)
      int from=(m_n>3)?m_n-3:0;                    // re-do the last 3 higher-TF bars, not only the forming one
      if(prev==0 || n<m_n || ft[0]!=m_first) from=0;
      int k=n-from;

      datetime t[]; double o[],h[],l[],c[];
      if(same)
        {
         if(ArrayCopy(t,ctime ,0,from,k)!=k || ArrayCopy(o,copen ,0,from,k)!=k ||
            ArrayCopy(h,chigh ,0,from,k)!=k || ArrayCopy(l,clow  ,0,from,k)!=k ||
            ArrayCopy(c,cclose,0,from,k)!=k) return(-1);
        }
      else if(CopyTime (_Symbol,m_tf,0,k,t)!=k || CopyOpen (_Symbol,m_tf,0,k,o)!=k ||
              CopyHigh (_Symbol,m_tf,0,k,h)!=k || CopyLow  (_Symbol,m_tf,0,k,l)!=k ||
              CopyClose(_Symbol,m_tf,0,k,c)!=k) return(-1);
      if(from>0 && (from>=ArraySize(m_time) || t[0]!=m_time[from])) { m_n=0; return(-1); }   // series moved under us: redo from scratch

      if(ArraySize(m_time)!=n) ArrayResize(m_time,n,512);
      for(int j=0;j<k;j++)
        {
         int r=from+j;
         m_time[r]=t[j];
         m_jh.Calc(r,h[j],m_len,m_phase,n);
         m_jl.Calc(r,l[j],m_len,m_phase,n);
         m_jt.Calc(r,AppPrice(m_price,o[j],h[j],l[j],c[j]),m_len,m_phase,n);
        }
      m_n=n; m_first=ft[0];

      //--- first chart bar that has to be mapped again
      int st=(prev>0)?prev-1:0;
      if(from==0) st=0;
      else
        {
         int cs=BsFirstGE(ctime,total,m_time[from]);
         if(cs<st) st=cs;
        }
      if(st>total-1) st=total-1;
      if(st<0)       st=0;

      if(ArraySize(m_mh)!=total)
        { ArrayResize(m_mh,total,512); ArrayResize(m_ml,total,512); ArrayResize(m_mt,total,512); }

      //--- chart bar -> higher-TF bar containing it
      int hi=BsLastLE(m_time,n,ctime[st]);
      for(int i=st;i<total;i++)
        {
         while(hi+1<n && m_time[hi+1]<=ctime[i]) hi++;
         int x=hi-(m_closed?1:0);
         if(x<m_len)                                  // no data yet / filter still warming up
           { m_mh[i]=EMPTY_VALUE; m_ml[i]=EMPTY_VALUE; m_mt[i]=EMPTY_VALUE; }
         else
           { m_mh[i]=m_jh.Get(x,n); m_ml[i]=m_jl.Get(x,n); m_mt[i]=m_jt.Get(x,n); }
        }
      return(st);
     }

   double H(const int idx,const int total) const { return((idx<0||idx>=total||idx>=ArraySize(m_mh))?EMPTY_VALUE:m_mh[idx]); }
   double L(const int idx,const int total) const { return((idx<0||idx>=total||idx>=ArraySize(m_ml))?EMPTY_VALUE:m_ml[idx]); }
   double T(const int idx,const int total) const { return((idx<0||idx>=total||idx>=ArraySize(m_mt))?EMPTY_VALUE:m_mt[idx]); }
  };

//+------------------------------------------------------------------+
//| EMA on its own timeframe (iMA handle) mapped onto the chart bars |
//+------------------------------------------------------------------+
class CHtfEma
  {
private:
   int             m_h;
   ENUM_TIMEFRAMES m_tf;
   bool            m_closed;
   int             m_n;
   datetime        m_time[];
   double          m_ema[];

public:
   CHtfEma() { m_h=INVALID_HANDLE; m_n=0; m_tf=PERIOD_CURRENT; m_closed=false; }

   void Release()
     {
      if(m_h!=INVALID_HANDLE) { IndicatorRelease(m_h); m_h=INVALID_HANDLE; }
      m_n=0; ArrayFree(m_time); ArrayFree(m_ema);
     }

   void Init(const ENUM_TIMEFRAMES tf,const int per,const ENUM_APPLIED_PRICE price,const bool closedOnly)
     {
      m_h=INVALID_HANDLE;                          // (globals survive an input change: Release() frees the old handle in OnDeinit)
      m_tf=tf; m_closed=closedOnly; m_n=0;
      ArrayFree(m_time); ArrayFree(m_ema);
      m_h=iMA(_Symbol,tf,MathMax(per,1),0,MODE_EMA,price);
     }

   //--- returns the first chart bar whose EMA value must be re-read, -1 when the data is not ready
   int Update(const int total,const int prev,const datetime &ctime[])
     {
      if(m_h==INVALID_HANDLE) return(-1);
      int cnt=BarsCalculated(m_h);
      int n  =Bars(_Symbol,m_tf);
      if(cnt<=0 || n<=0) return(-1);

      if(prev==0 || m_n==0 || cnt!=m_n)            // full copy
        {
         if(CopyTime  (_Symbol,m_tf,0,cnt,m_time)!=cnt) { m_n=0; return(-1); }
         if(CopyBuffer(m_h,0,0,cnt,m_ema)        !=cnt) { m_n=0; return(-1); }
         m_n=cnt;
         return(0);                                // data copied: use it (a later bar-count change re-copies); never block the candles
        }

      //--- same number of bars: refresh only the last few higher-TF bars
      int k=MathMin(4,cnt);
      datetime t[]; double e[];
      if(CopyTime  (_Symbol,m_tf,0,k,t)!=k) return(-1);
      if(CopyBuffer(m_h,0,0,k,e)       !=k) return(-1);
      if(t[0]!=m_time[cnt-k]) { m_n=0; return(-1); }
      for(int j=0;j<k;j++) { m_time[cnt-k+j]=t[j]; m_ema[cnt-k+j]=e[j]; }
      int st=BsFirstGE(ctime,total,m_time[cnt-k]);
      if(st>total-1) st=total-1;
      if(st<0)       st=0;
      return(st);
     }

   //--- EMA value valid for the chart bar opened at ctime (EMPTY_VALUE if none)
   double Value(const datetime ctime) const
     {
      if(m_n<=0) return(EMPTY_VALUE);
      int idx=BsLastLE(m_time,m_n,ctime);
      if(m_closed) idx--;
      if(idx<0 || idx>=m_n) return(EMPTY_VALUE);
      double v=m_ema[idx];
      if(v<=0.0 || v==EMPTY_VALUE || !MathIsValidNumber(v)) return(EMPTY_VALUE);
      return(v);
     }
  };

//+------------------------------------------------------------------+
//| Timeframe must not be lower than the chart                       |
//+------------------------------------------------------------------+
ENUM_TIMEFRAMES ResolveTF(const ENUM_TIMEFRAMES tf,const string who)
  {
   if(tf==PERIOD_CURRENT || tf==_Period) return(_Period);
   if(PeriodSeconds(tf)<PeriodSeconds())
     {
      Print("XU-MA v3: ",who," timeframe is lower than the chart timeframe - using the chart timeframe");
      return(_Period);
     }
   return(tf);
  }

//+------------------------------------------------------------------+
//| Histogram colour engine, ported 1:1 from "color MACD 3D XU MA"  |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| XU Candles colour logic (ported from XU_Candles_EMA_v5_14_test_   |
//| JurikFlip_MTF_Auto) - only what decides blue / red candles        |
//+------------------------------------------------------------------+
double xuSig[];                       // 0 = white, 1 = blue, 2 = red (per chart bar)
double EMA54[],EMA4[];
double zzUp[],zzDown[],highMap[],lowMap[];
double JurikMap[];                    // Jurik MACD main line mapped to chart bars

ENUM_TIMEFRAMES tfFast=PERIOD_CURRENT;   // resolved fast EMA time frame
ENUM_TIMEFRAMES tfSlow=PERIOD_CURRENT;   // resolved slow EMA time frame
int    hEMA54=INVALID_HANDLE;
int    hEMA4 =INVALID_HANDLE;

int Highest(const double &arr[],int count,int start)
{
   int idx=start; double val=arr[start];
   for(int i=start-1; i>start-count && i>=0; i--)
      if(arr[i]>val){ val=arr[i]; idx=i; }
   return(idx);
}

int Lowest(const double &arr[],int count,int start)
{
   int idx=start; double val=arr[start];
   for(int i=start-1; i>start-count && i>=0; i--)
      if(arr[i]<val){ val=arr[i]; idx=i; }
   return(idx);
}

// Jurik MACD state (computed on JurikTF bars, persistent between calls)
ENUM_TIMEFRAMES jmTF=PERIOD_CURRENT;   // resolved Jurik time frame
double   jmMacd[];                     // Jurik MACD main line on JurikTF bars
datetime jmTime[];                     // open time of the JurikTF bars
double   jmWork[][20];                 // Jurik smoother state: 2 instances (fast / slow) x 10 values
double   jmHa[][4];                    // Heiken Ashi state for the HA price options
int      jmCount=0;                    // number of JurikTF bars calculated
bool     jmReady=false;                // Jurik MACD calculated at least once
bool     jurikDone=false;              // Jurik MACD mapped to chart bars

// Prints a message to the Experts log only when it differs from the previous one
string g_lastDbg="";
void DbgOnce(const string msg)
{
   if(msg==g_lastDbg) return;
   g_lastDbg=msg;
   Print(msg);
}

// Index of last element <= t in an ascending datetime array (-1 if t is before the first)
int FindBar(const datetime &arr[],int n,datetime t)
{
   int lo=0,hi=n-1,res=-1;
   while(lo<=hi)
   {
      int mid=(lo+hi)/2;
      if(arr[mid]<=t){res=mid; lo=mid+1;}
      else hi=mid-1;
   }
   return(res);
}

//------------------------------------------------------------------
// Jurik smoothing engine (extracted from "Jurik MACD XU MA v3")
//   inst 0 = fast smoother, inst 1 = slow smoother (10 state values each)
//   i = absolute bar index on the JurikTF series (oldest = 0)
//------------------------------------------------------------------
double JmSmooth(const double price,const double length,const double phase,const int i,const int inst)
{
   int _inst=inst*10;
   int _indC=i;
   int _indP=MathMax(i-1,0);
   int _indF=MathMax(i-10,0);

   if(i==0 || length<=1)
   {
      int k=0;
      for(;k<7;k++)  jmWork[_indC][_inst+k]=price;
      for(;k<10;k++) jmWork[_indC][_inst+k]=0;
      return(price);
   }

   double len1=MathMax(MathLog(MathSqrt(0.5*(length-1.0)))/MathLog(2.0)+2.0,0);
   double pow1=MathMax(len1-2.0,0.5);
   double del1=price-jmWork[_indP][_inst+5];
   double del2=price-jmWork[_indP][_inst+6];

   jmWork[_indC][_inst+7]=(MathAbs(del1)>MathAbs(del2))?MathAbs(del1):((MathAbs(del1)<MathAbs(del2))?MathAbs(del2):0);
   jmWork[_indC][_inst+8]=jmWork[_indP][_inst+8]+(jmWork[_indC][_inst+7]-jmWork[_indF][_inst+7])*0.1;
   jmWork[_indC][_inst+9]=jmWork[_indP][_inst+9]+(2.0/(MathMax(4.0*length,30)+1.0))*(jmWork[_indC][_inst+8]-jmWork[_indP][_inst+9]);

   double dVolty=(jmWork[_indC][_inst+9]>0)?jmWork[_indC][_inst+7]/jmWork[_indC][_inst+9]:0;
   if(dVolty>MathPow(len1,1.0/pow1)) dVolty=MathPow(len1,1.0/pow1);
   if(dVolty<1.0)                    dVolty=1.0;

   double pow2=MathPow(dVolty,pow1);
   double len2=MathSqrt(0.5*(length-1))*len1;
   double Kv  =MathPow(len2/(len2+1),MathSqrt(pow2));

   if(del1>0) jmWork[_indC][_inst+5]=price; else jmWork[_indC][_inst+5]=price-Kv*del1;
   if(del2<0) jmWork[_indC][_inst+6]=price; else jmWork[_indC][_inst+6]=price-Kv*del2;

   double corr =MathMax(MathMin(phase,100),-100)/100.0+1.5;
   double beta =0.45*(length-1)/(0.45*(length-1)+2);
   double alpha=MathPow(beta,pow2);

   jmWork[_indC][_inst+0]=price+alpha*(jmWork[_indP][_inst+0]-price);
   jmWork[_indC][_inst+1]=(price-jmWork[_indC][_inst+0])*(1-beta)+beta*jmWork[_indP][_inst+1];
   jmWork[_indC][_inst+2]=(jmWork[_indC][_inst+0]+corr*jmWork[_indC][_inst+1]);
   jmWork[_indC][_inst+3]=(jmWork[_indC][_inst+2]-jmWork[_indP][_inst+4])*MathPow((1-alpha),2)+MathPow(alpha,2)*jmWork[_indP][_inst+3];
   jmWork[_indC][_inst+4]=(jmWork[_indP][_inst+4]+jmWork[_indC][_inst+3]);

   return(jmWork[_indC][_inst+4]);
}

// Applied price for the Jurik MACD (incl. Heiken Ashi variants); o/h/l/c = bar i of JurikTF
double JmPrice(const int price,const double o,const double h,const double l,const double c,const int i)
{
   if(price>=pr_haclose)
   {
      double haOpen;
      if(i>0) haOpen=(jmHa[i-1][2]+jmHa[i-1][3])/2.0;
      else    haOpen=(o+c)/2.0;

      double haClose=(o+h+l+c)/4.0;
      double haHigh =MathMax(h,MathMax(haOpen,haClose));
      double haLow  =MathMin(l,MathMin(haOpen,haClose));

      if(haOpen<haClose){ jmHa[i][0]=haLow;  jmHa[i][1]=haHigh; }
      else              { jmHa[i][0]=haHigh; jmHa[i][1]=haLow;  }
      jmHa[i][2]=haOpen;
      jmHa[i][3]=haClose;

      switch(price)
      {
         case pr_haclose:    return(haClose);
         case pr_haopen:     return(haOpen);
         case pr_hahigh:     return(haHigh);
         case pr_halow:      return(haLow);
         case pr_hamedian:   return((haHigh+haLow)/2.0);
         case pr_hamedianb:  return((haOpen+haClose)/2.0);
         case pr_hatypical:  return((haHigh+haLow+haClose)/3.0);
         case pr_haweighted: return((haHigh+haLow+haClose+haClose)/4.0);
         case pr_haaverage:  return((haHigh+haLow+haClose+haOpen)/4.0);
         case pr_hatbiased:
            if(haClose>haOpen) return((haHigh+haClose)/2.0);
            else               return((haLow+haClose)/2.0);
      }
   }

   switch(price)
   {
      case pr_close:    return(c);
      case pr_open:     return(o);
      case pr_high:     return(h);
      case pr_low:      return(l);
      case pr_median:   return((h+l)/2.0);
      case pr_medianb:  return((o+c)/2.0);
      case pr_typical:  return((h+l+c)/3.0);
      case pr_weighted: return((h+l+c+c)/4.0);
      case pr_average:  return((h+l+c+o)/4.0);
      case pr_tbiased:
         if(c>o) return((h+c)/2.0);
         else    return((l+c)/2.0);
   }
   return(0);
}

// Jurik MACD main line (JMA fast - JMA slow) on any time frame, mapped to chart bars:
// each chart bar takes the value of the JurikTF bar that contains it (same rule as CalcMACDMap).
// The Jurik state is recursive, so it is calculated incrementally: only the newest JurikTF bars
// are recomputed per tick; a full rebuild happens on first run or when the stored series no longer
// lines up with the terminal's data. A full rebuild uses as many bars as the terminal can actually
// deliver (Copy* may return fewer than iBars() when "max bars in chart" / history sync limits apply).
void CalcJurikMap(const int rates_total,const int start,const datetime &time[])
{
   int total=iBars(_Symbol,jmTF);
   if(total<=0) return;

   datetime ct[];
   double   co[],ch[],cl[],cc[];
   int  from=0,n=0;
   bool full=true;

   if(jmReady && jmCount>0)
   {
      int k=MathMin(total,20);                       // newest bars overlap the stored series
      n=CopyTime(_Symbol,jmTF,0,k,ct);
      if(n==k && ct[0]<=jmTime[jmCount-1])
      {
         int p=FindBar(jmTime,jmCount,ct[0]);
         if(p>=0 && jmTime[p]==ct[0]){from=p; full=false;}
      }
   }
   if(full)
   {
      n=CopyTime(_Symbol,jmTF,0,total,ct);           // whatever the terminal can deliver
      if(n<=0) return;                               // history not ready - retry on next call
      from=0;
   }
   if(CopyOpen (_Symbol,jmTF,0,n,co)!=n) return;
   if(CopyHigh (_Symbol,jmTF,0,n,ch)!=n) return;
   if(CopyLow  (_Symbol,jmTF,0,n,cl)!=n) return;
   if(CopyClose(_Symbol,jmTF,0,n,cc)!=n) return;

   int newCount=from+n;
   ArrayResize(jmMacd,newCount);
   ArrayResize(jmTime,newCount);
   ArrayResize(jmWork,newCount);
   ArrayResize(jmHa,newCount);

   for(int j=0;j<n;j++)
   {
      int i=from+j;
      jmTime[i]=ct[j];
      double p=JmPrice(JurikPrice,co[j],ch[j],cl[j],cc[j],i);
      double f=JmSmooth(p,JurikFast,JurikPhase,i,0);
      double sl=JmSmooth(p,JurikSlow,JurikPhase,i,1);
      jmMacd[i]=f-sl;
   }
   jmCount=newCount;

   // chart bars to (re)map: everything after a full rebuild, otherwise from the first chart bar
   // that lies inside the recomputed JurikTF bars
   int s=0;
   if(!full)
   {
      s=MathMin(start,rates_total-1);
      datetime tFrom=jmTime[from];
      while(s>0 && time[s]>=tFrom) s--;
   }
   jmReady=true;

   for(int i=s;i<rates_total;i++)
   {
      int j=FindBar(jmTime,jmCount,time[i]);
      JurikMap[i]=(j<0)?EMPTY_VALUE:jmMacd[j];
   }
   jurikDone=true;
}

// EMA (any time frame / period) mapped onto the chart bars.
//   - same time frame as the chart: plain iMA buffer (fallback: EMA calculated on chart close)
//   - other time frame: each chart bar takes the EMA of the bar of that time frame that contains it
//     (for a LOWER time frame: the last bar inside the chart bar, i.e. the value at the chart bar's close)
// fromBar = first chart bar whose value was (re)written, so the caller can re-evaluate from there.
// Returns false when the other time frame's data is not ready yet (call again on the next tick).
bool CalcEMA(const int handle,const ENUM_TIMEFRAMES tf,const int period,double &out[],
             const int rates_total,const int prev_calculated,
             const datetime &time[],const double &close[],int &fromBar)
{
   int start=(prev_calculated==0)?0:prev_calculated-1;
   fromBar=start;

   if(PeriodSeconds(tf)==PeriodSeconds((ENUM_TIMEFRAMES)_Period))
   {
      if(handle!=INVALID_HANDLE && CopyBuffer(handle,0,0,rates_total,out)>0) return(true);
      double k=2.0/(period+1.0);
      if(start==0) out[0]=close[0];
      for(int i=MathMax(1,start);i<rates_total;i++)
         out[i]=close[i]*k+out[i-1]*(1.0-k);
      return(true);
   }

   int tfSec=PeriodSeconds(tf);
   int chSec=PeriodSeconds((ENUM_TIMEFRAMES)_Period);

   if(tfSec>chSec)
   {
      // ---- HIGHER time frame than the chart (original behaviour, uses the iMA handle) ----
      if(handle==INVALID_HANDLE || BarsCalculated(handle)<=0) return(false);

      datetime from =time[start]-2*tfSec;
      datetime to   =time[rates_total-1]+chSec;

      datetime ht[];
      double   hv[];
      int n=CopyTime(_Symbol,tf,from,to,ht);
      if(n<=0) return(false);
      if(CopyBuffer(handle,0,from,to,hv)!=n) return(false);

      int s=0;
      if(prev_calculated>0)
      {
         datetime tFrom=ht[MathMax(n-2,0)];
         s=MathMin(start,rates_total-1);
         while(s>0 && time[s-1]>=tFrom) s--;
      }
      for(int i=s;i<rates_total;i++)
      {
         int j=FindBar(ht,n,time[i]);
         out[i]=(j<0 || hv[j]==EMPTY_VALUE)?EMPTY_VALUE:hv[j];
      }
      fromBar=s;
      return(true);
   }

   // ---- LOWER time frame than the chart (D1 / W1 / MN charts with H4 EMAs) ----
   // FIX: no iMA handle and no range-based CopyBuffer here (they fail / return a different bar
   // count while the other time frame is still loading, and then nothing was drawn). The EMA is
   // calculated directly from the other time frame's closes and each chart bar takes the value
   // of the LAST lower-TF bar inside it (value at the chart bar's close).
   int total=iBars(_Symbol,tf);
   if(total<=0) return(false);
   datetime ht[];
   double   hc[];
   int n1=CopyTime (_Symbol,tf,0,total,ht);
   int n2=CopyClose(_Symbol,tf,0,total,hc);
   int n=n1;
   if(n<=1 || n1!=n2)
   {
      DbgOnce("XU EMA: "+EnumToString(tf)+" history not available yet - retrying");
      return(false);
   }
   double ema[];
   ArrayResize(ema,n);
   double k=2.0/(period+1.0);
   ema[0]=hc[0];
   for(int i=1;i<n;i++) ema[i]=ema[i-1]+k*(hc[i]-ema[i-1]);

   int first=rates_total;                     // first chart bar whose value changed
   if(prev_calculated==0) first=0;
   for(int i=0;i<rates_total;i++)
   {
      datetime t=(i<rates_total-1)?time[i+1]-1:time[i]+chSec-1;   // end of this chart bar
      int j=FindBar(ht,n,t);
      double v=(j<0)?EMPTY_VALUE:ema[j];
      if(first==rates_total && out[i]!=v) first=i;
      out[i]=v;
   }
   fromBar=MathMin(start,first);
   return(true);
}

// ZigZag whose swings are fixed by MACD centre-line crossings:
//   every time the MACD line crosses zero the swing of the finished MACD segment is fixed
//   (highest high of a positive segment = top, lowest low of a negative segment = bottom)
//   and a new leg starts from the crossing bar.
// up[] = bottoms, dn[] = tops (same layout as GetZigZag). Pivots of the running segment are not
// drawn until the next crossing fixes them. firstDiff = first bar whose pivot data changed.
void GetMACDZigZag(double &up[],double &dn[],const double &macd[],const int total,
                   const double &hi[],const double &lo[],const bool full,int &firstDiff)
{
   double tUp[],tDn[];
   ArrayResize(tUp,total);
   ArrayResize(tDn,total);
   ArrayInitialize(tUp,EMPTY_VALUE);
   ArrayInitialize(tDn,EMPTY_VALUE);

   int    segSign=0;
   double hiVal=0.0,loVal=0.0;
   int    hiIdx=-1,loIdx=-1;

   for(int i=0;i<total;i++)
   {
      if(macd[i]==EMPTY_VALUE) continue;
      int sg=(macd[i]>0.0)?1:(macd[i]<0.0)?-1:segSign;

      if(segSign==0)
      {
         if(sg==0) continue;
         segSign=sg; hiVal=hi[i]; hiIdx=i; loVal=lo[i]; loIdx=i;
         continue;
      }

      if(sg!=segSign)                                   // centre-line crossing: fix the finished swing
      {
         if(segSign>0) tDn[hiIdx]=hi[hiIdx];
         else          tUp[loIdx]=lo[loIdx];
         segSign=sg; hiVal=hi[i]; hiIdx=i; loVal=lo[i]; loIdx=i;   // new leg starts here
      }
      else
      {
         if(hi[i]>hiVal){hiVal=hi[i]; hiIdx=i;}
         if(lo[i]<loVal){loVal=lo[i]; loIdx=i;}
      }
   }

   firstDiff=full?0:total;
   for(int i=0;i<total;i++)
   {
      if(firstDiff==total && (tUp[i]!=up[i] || tDn[i]!=dn[i])) firstDiff=i;
      up[i]=tUp[i];
      dn[i]=tDn[i];
   }
}

void GetZigZag(double &up[],double &dn[],double &hmap[],double &lmap[],
               int prev,int total,int depth,
               const double &hi[],const double &lo[])
{
   int start=0,search=0,cnt=0;
   int shift,last_hp=0,last_lp=0;
   double last_h=EMPTY_VALUE,last_l=EMPTY_VALUE,curh=EMPTY_VALUE,curl=EMPTY_VALUE;

   if(prev==0)
   {
      ArrayInitialize(up,EMPTY_VALUE); ArrayInitialize(dn,EMPTY_VALUE);
      ArrayInitialize(hmap,EMPTY_VALUE); ArrayInitialize(lmap,EMPTY_VALUE);
      start=MathMax(total-5000,depth);
   }
   else
   {
      int i=total-4;
      while(cnt<3 && i>0){if(up[i]!=EMPTY_VALUE || dn[i]!=EMPTY_VALUE)cnt++; i--;}
      start=i+1;
      if(lmap[start]!=EMPTY_VALUE)     {curl=lmap[start]; search=1;}
      else if(hmap[start]!=EMPTY_VALUE){curh=hmap[start]; search=-1;}
      for(int j=start+1;j<total;j++) hmap[j]=lmap[j]=up[j]=dn[j]=EMPTY_VALUE;
   }

   int limit=total-3;
   for(shift=start;shift<limit && !IsStopped();shift++)
   {
      double v=lo[Lowest(lo,depth,shift)];
      if(v==last_l) v=EMPTY_VALUE; else{last_l=v; if(lo[shift]>v)v=EMPTY_VALUE;}
      lmap[shift]=(lo[shift]==v)?v:EMPTY_VALUE;

      v=hi[Highest(hi,depth,shift)];
      if(v==last_h) v=EMPTY_VALUE; else{last_h=v; if(hi[shift]<v)v=EMPTY_VALUE;}
      hmap[shift]=(hi[shift]==v)?v:EMPTY_VALUE;
   }

   if(search==0){last_l=last_h=EMPTY_VALUE;}
   else{last_l=curl; last_h=curh;}

   for(shift=start;shift<limit && !IsStopped();shift++)
   {
      switch(search)
      {
         case 0:
            if(last_l==EMPTY_VALUE && last_h==EMPTY_VALUE)
            {
               if(hmap[shift]!=EMPTY_VALUE){last_h=hmap[shift]; last_hp=shift; search=-1; dn[shift]=last_h;}
               else if(lmap[shift]!=EMPTY_VALUE){last_l=lmap[shift]; last_lp=shift; search=1; up[shift]=last_l;}
            }
            break;
         case 1:
            if(lmap[shift]!=EMPTY_VALUE && lmap[shift]<last_l && hmap[shift]==EMPTY_VALUE)
            {up[last_lp]=EMPTY_VALUE; last_lp=shift; last_l=lmap[shift]; up[shift]=last_l;}
            if(hmap[shift]!=EMPTY_VALUE && lmap[shift]==EMPTY_VALUE)
            {last_h=hmap[shift]; last_hp=shift; dn[shift]=last_h; search=-1;}
            break;
         case -1:
            if(hmap[shift]!=EMPTY_VALUE && hmap[shift]>last_h && lmap[shift]==EMPTY_VALUE)
            {dn[last_hp]=EMPTY_VALUE; last_hp=shift; last_h=hmap[shift]; dn[shift]=last_h;}
            if(lmap[shift]!=EMPTY_VALUE && hmap[shift]==EMPTY_VALUE)
            {last_l=lmap[shift]; last_lp=shift; up[shift]=last_l; search=1;}
            break;
      }
   }
}

// Automatic EMA time frame: one step above the chart time frame.
//   H4 -> D1, H1 -> H4, M15 -> H1, M5 -> M15, M1 -> M5
// Returns false for any other chart time frame (the manual inputs are then used).
bool AutoEmaTF(const ENUM_TIMEFRAMES chart,ENUM_TIMEFRAMES &tf)
{
   switch(chart)
   {
      case PERIOD_H4:  tf=PERIOD_D1;  return(true);
      case PERIOD_H1:  tf=PERIOD_H4;  return(true);
      case PERIOD_M15: tf=PERIOD_H1;  return(true);
      case PERIOD_M5:  tf=PERIOD_M15; return(true);
      case PERIOD_M1:  tf=PERIOD_M5;  return(true);
   }
   return(false);
}


// Candle signal per chart bar: 1 = blue (ZigZag up + EMA4>=EMA54), 2 = red (ZigZag down + EMA4<=EMA54), 0 = other
// loopStart = first chart bar whose signal was re-evaluated. Returns false when data is not ready (retry next tick).
bool CalcXuSignal(const int rates_total,const int prev_calculated,
                  const datetime &time[],const double &high[],const double &low[],const double &close[],
                  int &loopStart)
{
   int start=(prev_calculated==0)?0:prev_calculated-1;

   int fFrom=start,sFrom=start;
   bool okFast=CalcEMA(hEMA4 ,tfFast,EMA4per,EMA4 ,rates_total,prev_calculated,time,close,fFrom);
   bool okSlow=CalcEMA(hEMA54,tfSlow,EMAper ,EMA54,rates_total,prev_calculated,time,close,sFrom);
   if(!okFast || !okSlow) return(false);

   loopStart=MathMin(start,MathMin(fFrom,sFrom));
   if(ZZ_Mode==ZZ_MODE_JURIK)
   {
      CalcJurikMap(rates_total,start,time);
      if(jurikDone)
      {
         int firstDiff=rates_total;
         GetMACDZigZag(zzUp,zzDown,JurikMap,rates_total,high,low,(prev_calculated==0),firstDiff);
         loopStart=MathMin(loopStart,firstDiff);
      }
      else if(prev_calculated==0)
      {
         ArrayInitialize(zzUp,EMPTY_VALUE);
         ArrayInitialize(zzDown,EMPTY_VALUE);
      }
   }
   else
      GetZigZag(zzUp,zzDown,highMap,lowMap,prev_calculated,rates_total,ZZ_Depth,high,low);

   // trend state just before loopStart = direction of the last pivot before it
   int currentZZ=0;
   for(int j=loopStart-1;j>=0;j--)
   {
      if(zzUp[j]!=EMPTY_VALUE && zzUp[j]!=0)     {currentZZ=1;  break;}
      if(zzDown[j]!=EMPTY_VALUE && zzDown[j]!=0) {currentZZ=-1; break;}
   }

   for(int i=loopStart;i<rates_total;i++)
   {
      if(zzUp[i]!=EMPTY_VALUE && zzUp[i]!=0)     currentZZ=1;
      if(zzDown[i]!=EMPTY_VALUE && zzDown[i]!=0) currentZZ=-1;

      bool emaOk=(EMA4[i]!=EMPTY_VALUE && EMA54[i]!=EMPTY_VALUE);

      int zzDir=currentZZ;
      if(zzDir==0 && ZZ_Mode==ZZ_MODE_JURIK && jurikDone && JurikMap[i]!=EMPTY_VALUE)
         zzDir=(JurikMap[i]>0.0)?1:(JurikMap[i]<0.0)?-1:0;

      int sig=0;
      if(emaOk && zzDir==1  && EMA4[i]>=EMA54[i]) sig=1;
      if(emaOk && zzDir==-1 && EMA4[i]<=EMA54[i]) sig=2;
      xuSig[i]=sig;
   }
   return(true);
}

//--- match state of one bar: +1 = histogram blue AND candle blue, -1 = histogram red AND candle red, 0 = no match
//    candleIdx : 0 = blue candle, 1 = white, 2 = red candle    histSig : 0 = white, 1 = blue, 2 = red
int MatchState(const int candleIdx,const double histSig)
  {
   if(histSig==EMPTY_VALUE) return(0);
   int h=(int)MathRound(histSig);
   if(candleIdx==0 && h==1) return( 1);
   if(candleIdx==2 && h==2) return(-1);
   return(0);
  }

//--- arrow glyph codes from the selected type
void ArrowCodes(int &up,int &dn)
  {
   switch(ArrowType)
     {
      case ARW_233_234: up=233; dn=234; break;
      case ARW_225_226: up=225; dn=226; break;
      case ARW_241_242: up=241; dn=242; break;
      case ARW_217_218: up=217; dn=218; break;
      case ARW_CIRCLE:  up=108; dn=108; break;
      case ARW_DOT:     up=159; dn=159; break;
      default:          up=ArrowCodeUp; dn=ArrowCodeDn; break;
     }
  }

double ArrUp[],ArrDn[];                // match arrows (plots 7 / 8)
bool   histOn=false;                   // histogram engine running
bool   g_xuPending=true;               // histogram colours still owe a from-scratch pass

//+------------------------------------------------------------------+
double WickHi[],WickLo[],WickClr[];
double BodyHi[],BodyLo[],BodyClr[];
double DOP[];
double TrendBgd[],TREND[],TRENDclr[];
double SigBgd[],SIGNAL[],SIGNALclr[];
double trend[],signal[],xtrend[],xage[];

//--- Jurik filters (High / Low / applied price) on their own timeframe, mapped to the chart
CMtfJurik       mTrend,mSignal;
ENUM_TIMEFRAMES tfTrend,tfSignal;
CHtfEma         mEmaF;                    // higher-TF EMA candle filter
ENUM_TIMEFRAMES tfEmaF;

int             trendPer,signalPer,lastScale=-1;

//--- retry state: higher-TF data may not be ready on the first calculation
bool            g_dirty=true;       // a from-scratch pass with ALL data is still owed
bool            g_lastOk=true;      // for log messages (state changes only)
int             g_total=0;          // rates_total of the last OnCalculate
int             g_retry=0;          // timer retries since the last unfinished calculation
string          g_wait="";          // which data source was not ready
datetime        g_firstTime=0;      // time of chart bar 0 -> detects history shifting (max bars in chart reached)
uint            g_lastFull=0;       // GetTickCount() of the last from-scratch attempt
int             g_lastX=0;          // last logged xtrend (LogFlips)
int             g_zoneAcc=0;        // new bars since the zone rectangles were last rebuilt
double          g_sig=0.0;          // signature of the higher-TF bars last used (timer detects late higher-TF updates)
int             g_passes=0;         // successful from-scratch passes since OnInit (2 needed after init / input change)
#define RETRY_MS    1000
#define ZONE_REBUILD_BARS 500
ENUM_TIMEFRAMES dopTF;
bool            dopOn;

//+------------------------------------------------------------------+
int OnInit()
  {
   tfTrend=ResolveTF(TRENDtf,"TREND");
   tfSignal=ResolveTF(SIGNALtf,"SIGNAL");

   // the periods are exactly what the user typed in the inputs (counted in bars of the line's timeframe).
   // Optional: the old timeframe based multiplier, only for a line running on the chart timeframe.
   trendPer=TRENDper; signalPer=SIGNALper;
   if(ScalePerByTF)
     {
      int mul=0;
      switch(_Period)
        {
         case PERIOD_M1:  mul=5; break;
         case PERIOD_M5:  mul=3; break;
         case PERIOD_M15: mul=4; break;
         case PERIOD_M30: mul=2; break;
         case PERIOD_H1:  mul=1; break;
         default: break;
        }
      if(mul>0 && tfTrend==_Period)  trendPer *=mul;
      if(mul>0 && tfSignal==_Period) signalPer*=mul;
     }
   trendPer =MathMax(trendPer,2);                   // Jurik length must be > 1
   signalPer=MathMax(signalPer,2);

   // ---- buffers
   SetIndexBuffer(0,WickHi,INDICATOR_DATA);
   SetIndexBuffer(1,WickLo,INDICATOR_DATA);
   SetIndexBuffer(2,WickClr,INDICATOR_COLOR_INDEX);
   SetIndexBuffer(3,BodyHi,INDICATOR_DATA);
   SetIndexBuffer(4,BodyLo,INDICATOR_DATA);
   SetIndexBuffer(5,BodyClr,INDICATOR_COLOR_INDEX);
   SetIndexBuffer(6,DOP,INDICATOR_DATA);
   SetIndexBuffer(7,TrendBgd,INDICATOR_DATA);
   SetIndexBuffer(8,TREND,INDICATOR_DATA);
   SetIndexBuffer(9,TRENDclr,INDICATOR_COLOR_INDEX);
   SetIndexBuffer(10,SigBgd,INDICATOR_DATA);
   SetIndexBuffer(11,SIGNAL,INDICATOR_DATA);
   SetIndexBuffer(12,SIGNALclr,INDICATOR_COLOR_INDEX);
   SetIndexBuffer(13,ArrUp,INDICATOR_DATA);
   SetIndexBuffer(14,ArrDn,INDICATOR_DATA);
   SetIndexBuffer(15,trend,INDICATOR_CALCULATIONS);
   SetIndexBuffer(16,signal,INDICATOR_CALCULATIONS);
   SetIndexBuffer(17,xtrend,INDICATOR_CALCULATIONS);
   SetIndexBuffer(18,xage,INDICATOR_CALCULATIONS);
   // histogram colour engine (calculation buffers)
   SetIndexBuffer(19,xuSig,   INDICATOR_CALCULATIONS);
   SetIndexBuffer(20,EMA4,    INDICATOR_CALCULATIONS);
   SetIndexBuffer(21,EMA54,   INDICATOR_CALCULATIONS);
   SetIndexBuffer(22,zzUp,    INDICATOR_CALCULATIONS);
   SetIndexBuffer(23,zzDown,  INDICATOR_CALCULATIONS);
   SetIndexBuffer(24,highMap, INDICATOR_CALCULATIONS);
   SetIndexBuffer(25,lowMap,  INDICATOR_CALCULATIONS);
   SetIndexBuffer(26,JurikMap,INDICATOR_CALCULATIONS);

   for(int p=0;p<9;p++) PlotIndexSetDouble(p,PLOT_EMPTY_VALUE,EMPTY_VALUE);

   // ---- candles (wick = plot 0, body = plot 1); colour index 0=up 1=neutral 2=down
   color cu=showCANDLES?CandleUp:clrNONE, cw=showCANDLES?CandleWt:clrNONE, cd=showCANDLES?CandleDn:clrNONE;
   for(int p=0;p<2;p++)
     {
      PlotIndexSetInteger(p,PLOT_COLOR_INDEXES,3);
      PlotIndexSetInteger(p,PLOT_LINE_COLOR,0,cu);
      PlotIndexSetInteger(p,PLOT_LINE_COLOR,1,cw);
      PlotIndexSetInteger(p,PLOT_LINE_COLOR,2,cd);
      PlotIndexSetInteger(p,PLOT_SHOW_DATA,false);
     }
   PlotIndexSetInteger(0,PLOT_LINE_WIDTH,cWick);
   PlotIndexSetString(0,PLOT_LABEL,"Wick");
   PlotIndexSetString(1,PLOT_LABEL,"Body");

   // ---- daily / weekly open line
   dopTF=DOPtf; dopOn=showDOP;
   int ps=PeriodSeconds();
   if(ps<=3600)  dopTF=PERIOD_D1;
   if(ps==14400) dopTF=PERIOD_W1;
   if(ps>=86400) dopOn=false;
   PlotIndexSetInteger(2,PLOT_LINE_COLOR,dopOn?DOPclr:clrNONE);
   PlotIndexSetInteger(2,PLOT_LINE_WIDTH,DOPwidth);
   PlotIndexSetString (2,PLOT_LABEL,"Open line");

   // ---- TREND line
   PlotIndexSetInteger(3,PLOT_LINE_COLOR,showTREND?Tbgdclr:clrNONE);
   PlotIndexSetInteger(3,PLOT_LINE_WIDTH,TRENDwidth+4);
   PlotIndexSetInteger(3,PLOT_DRAW_BEGIN,trendPer+1);
   PlotIndexSetInteger(3,PLOT_SHOW_DATA,false);
   PlotIndexSetInteger(4,PLOT_COLOR_INDEXES,2);
   PlotIndexSetInteger(4,PLOT_LINE_COLOR,0,showTREND?TRENDupclr:clrNONE);
   PlotIndexSetInteger(4,PLOT_LINE_COLOR,1,showTREND?TRENDdnclr:clrNONE);
   PlotIndexSetInteger(4,PLOT_LINE_WIDTH,TRENDwidth);
   PlotIndexSetInteger(4,PLOT_DRAW_BEGIN,trendPer+1);
   PlotIndexSetString (4,PLOT_LABEL,"TREND");

   // ---- SIGNAL line
   PlotIndexSetInteger(5,PLOT_LINE_COLOR,showSIGNAL?Sbgdclr:clrNONE);
   PlotIndexSetInteger(5,PLOT_LINE_WIDTH,SIGNALwidth+4);
   PlotIndexSetInteger(5,PLOT_DRAW_BEGIN,signalPer+1);
   PlotIndexSetInteger(5,PLOT_SHOW_DATA,false);
   PlotIndexSetInteger(6,PLOT_COLOR_INDEXES,2);
   PlotIndexSetInteger(6,PLOT_LINE_COLOR,0,showSIGNAL?SIGNALupclr:clrNONE);
   PlotIndexSetInteger(6,PLOT_LINE_COLOR,1,showSIGNAL?SIGNALdnclr:clrNONE);
   PlotIndexSetInteger(6,PLOT_LINE_WIDTH,SIGNALwidth);
   PlotIndexSetInteger(6,PLOT_DRAW_BEGIN,signalPer+1);
   PlotIndexSetString (6,PLOT_LABEL,"SIGNAL");

   mTrend.Init (tfTrend, trendPer, TRENDphase, TRENDtype, MTFclosedBar);
   mSignal.Init(tfSignal,signalPer,SIGNALphase,SIGNALtype,MTFclosedBar);

   tfEmaF=ResolveTF(EMAFilterTF,"EMA filter");
   mEmaF.Release();
   if(EMAFilterOn) mEmaF.Init(tfEmaF,EMAFilterPer,EMAFilterPrice,EMAFilterClosed);

   // ---- histogram colour engine + match arrows
   histOn=ShowMatchArrows;
   int acUp=233,acDn=234;
   ArrowCodes(acUp,acDn);
   int asz=MathMax(1,MathMin(5,ArrowSize));
   int aoff=MathMax(0,ArrowOffsetPx);
   PlotIndexSetInteger(7,PLOT_ARROW,acUp);
   PlotIndexSetInteger(7,PLOT_LINE_COLOR,histOn?ArrowUpClr:clrNONE);
   PlotIndexSetInteger(7,PLOT_LINE_WIDTH,asz);
   PlotIndexSetInteger(7,PLOT_ARROW_SHIFT,aoff);       // positive = shifted DOWN (arrow sits under the candle low)
   PlotIndexSetString (7,PLOT_LABEL,"Match UP arrow");
   PlotIndexSetInteger(8,PLOT_ARROW,acDn);
   PlotIndexSetInteger(8,PLOT_LINE_COLOR,histOn?ArrowDnClr:clrNONE);
   PlotIndexSetInteger(8,PLOT_LINE_WIDTH,asz);
   PlotIndexSetInteger(8,PLOT_ARROW_SHIFT,-aoff);      // negative = shifted UP (arrow sits above the candle high)
   PlotIndexSetString (8,PLOT_LABEL,"Match DOWN arrow");

   //--- OnInit runs again on an input change but the globals survive: drop the old handles / state
   if(hEMA54!=INVALID_HANDLE) { IndicatorRelease(hEMA54); hEMA54=INVALID_HANDLE; }
   if(hEMA4 !=INVALID_HANDLE) { IndicatorRelease(hEMA4 ); hEMA4 =INVALID_HANDLE; }
   jmCount=0; jmReady=false; jurikDone=false; g_xuPending=true; g_lastDbg="";
   ArrayResize(jmMacd,0); ArrayResize(jmTime,0); ArrayResize(jmWork,0); ArrayResize(jmHa,0);
   tfFast=_Period; tfSlow=_Period; jmTF=_Period;
   if(histOn)
     {
      if(ZZ_Depth<5 || ZZ_Depth>1000 || JurikFast<1 || JurikSlow<=JurikFast || EMA4per<1 || EMAper<1)
        { Print("XU-MA v3: invalid histogram engine parameters"); return(INIT_PARAMETERS_INCORRECT); }
      tfFast=(EMA4_TF  ==PERIOD_CURRENT)?(ENUM_TIMEFRAMES)_Period:EMA4_TF;
      tfSlow=(EMAper_TF==PERIOD_CURRENT)?(ENUM_TIMEFRAMES)_Period:EMAper_TF;
      if(AutoEMA_TF)
        {
         ENUM_TIMEFRAMES autoTF;
         if(AutoEmaTF((ENUM_TIMEFRAMES)_Period,autoTF)) { tfFast=autoTF; tfSlow=autoTF; }
        }
      hEMA54=iMA(_Symbol,tfSlow,EMAper,0,MODE_EMA,PRICE_CLOSE);
      hEMA4 =iMA(_Symbol,tfFast,EMA4per,0,MODE_EMA,PRICE_CLOSE);
      if(hEMA54==INVALID_HANDLE || hEMA4==INVALID_HANDLE)
        { Print("XU-MA v3: error creating the histogram engine EMA handles"); return(INIT_FAILED); }
      jmTF=(JurikTF==PERIOD_CURRENT)?(ENUM_TIMEFRAMES)_Period:JurikTF;
     }

   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
   IndicatorSetString(INDICATOR_SHORTNAME,"XU-MA v3");
   fSetBuffers();
   g_dirty=true; g_lastOk=true; g_total=0; g_retry=0; g_firstTime=0; g_lastFull=0; g_zoneAcc=0; g_lastX=0; g_passes=0; g_sig=0.0;
   EventSetMillisecondTimer(RETRY_MS);               // finishes the calculation when late data arrives, no tick needed
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   EventKillTimer();
   mEmaF.Release();
   if(hEMA54!=INVALID_HANDLE) { IndicatorRelease(hEMA54); hEMA54=INVALID_HANDLE; }
   if(hEMA4 !=INVALID_HANDLE) { IndicatorRelease(hEMA4 ); hEMA4 =INVALID_HANDLE; }
   ObjectsDeleteAll(0,ID);
   ChartRedraw();
  }
//+------------------------------------------------------------------+
bool Valid(const double v) { return(v!=0.0 && v!=EMPTY_VALUE && MathIsValidNumber(v)); }
//--- changes whenever the forming bar (or the bar count) of any higher timeframe in use changes
double HtfSig()
  {
   double s=0.0;
   ENUM_TIMEFRAMES tf[6]; int cntTf=0;
   tf[cntTf++]=tfTrend; tf[cntTf++]=tfSignal;
   if(EMAFilterOn) tf[cntTf++]=tfEmaF;
   if(histOn) { tf[cntTf++]=tfFast; tf[cntTf++]=tfSlow; tf[cntTf++]=jmTF; }
   for(int k=0;k<cntTf;k++)
      s+=(double)iBars(_Symbol,tf[k])+(double)iTime(_Symbol,tf[k],0)+iOpen(_Symbol,tf[k],0)
         +iHigh(_Symbol,tf[k],0)*3.0+iLow(_Symbol,tf[k],0)*5.0+iClose(_Symbol,tf[k],0)*7.0;
   return(s);
  }
//+------------------------------------------------------------------+
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<MathMax(trendPer,signalPer)+3) return(0);
   fSetBuffers();
   g_total=rates_total;

   int prev=prev_calculated;
   //--- history moved under us (max bars in chart reached, history reloaded / trimmed):
   //    rates_total / prev_calculated can look normal while every bar index has shifted
   if(prev>0 && (prev>rates_total || time[0]!=g_firstTime)) prev=0;
   g_firstTime=time[0];

   //--- an earlier pass could not use all higher-TF data: rebuild from scratch (at most once per second)
   if(g_dirty && prev>0 && GetTickCount()-g_lastFull>=1000) prev=0;
   if(prev==0) g_lastFull=GetTickCount();

   bool ok=Calculate(rates_total,prev,time,open,high,low,close);
   g_sig=HtfSig();
   if(prev==0)                                            // only a from-scratch pass can clear the flag
     {
      //--- right after OnInit / an input change the higher-TF series can still be half-synchronised and
      //    look complete: demand a second clean from-scratch pass (>=1 s later) before trusting the result
      if(ok) { g_passes++; g_dirty=(g_passes<2); }
      else   { g_passes=0; g_dirty=true; }
     }
   else if(!ok) { g_dirty=true; g_passes=0; }
   if(!g_dirty) g_retry=0;

   // ALWAYS report the bars as calculated: returning 0 made the terminal re-run everything on every tick
   // (thousands of objects deleted / recreated per tick) and was the way this indicator froze the terminal
   return(rates_total);
  }
//+------------------------------------------------------------------+
//| Timer: while a from-scratch pass is still owed (typical right    |
//| after attaching / reconnecting) redo it here, no tick needed.    |
//| No retry limit any more - it backs off to every 5 s instead.     |
//+------------------------------------------------------------------+
void OnTimer()
  {
   if(g_total<=0) return;
   if(!g_dirty)
     {
      //--- higher-TF data often updates AFTER the chart tick that triggered OnCalculate, and no further
      //    tick may follow: when a higher-TF bar changed since the last pass, recalculate the tail now
      double sg=HtfSig();
      if(sg==g_sig) return;
      int n=g_total;
      if(Bars(_Symbol,_Period)!=n) return;                 // a new chart bar is pending: OnCalculate handles it
      datetime t[]; double o[],h[],l[],c[];
      if(CopyTime (_Symbol,_Period,0,n,t)!=n || CopyOpen(_Symbol,_Period,0,n,o)!=n ||
         CopyHigh (_Symbol,_Period,0,n,h)!=n || CopyLow (_Symbol,_Period,0,n,l)!=n ||
         CopyClose(_Symbol,_Period,0,n,c)!=n) return;
      if(!Calculate(n,n,t,o,h,l,c)) { g_dirty=true; g_passes=0; }
      g_sig=sg;
      ChartRedraw();
      return;
     }
   g_retry++;
   if(g_retry>60 && g_retry%5!=0) return;                // back-off, but never give up

   int n=g_total;
   datetime t[]; double o[],h[],l[],c[];
   if(CopyTime (_Symbol,_Period,0,n,t)!=n || CopyOpen(_Symbol,_Period,0,n,o)!=n ||
      CopyHigh (_Symbol,_Period,0,n,h)!=n || CopyLow (_Symbol,_Period,0,n,l)!=n ||
      CopyClose(_Symbol,_Period,0,n,c)!=n) return;

   g_lastFull=GetTickCount();
   bool ok=Calculate(n,0,t,o,h,l,c);
   if(ok) { g_passes++; g_dirty=(g_passes<2); }
   else   { g_passes=0; g_dirty=true; }
   if(!g_dirty) g_retry=0;
   ChartRedraw();
  }
//+------------------------------------------------------------------+
//| Main calculation. Returns true when ALL data was available, false|
//| when some was not ready (g_dirty then forces a full recalculation)|
//| Candles are ALWAYS written - neutral colour while data is missing|
//+------------------------------------------------------------------+
bool Calculate(const int rates_total,
              const int prev_calculated,
              const datetime &time[],
              const double &open[],
              const double &high[],
              const double &low[],
              const double &close[])
  {
   int  start=(prev_calculated>0)?prev_calculated-1:0;
   bool ready=true;

   //--- TREND / SIGNAL filters on their own timeframe, mapped to the chart bars.
   //    A forming higher-TF bar changes its value, so every chart bar inside it is recalculated too.
   int sT=mTrend.Update (rates_total,prev_calculated,time,open,high,low,close);
   int sS=mSignal.Update(rates_total,prev_calculated,time,open,high,low,close);
   g_wait="";
   if(sT>=0) start=MathMin(start,sT); else { ready=false; g_wait+="TREND "; }
   if(sS>=0) start=MathMin(start,sS); else { ready=false; g_wait+="SIGNAL "; }
   if(EMAFilterOn)
     {
      int sE=mEmaF.Update(rates_total,prev_calculated,time);
      if(sE>=0) start=MathMin(start,sE); else { ready=false; g_wait+="EMA "; }
     }

   //--- histogram colour (blue / red / white of the MACD sub-window) per chart bar
   if(histOn)
     {
      int xf=0;
      int xp=g_xuPending?0:prev_calculated;
      if(CalcXuSignal(rates_total,xp,time,high,low,close,xf))
        {
         g_xuPending=false;
         start=MathMin(start,xf);                  // bars whose histogram colour changed are rewritten too
        }
      else
        {
         ready=false; g_wait+="HIST ";
         int z=g_xuPending?start:0;                // first failure: everything neutral, later: only the new bars
         for(int k=z;k<rates_total;k++) xuSig[k]=0;
         start=MathMin(start,z);
         g_xuPending=true;
        }
     }

   bool missing=false;

   for(int i=start;i<rates_total;i++)
     {
      //--- daily / weekly open
      DOP[i]=EMPTY_VALUE;
      if(dopOn)
        {
         int sh=iBarShift(_Symbol,dopTF,time[i],false);
         double o=(sh>=0)?iOpen(_Symbol,dopTF,sh):0.0;
         if(o>0.0) DOP[i]=o;
         else if(i==rates_total-1) missing=true;
        }

      //--- TREND
      trend[i]=(i>0)?trend[i-1]:0;
      if(i>0)
        {
         double h=mTrend.H(i-1-TRENDshft,rates_total), l=mTrend.L(i-1-TRENDshft,rates_total);
         if(Valid(h) && close[i]>h) trend[i]= 1;
         if(Valid(l) && close[i]<l) trend[i]=-1;
        }
      double t=mTrend.T(i-TRENDshft,rates_total);
      if(Valid(t)) { TrendBgd[i]=t; TREND[i]=t; }
      else         { TrendBgd[i]=EMPTY_VALUE; TREND[i]=EMPTY_VALUE; }
      TRENDclr[i]=(trend[i]==-1)?1:0;

      //--- SIGNAL
      signal[i]=(i>0)?signal[i-1]:0;
      if(i>0)
        {
         double h=mSignal.H(i-1-SIGNALshft,rates_total), l=mSignal.L(i-1-SIGNALshft,rates_total);
         if(Valid(h) && close[i]>h) signal[i]= 1;
         if(Valid(l) && close[i]<l) signal[i]=-1;
        }
      double s=mSignal.T(i-SIGNALshft,rates_total);
      if(Valid(s)) { SigBgd[i]=s; SIGNAL[i]=s; }
      else         { SigBgd[i]=EMPTY_VALUE; SIGNAL[i]=EMPTY_VALUE; }
      SIGNALclr[i]=(signal[i]==-1)?1:0;

      //--- directional trade + candle colouring
      xtrend[i]=0; int dir=1;                      // 0 = up, 1 = neutral, 2 = down (colour index)
      if(trend[i]== 1 && signal[i]== 1) { xtrend[i]= 1; dir=0; }
      if(trend[i]==-1 && signal[i]==-1) { xtrend[i]=-1; dir=2; }
      xage[i]=(i>0 && xtrend[i]==xtrend[i-1])?xage[i-1]+1.0:0.0;   // bars since the last flip
      //--- higher-TF EMA filter (candle colour only, trend / zones / alerts are not affected):
      //    price above EMA: red (down) candle -> white,  price below EMA: blue (up) candle -> white
      if(EMAFilterOn)
        {
         double ef=mEmaF.Value(time[i]);
         if(ef!=EMPTY_VALUE)
           {
            if(close[i]>ef && dir==2) dir=1;
            if(close[i]<ef && dir==0) dir=1;
           }
        }
      WickHi[i]=high[i]; WickLo[i]=low[i];
      BodyHi[i]=MathMax(open[i],close[i]); BodyLo[i]=MathMin(open[i],close[i]);
      WickClr[i]=dir; BodyClr[i]=dir;

      //--- MATCH arrows: histogram colour == candle colour (blue/blue -> up, red/red -> down),
      //    drawn on the FIRST candle of every run of the same match
      ArrUp[i]=EMPTY_VALUE; ArrDn[i]=EMPTY_VALUE;
      if(histOn)
        {
         int m =MatchState(dir,xuSig[i]);
         int pm=(i>0)?MatchState((int)WickClr[i-1],xuSig[i-1]):0;
         if(m!=0 && m!=pm)
           {
            if(m== 1) ArrUp[i]=low[i];
            else      ArrDn[i]=high[i];
           }
        }
     }

   //--- BGD zones (rebuilt every ZONE_REBUILD_BARS new bars so rectangles that scrolled out of
   //    ZonesMaxBars do not pile up for days and slow the whole terminal down)
   if(showBGDzones)
     {
      int zs=start;
      if(prev_calculated==0) g_zoneAcc=0;
      else g_zoneAcc+=MathMax(rates_total-prev_calculated,0);
      if(prev_calculated==0 || g_zoneAcc>=ZONE_REBUILD_BARS)
        {
         ObjectsDeleteAll(0,ID+"X");
         g_zoneAcc=0; zs=0;
        }
      UpdateZones(rates_total,zs,time,high);
     }

   //--- state of the newest bar -> panel / labels
   int last=rates_total-1;
   string boxTxt=" WAITING . . .";
   color  boxClr=C'40,40,40', txClr=clrW;
   if(LogFlips && (int)xtrend[last]!=g_lastX)
     {
      PrintFormat("XU-MA v3 flip %s: xtrend=%d trend=%d signal=%d close=%s candle colour=%d (0=up 1=neutral 2=down)",
                  TimeToString(time[last],TIME_DATE|TIME_MINUTES),(int)xtrend[last],(int)trend[last],(int)signal[last],
                  DoubleToString(close[last],_Digits),(int)WickClr[last]);
      g_lastX=(int)xtrend[last];
     }
   if(xtrend[last]== 1) { boxTxt="   UP TREND"; boxClr=clrDodgerBlue;  txClr=clrB; }
   if(xtrend[last]==-1) { boxTxt="DOWN TREND";  boxClr=C'174,107,52';   txClr=clrS; }

   if(showBOXtxt)
     {
      SetPanel(ID+"Drax1",CORNER_RIGHT_LOWER,0+moveTxtLR,25+moveTxtUD,200,25,boxClr,clrBlack);
      SetLabel(ID+"Drax2",CORNER_RIGHT_LOWER,196+moveTxtLR,27+moveTxtUD,
               TfToString()+" "+boxTxt,16,"Arial Bold",clrSilver,false,ANCHOR_LEFT_LOWER);
     }

   if(showSig)
     {
      color  TXbgd=C'34,34,34';
      double OpenToday=iOpen(_Symbol,PERIOD_D1,0), CloseToday=iClose(_Symbol,PERIOD_D1,0);
      color  TXu=(CloseToday>OpenToday)?clrDodgerBlue:clrMediumVioletRed;
      SetLabel(ID+"Drax3",CORNER_LEFT_UPPER, 78,12,"XARD",32,"BorisBlackBloxx",TXbgd,true,ANCHOR_LEFT_UPPER);
      SetLabel(ID+"Drax4",CORNER_LEFT_UPPER,260,12,"UNIVERSE",32,"BorisBlackBloxx",TXbgd,true,ANCHOR_LEFT_UPPER);
      SetLabel(ID+"Drax5",CORNER_LEFT_UPPER, 76,10,"XARD",32,"BorisBlackBloxx",txClr,true,ANCHOR_LEFT_UPPER);
      SetLabel(ID+"Drax6",CORNER_LEFT_UPPER,258,10,"UNIVERSE",32,"BorisBlackBloxx",TXu,true,ANCHOR_LEFT_UPPER);
      SetLabel(ID+"Drax7",CORNER_LEFT_UPPER,388,58,"VWAP Edition",12,"BorisBlackBloxx",clrDarkGray,true,ANCHOR_LEFT_UPPER);
     }

   bool ok=(ready && !missing);
   if(!ok && g_lastOk) Print("XU-MA v3: waiting for data (",g_wait,") error=",GetLastError()," - will retry");
   if(ok && !g_lastOk) Print("XU-MA v3: data complete, indicator recalculated");
   g_lastOk=ok;
   if(ok) manageAlerts(rates_total,time);                // no alerts from a half-calculated state
   return(ok);
  }
//+------------------------------------------------------------------+
void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
  {
   if(id==CHARTEVENT_CHART_CHANGE) fSetBuffers();
  }
//+------------------------------------------------------------------+
//| Candle body width follows the chart zoom level                   |
//+------------------------------------------------------------------+
void fSetBuffers()
  {
   int sc=(int)ChartGetInteger(0,CHART_SCALE);
   if(sc==lastScale) return;
   lastScale=sc;
   int w=1;
   switch(sc)
     {
      case 0: w=1;  break;
      case 1: w=1;  break;
      case 2: w=2;  break;
      case 3: w=3;  break;
      case 4: w=6;  break;
      case 5: w=14; break;
     }
   PlotIndexSetInteger(1,PLOT_LINE_WIDTH,w);
   ChartRedraw();
  }
//+------------------------------------------------------------------+
string TfToString()
  {
   return(StringSubstr(EnumToString((ENUM_TIMEFRAMES)_Period),7));
  }
//+------------------------------------------------------------------+
//| BGD zones: one full-height rectangle per run of equal trend      |
//+------------------------------------------------------------------+
string ZoneName(const datetime t) { return(ID+"X"+IntegerToString((long)t)); }
//+------------------------------------------------------------------+
color ZoneColor(const double tr)
  {
   if(tr== 1) return(ColorUp);
   if(tr==-1) return(ColorDown);
   return(ColorWait);
  }
//+------------------------------------------------------------------+
void DrawZone(const string name,const datetime t1,const datetime t2,const double maxV,const color clr)
  {
   if(ObjectFind(0,name)<0)
     {
      ObjectCreate(0,name,OBJ_RECTANGLE,0,t1,0.0,t2,maxV);
      ObjectSetInteger(0,name,OBJPROP_BACK,true);
      ObjectSetInteger(0,name,OBJPROP_FILL,true);
      ObjectSetInteger(0,name,OBJPROP_SELECTABLE,false);
      ObjectSetInteger(0,name,OBJPROP_HIDDEN,true);
     }
   ObjectSetInteger(0,name,OBJPROP_TIME,0,t1);
   ObjectSetDouble (0,name,OBJPROP_PRICE,0,0.0);
   ObjectSetInteger(0,name,OBJPROP_TIME,1,t2);
   ObjectSetDouble (0,name,OBJPROP_PRICE,1,maxV);
   ObjectSetInteger(0,name,OBJPROP_COLOR,clr);
  }
//+------------------------------------------------------------------+
void UpdateZones(const int total,const int start,const datetime &time[],const double &high[])
  {
   int first=(ZonesMaxBars>0)?MathMax(0,total-ZonesMaxBars):0;
   int s=MathMax(start,first);
   double maxV=high[total-1]*10.0;

   // beginning of the run that contains bar s
   int rs=s;
   while(rs>first && trend[rs-1]==trend[s]) rs--;

   if(rs==s)
     {
      // a new run starts at s: the previous run must end at bar s-1
      if(s>first)
        {
         int k=s-1;
         while(k>first && trend[k-1]==trend[s-1]) k--;
         string pn=ZoneName(time[k]);
         if(ObjectFind(0,pn)>=0) ObjectSetInteger(0,pn,OBJPROP_TIME,1,time[s-1]);
        }
     }
   else
      ObjectDelete(0,ZoneName(time[s]));     // stale rectangle from an earlier tick

   for(int i=s+1;i<total;i++) ObjectDelete(0,ZoneName(time[i]));   // runs inside the recalculated range are redrawn

   for(int i=s;i<total;i++)
     {
      if(i>s && trend[i]!=trend[i-1]) rs=i;
      if(i==total-1 || trend[i+1]!=trend[i])
         DrawZone(ZoneName(time[rs]),time[rs>0?rs-1:rs],time[i],maxV,ZoneColor(trend[i]));
     }
  }
//+------------------------------------------------------------------+
//| Alerts                                                           |
//+------------------------------------------------------------------+
void manageAlerts(const int total,const datetime &time[])
  {
   if(!AlertsOn) return;
   int bar=total-1-(AlertsOnCurrent?0:1);
   if(bar<1) return;
   if(xtrend[bar]!=xtrend[bar-1])
     {
      if(xtrend[bar]== 1) doAlert(time[bar],"UP");
      if(xtrend[bar]==-1) doAlert(time[bar],"DOWN");
     }
  }
//+------------------------------------------------------------------+
void doAlert(const datetime barTime,const string doWhat)
  {
   static string   previousAlert="nothing";
   static datetime previousTime=0;
   if(previousAlert!=doWhat || previousTime!=barTime)
     {
      previousAlert=doWhat; previousTime=barTime;
      string msg=_Symbol+" "+TfToString()+" : Direction changed to "+doWhat;
      if(AlertsMessage) Alert(msg);
      if(AlertsSound)   PlaySound(soundfile);
      if(alertsNotify)  SendNotification(msg);
      if(AlertsEmail)   SendMail(msg,msg+"\nLocal time "+TimeToString(TimeLocal(),TIME_SECONDS)+
                                      "\nBroker time "+TimeToString(TimeCurrent(),TIME_SECONDS));
     }
  }
//+------------------------------------------------------------------+
//| Panel / label helpers                                            |
//+------------------------------------------------------------------+
void SetPanel(const string name,const ENUM_BASE_CORNER corner,const int x,const int y,
              const int w,const int h,const color bg,const color border)
  {
   if(ObjectFind(0,name)<0)
     {
      ObjectCreate(0,name,OBJ_RECTANGLE_LABEL,0,0,0);
      ObjectSetInteger(0,name,OBJPROP_BORDER_TYPE,BORDER_FLAT);
      ObjectSetInteger(0,name,OBJPROP_COLOR,border);
      ObjectSetInteger(0,name,OBJPROP_WIDTH,0);
      ObjectSetInteger(0,name,OBJPROP_BACK,false);
      ObjectSetInteger(0,name,OBJPROP_SELECTABLE,false);
      ObjectSetInteger(0,name,OBJPROP_HIDDEN,true);
      ObjectSetString (0,name,OBJPROP_TOOLTIP,"\n");
     }
   ObjectSetInteger(0,name,OBJPROP_CORNER,corner);
   ObjectSetInteger(0,name,OBJPROP_XDISTANCE,x);
   ObjectSetInteger(0,name,OBJPROP_YDISTANCE,y);
   ObjectSetInteger(0,name,OBJPROP_XSIZE,w);
   ObjectSetInteger(0,name,OBJPROP_YSIZE,h);
   ObjectSetInteger(0,name,OBJPROP_BGCOLOR,bg);
  }
//+------------------------------------------------------------------+
void SetLabel(const string name,const ENUM_BASE_CORNER corner,const int x,const int y,const string text,
              const int fontsize,const string fontname,const color clr,const bool back,
              const ENUM_ANCHOR_POINT anchor)
  {
   if(ObjectFind(0,name)<0)
     {
      ObjectCreate(0,name,OBJ_LABEL,0,0,0);
      ObjectSetInteger(0,name,OBJPROP_SELECTABLE,false);
      ObjectSetInteger(0,name,OBJPROP_HIDDEN,true);
      ObjectSetString (0,name,OBJPROP_TOOLTIP,"\n");
     }
   ObjectSetInteger(0,name,OBJPROP_CORNER,corner);
   ObjectSetInteger(0,name,OBJPROP_ANCHOR,anchor);
   ObjectSetInteger(0,name,OBJPROP_XDISTANCE,x);
   ObjectSetInteger(0,name,OBJPROP_YDISTANCE,y);
   ObjectSetString (0,name,OBJPROP_TEXT,text);
   ObjectSetInteger(0,name,OBJPROP_FONTSIZE,fontsize);
   ObjectSetString (0,name,OBJPROP_FONT,fontname);
   ObjectSetInteger(0,name,OBJPROP_COLOR,clr);
   ObjectSetInteger(0,name,OBJPROP_BACK,back);
  }
//+------------------------------------------------------------------+
