//+------------------------------------------------------------------+
//|                                                     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)    |
//|   Optional candle filter: higher-TF EMA turns counter candles    |
//|   to the neutral colour                                          |
//+------------------------------------------------------------------+
#property link        "https://forex-station.com/viewtopic.php?p=1295409935#p1295409935"
#property version     "3.00"
#property description "[XU-MA v3]"
#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 16
#property indicator_plots   7

// 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
// calc   : trend, signal, xtrend                  buffers 13,14,15
#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

#define ID "XUMA_"

//+------------------------------------------------------------------+
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 "<<<==== [10] Candle EMA Filter ====>>>"
input bool            EMAfilterOn     = true;      // price below EMA: up (blue) candles -> neutral; price above EMA: down (pink) candles -> neutral
input ENUM_TIMEFRAMES EMAfilterTF     = PERIOD_H1; // EMA timeframe
input int             EMAfilterPer    = 50;        // EMA period

//+------------------------------------------------------------------+
//| 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:
   //--- 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);
      if(price==EMPTY_VALUE) price=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]);
      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; }

   //--- 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[])
     {
      int n=Bars(_Symbol,m_tf);
      if(n<=0) return(-1);
      datetime ft[1];
      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>0)?m_n-1:0;
      if(prev==0 || n<m_n || ft[0]!=m_first) from=0;
      int k=n-from;

      datetime t[]; double o[],h[],l[],c[];
      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 && 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 of a (higher) timeframe mapped onto the chart bars           |
//+------------------------------------------------------------------+
class CMtfEma
  {
private:
   ENUM_TIMEFRAMES m_tf;
   int             m_per;
   int             m_h;
   bool            m_closed;
   datetime        m_time[];             // times of the filter-TF bars
   double          m_v[];                // EMA values of the filter-TF bars
   int             m_n;
   datetime        m_first;
   double          m_map[];              // values mapped to chart bars

public:
   CMtfEma() { m_h=INVALID_HANDLE; m_n=0; m_first=0; m_per=1; m_closed=false; m_tf=PERIOD_CURRENT; }

   bool Init(const ENUM_TIMEFRAMES tf,const int per,const bool closedOnly)
     {
      m_tf=tf; m_per=per; m_closed=closedOnly; m_n=0; m_first=0;
      m_h=iMA(_Symbol,tf,per,0,MODE_EMA,PRICE_CLOSE);
      return(m_h!=INVALID_HANDLE);
     }
   void Release() { if(m_h!=INVALID_HANDLE) IndicatorRelease(m_h); m_h=INVALID_HANDLE; }

   //--- returns the first chart bar whose mapped value was (re)written, -1 if data not ready
   int Update(const int total,const int prev,const datetime &ctime[])
     {
      if(m_h==INVALID_HANDLE) return(-1);
      int n=Bars(_Symbol,m_tf);
      if(n<=0 || BarsCalculated(m_h)<n) return(-1);
      datetime ft[1];
      if(CopyTime(_Symbol,m_tf,n-1,1,ft)!=1) return(-1);

      int from=(m_n>0)?m_n-1:0;
      if(prev==0 || n<m_n || ft[0]!=m_first) from=0;
      int k=n-from;

      datetime t[]; double v[];
      if(CopyTime(_Symbol,m_tf,0,k,t)!=k || CopyBuffer(m_h,0,0,k,v)!=k) return(-1);
      if(from>0 && t[0]!=m_time[from]) { m_n=0; return(-1); }

      if(ArraySize(m_time)!=n) { ArrayResize(m_time,n,512); ArrayResize(m_v,n,512); }
      for(int j=0;j<k;j++) { m_time[from+j]=t[j]; m_v[from+j]=v[j]; }
      m_n=n; m_first=ft[0];

      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_map)!=total) ArrayResize(m_map,total,512);

      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);
         m_map[i]=(x<m_per)?EMPTY_VALUE:m_v[x];
        }
      return(st);
     }

   double Get(const int idx,const int total) const
     { return((idx<0||idx>=total||idx>=ArraySize(m_map))?EMPTY_VALUE:m_map[idx]); }
  };

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

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

//--- Jurik filters (High / Low / applied price) on their own timeframe, mapped to the chart
CMtfJurik       mTrend,mSignal;
ENUM_TIMEFRAMES tfTrend,tfSignal;
CMtfEma         mEma;                                  // candle filter EMA
ENUM_TIMEFRAMES tfEma;

int             trendPer,signalPer,lastScale=-1;
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,trend,INDICATOR_CALCULATIONS);
   SetIndexBuffer(14,signal,INDICATOR_CALCULATIONS);
   SetIndexBuffer(15,xtrend,INDICATOR_CALCULATIONS);

   for(int p=0;p<7;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");

   tfEma=ResolveTF(EMAfilterTF,"EMA filter");
   if(EMAfilterOn && !mEma.Init(tfEma,MathMax(EMAfilterPer,1),MTFclosedBar))
     {
      Print("XU-MA v3: failed to create the EMA filter handle");
      return(INIT_FAILED);
     }

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

   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
   IndicatorSetString(INDICATOR_SHORTNAME,"XU-MA v3");
   fSetBuffers();
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   mEma.Release();
   ObjectsDeleteAll(0,ID);
   ChartRedraw();
  }
//+------------------------------------------------------------------+
bool Valid(const double v) { return(v!=0.0 && v!=EMPTY_VALUE); }
//+------------------------------------------------------------------+
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();

   int start=(prev_calculated>0)?prev_calculated-1:0;

   //--- 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);
   int sS=mSignal.Update(rates_total,prev_calculated,time);
   if(sT<0 || sS<0) return(prev_calculated);          // higher-TF data not ready yet
   start=MathMin(start,MathMin(sT,sS));

   if(EMAfilterOn)                                       // candle filter EMA (filter timeframe -> chart bars)
     {
      int sE=mEma.Update(rates_total,prev_calculated,time);
      if(sE<0) return(prev_calculated);
      start=MathMin(start,sE);
     }

   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; }
      if(EMAfilterOn)                                // colour filter only - trend / zones / alerts are not touched
        {
         double e=mEma.Get(i,rates_total);
         if(Valid(e))
           {
            if(dir==0 && close[i]<e) dir=1;          // up candle while price is below the EMA  -> neutral
            if(dir==2 && close[i]>e) dir=1;          // down candle while price is above the EMA -> neutral
           }
        }
      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;
     }

   //--- BGD zones
   if(showBGDzones)
     {
      if(prev_calculated==0) ObjectsDeleteAll(0,ID+"X");
      UpdateZones(rates_total,start,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(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);
     }

   manageAlerts(rates_total,time);
   return(missing?0:rates_total);
  }
//+------------------------------------------------------------------+
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);
  }
//+------------------------------------------------------------------+
