//+------------------------------------------------------------------+
//|                                                     XU-MA v3.mq5 |
//|   MQL5 port of the MQL4 indicator "XU-MA v3" (XARD UNIVERSE)     |
//+------------------------------------------------------------------+
#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 17
#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
// calc   : carpet trend score [-1..+1]            buffer  16
#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_"
#define N_CP 13                                   // number of carpet EMA layers

enum ENUM_CANDLE_SRC
  {
   CSRC_XUMA   = 0,   // XU-MA original (TREND + SIGNAL agree)
   CSRC_CARPET = 1,   // EMA Carpet trend score (4 shades)
   CSRC_MATCH  = 2    // MATCH: XU-MA + Carpet agree -> blue (up) / red (down), otherwise white
  };

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

input group "<<<==== [02] Openline Settings ====>>>"
input bool            showDOP     = true;
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  = true;
input color             TRENDupclr = clrBlue;
input color             TRENDdnclr = clrCrimson;
input color             Tbgdclr    = C'100,130,160';
input int               TRENDper   = 36;
input int               TRENDshft  = 0;
input ENUM_MA_METHOD    TRENDmode  = MODE_EMA;
input ENUM_APPLIED_PRICE TRENDtype = PRICE_MEDIAN;
input int               TRENDwidth = 7;

input group "<<<==== [04] SIGNAL Settings ====>>>"
input bool              showSIGNAL  = true;
input color             SIGNALupclr = clrBlue;
input color             SIGNALdnclr = clrCrimson;
input color             Sbgdclr     = C'100,130,160';
input int               SIGNALper   = 9;
input int               SIGNALshft  = 0;
input ENUM_MA_METHOD    SIGNALmode  = MODE_EMA;
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  = true;
input bool            showSig     = true;
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        = true;
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] Carpet Trend Candles (from EMA_Carpet_3D) ====>>>"
input ENUM_CANDLE_SRC CarpetSrc       = CSRC_MATCH;    // Candle colour source
input ENUM_TIMEFRAMES CarpetTF        = PERIOD_H1;     // Carpet EMA timeframe
input bool            CarpetNoRepaint = true;          // Non-repainting higher-TF EMAs (value as of each chart bar)
input int             CarpetP01       = 1;             // EMA  1 period
input int             CarpetP02       = 2;             // EMA  2 period
input int             CarpetP03       = 3;             // EMA  3 period
input int             CarpetP04       = 4;             // EMA  4 period
input int             CarpetP05       = 5;             // EMA  5 period
input int             CarpetP06       = 6;             // EMA  6 period
input int             CarpetP07       = 7;             // EMA  7 period
input int             CarpetP08       = 8;             // EMA  8 period
input int             CarpetP09       = 9;             // EMA  9 period
input int             CarpetP10       = 10;            // EMA 10 period
input int             CarpetP11       = 11;            // EMA 11 period
input int             CarpetP12       = 13;            // EMA 12 period
input int             CarpetP13       = 20;            // EMA 13 period
input double          CarpetContrast  = 1.00;          // Trend score contrast (>1 = stronger sooner)
input double          CarpetStrong    = 0.50;          // |score| at/above this = STRONG trend (0-1)
input color           CarpetStrongUp  = C'0,191,255';  // Strong bull candle
input color           CarpetWeakUp    = C'170,234,255';// Weak bull candle
input color           CarpetWeakDn    = C'255,170,170';// Weak bear candle
input color           CarpetStrongDn  = C'255,0,0';    // Strong bear candle

input group "<<<==== [09] Match Candles (XU-MA + Carpet agree) ====>>>"
input color           MatchUpClr      = clrBlue;       // Both UP   -> candle colour
input color           MatchDnClr      = clrRed;        // Both DOWN -> candle colour
input color           MatchNoClr      = clrWhite;      // Any other condition -> candle colour

//+------------------------------------------------------------------+
struct SArr { double v[]; };

double WickHi[],WickLo[],WickClr[];
double BodyHi[],BodyLo[],BodyClr[];
double DOP[];
double TrendBgd[],TREND[],TRENDclr[];
double SigBgd[],SIGNAL[],SIGNALclr[];
double trend[],signal[],xtrend[];
double cscore[];                       // carpet trend score per bar

double maTrH[],maTrL[],maTrT[],maSgH[],maSgL[],maSgT[];
int    hTrH=INVALID_HANDLE,hTrL=INVALID_HANDLE,hTrT=INVALID_HANDLE;
int    hSgH=INVALID_HANDLE,hSgL=INVALID_HANDLE,hSgT=INVALID_HANDLE;

int             trendPer,signalPer,lastScale=-1;

// ---- carpet trend mechanism (ported from EMA_Carpet_3D)
bool            cpOn=false;
ENUM_TIMEFRAMES cpTF;
int             cpPeriod[N_CP];
int             cpHH[N_CP],cpHL[N_CP];      // EMA(high) / EMA(low) handles on cpTF
int             cpCnt[N_CP];
SArr            cpH[N_CP],cpL[N_CP];        // EMA(high)/EMA(low) on cpTF (series)
SArr            cpSt[N_CP];                 // latched state per layer per chart bar: +1 bull, -1 bear
color           cpCol[4];                   // 0 strong bull, 1 weak bull, 2 weak bear, 3 strong bear
ENUM_TIMEFRAMES dopTF;
bool            dopOn;

//+------------------------------------------------------------------+
int OnInit()
  {
   cpOn=(CarpetSrc==CSRC_CARPET || CarpetSrc==CSRC_MATCH);
   cpTF=(CarpetTF==PERIOD_CURRENT)?(ENUM_TIMEFRAMES)_Period:CarpetTF;
   cpPeriod[0]=CarpetP01; cpPeriod[1]=CarpetP02; cpPeriod[2]=CarpetP03; cpPeriod[3]=CarpetP04;
   cpPeriod[4]=CarpetP05; cpPeriod[5]=CarpetP06; cpPeriod[6]=CarpetP07; cpPeriod[7]=CarpetP08;
   cpPeriod[8]=CarpetP09; cpPeriod[9]=CarpetP10; cpPeriod[10]=CarpetP11; cpPeriod[11]=CarpetP12;
   cpPeriod[12]=CarpetP13;
   cpCol[0]=CarpetStrongUp; cpCol[1]=CarpetWeakUp; cpCol[2]=CarpetWeakDn; cpCol[3]=CarpetStrongDn;
   for(int k=0;k<N_CP;k++)
     {
      cpHH[k]=INVALID_HANDLE; cpHL[k]=INVALID_HANDLE; cpCnt[k]=0;
      if(cpOn && cpPeriod[k]<1)
        {
         Print("XU-MA v3: carpet EMA ",k+1," period must be >= 1");
         return(INIT_PARAMETERS_INCORRECT);
        }
     }

   trendPer=TRENDper; signalPer=SIGNALper;
   switch(_Period)
     {
      case PERIOD_M1:  trendPer=36*5; signalPer=9*5; break;
      case PERIOD_M5:  trendPer=36*3; signalPer=9*3; break;
      case PERIOD_M15: trendPer=36*4; signalPer=9*4; break;
      case PERIOD_M30: trendPer=36*2; signalPer=9*2; break;
      case PERIOD_H1:  trendPer=36*1; signalPer=9*1; break;
      default: break;
     }

   // ---- 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);
   SetIndexBuffer(16,cscore,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 (XU-MA), 3..6 = carpet shades, 7=match up 8=match down 9=no match
   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,10);
      PlotIndexSetInteger(p,PLOT_LINE_COLOR,0,cu);
      PlotIndexSetInteger(p,PLOT_LINE_COLOR,1,cw);
      PlotIndexSetInteger(p,PLOT_LINE_COLOR,2,cd);
      for(int c=0;c<4;c++)                                  // carpet shades: colour index 3..6
         PlotIndexSetInteger(p,PLOT_LINE_COLOR,3+c,showCANDLES?cpCol[c]:clrNONE);
      PlotIndexSetInteger(p,PLOT_LINE_COLOR,7,showCANDLES?MatchUpClr:clrNONE);   // match up   (blue)
      PlotIndexSetInteger(p,PLOT_LINE_COLOR,8,showCANDLES?MatchDnClr:clrNONE);   // match down (red)
      PlotIndexSetInteger(p,PLOT_LINE_COLOR,9,showCANDLES?MatchNoClr:clrNONE);   // no match   (white)
      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");

   // ---- moving average handles
   hTrH=iMA(_Symbol,_Period,trendPer, TRENDshft, TRENDmode, PRICE_HIGH);
   hTrL=iMA(_Symbol,_Period,trendPer, TRENDshft, TRENDmode, PRICE_LOW);
   hTrT=iMA(_Symbol,_Period,trendPer, TRENDshft, TRENDmode, TRENDtype);
   hSgH=iMA(_Symbol,_Period,signalPer,SIGNALshft,SIGNALmode,PRICE_HIGH);
   hSgL=iMA(_Symbol,_Period,signalPer,SIGNALshft,SIGNALmode,PRICE_LOW);
   hSgT=iMA(_Symbol,_Period,signalPer,SIGNALshft,SIGNALmode,SIGNALtype);
   if(hTrH==INVALID_HANDLE || hTrL==INVALID_HANDLE || hTrT==INVALID_HANDLE ||
      hSgH==INVALID_HANDLE || hSgL==INVALID_HANDLE || hSgT==INVALID_HANDLE)
     {
      Print("XU-MA v3: failed to create iMA handles");
      return(INIT_FAILED);
     }

   if(cpOn)
      for(int k=0;k<N_CP;k++)
        {
         cpHH[k]=iMA(_Symbol,cpTF,cpPeriod[k],0,MODE_EMA,PRICE_HIGH);
         cpHL[k]=iMA(_Symbol,cpTF,cpPeriod[k],0,MODE_EMA,PRICE_LOW);
         if(cpHH[k]==INVALID_HANDLE || cpHL[k]==INVALID_HANDLE)
           {
            Print("XU-MA v3: failed to create carpet iMA handles for EMA ",k+1);
            return(INIT_FAILED);
           }
        }

   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
   IndicatorSetString(INDICATOR_SHORTNAME,"XU-MA v3");
   fSetBuffers();
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   int h[6]; h[0]=hTrH; h[1]=hTrL; h[2]=hTrT; h[3]=hSgH; h[4]=hSgL; h[5]=hSgT;
   for(int k=0;k<6;k++) if(h[k]!=INVALID_HANDLE) IndicatorRelease(h[k]);
   for(int k=0;k<N_CP;k++)
     {
      if(cpHH[k]!=INVALID_HANDLE) IndicatorRelease(cpHH[k]);
      if(cpHL[k]!=INVALID_HANDLE) IndicatorRelease(cpHL[k]);
     }
   ObjectsDeleteAll(0,ID);
   ChartRedraw();
  }
//+------------------------------------------------------------------+
bool Valid(const double v) { return(v!=0.0 && v!=EMPTY_VALUE); }
//+------------------------------------------------------------------+
//| Carpet trend mechanism (ported from EMA_Carpet_3D)               |
//|  per EMA layer (High/Low latch, as in XU-MA):                    |
//|     close > EMA(high) -> +1 ; close < EMA(low) -> -1 ; else keep |
//|  per strip k: sign( state[k] + state[k+1] )                      |
//|  score = average of the 12 strips * contrast, clamped to [-1,1]  |
//|  score -> 4 shades: strong bull / weak bull / weak bear / strong |
//+------------------------------------------------------------------+
double ValidVal(const double x)
  {
   if(MathIsValidNumber(x) && x>0.0 && x<DBL_MAX) return(x);
   return(-1.0);
  }
//+------------------------------------------------------------------+
int CandleIdx(const double s,const bool candleUp)
  {
   double th=MathMax(0.01,MathMin(1.0,CarpetStrong));
   if(s>=th)  return(0);
   if(s>0.0)  return(1);
   if(s<=-th) return(3);
   if(s<0.0)  return(2);
   return(candleUp?1:2);          // score exactly 0 -> the candle's own direction
  }
//+------------------------------------------------------------------+
int CpShift(const int total,const int i,const datetime t,const int chartSec,const int tfSec)
  {
   if(cpTF==(ENUM_TIMEFRAMES)_Period) return(total-1-i);
   datetime tt=t;
   if(tfSec<chartSec) tt+=chartSec-1;            // value at the close of the chart bar
   return(iBarShift(_Symbol,cpTF,tt,false));
  }
//+------------------------------------------------------------------+
bool CalcCarpet(const int total,const int start,const datetime &time[],
                const double &high[],const double &low[],const double &close[])
  {
   int  chartSec=PeriodSeconds(_Period), tfSec=PeriodSeconds(cpTF);
   bool htf=CarpetNoRepaint && (cpTF!=(ENUM_TIMEFRAMES)_Period) && (tfSec>chartSec);

   for(int k=0;k<N_CP;k++)
      if(BarsCalculated(cpHH[k])<=0 || BarsCalculated(cpHL[k])<=0) return(false);
   int avail=Bars(_Symbol,cpTF);
   if(avail<=0) return(false);

   // higher-TF EMAs are evaluated "as of" each chart bar: restart at the first chart bar of the forming HTF bar
   int cs=start;
   if(htf && cs>0)
     {
      int s0=CpShift(total,start,time[start],chartSec,tfSec);
      while(cs>0 && CpShift(total,cs-1,time[cs-1],chartSec,tfSec)==s0) cs--;
     }

   int tfs[];
   ArrayResize(tfs,total-cs);
   int need=0;
   for(int i=cs;i<total;i++)
     {
      int s=CpShift(total,i,time[i],chartSec,tfSec);
      tfs[i-cs]=s;
      if(s+2>need) need=s+2;
     }
   need=MathMin(need,avail);
   if(need<2) return(false);

   for(int k=0;k<N_CP;k++)
     {
      ArraySetAsSeries(cpH[k].v,true);
      ArraySetAsSeries(cpL[k].v,true);
      int ch=CopyBuffer(cpHH[k],0,0,need,cpH[k].v);
      int cl=CopyBuffer(cpHL[k],0,0,need,cpL[k].v);
      if(ch<=0 || cl<=0) return(false);
      cpCnt[k]=MathMin(ch,cl);
      ArrayResize(cpSt[k].v,total);              // keeps the stored history of latch states
     }

   double rH=0.0,rL=0.0;
   int    prevTf=-2;

   for(int i=cs;i<total;i++)
     {
      int s=tfs[i-cs];

      if(htf && s>=0)                            // running High/Low of the forming HTF bar
        {
         if(s!=prevTf) { rH=high[i]; rL=low[i]; prevTf=s; }
         else
           {
            if(high[i]>rH) rH=high[i];
            if(low[i]<rL)  rL=low[i];
           }
        }

      double cl=close[i];
      for(int k=0;k<N_CP;k++)
        {
         double hi=-1.0,lo=-1.0;
         if(s>=0 && s<cpCnt[k])
           {
            hi=ValidVal(cpH[k].v[s]);
            lo=ValidVal(cpL[k].v[s]);
            if(htf && s+1<cpCnt[k])
              {
               double al=2.0/(cpPeriod[k]+1.0);
               double ph=ValidVal(cpH[k].v[s+1]);
               double pl=ValidVal(cpL[k].v[s+1]);
               if(ph>0.0) hi=rH*al+ph*(1.0-al);
               if(pl>0.0) lo=rL*al+pl*(1.0-al);
              }
           }
         double st=(i>0)?cpSt[k].v[i-1]:0.0;
         if(hi>0.0 && lo>0.0)
           {
            if(cl>hi)      st= 1.0;
            else if(cl<lo) st=-1.0;
           }
         cpSt[k].v[i]=st;
        }

      int sg=0;
      for(int k=0;k<N_CP-1;k++)
        {
         int sum=(int)(cpSt[k].v[i]+cpSt[k+1].v[i]);     // -2 .. +2
         sg+=(sum>0)?1:((sum<0)?-1:0);
        }
      double sc=((double)sg/(N_CP-1))*MathMax(0.0,CarpetContrast);
      if(sc> 1.0) sc= 1.0;
      if(sc<-1.0) sc=-1.0;
      cscore[i]=sc;
     }
   return(true);
  }
//+------------------------------------------------------------------+
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();

   if(BarsCalculated(hTrH)<rates_total || BarsCalculated(hTrL)<rates_total || BarsCalculated(hTrT)<rates_total ||
      BarsCalculated(hSgH)<rates_total || BarsCalculated(hSgL)<rates_total || BarsCalculated(hSgT)<rates_total)
      return(prev_calculated);

   int start=(prev_calculated>0)?prev_calculated-1:0;
   int from =(start>0)?start-1:0;          // MA arrays are indexed [bar-from]
   int count=rates_total-from;

   if(CopyBuffer(hTrH,0,0,count,maTrH)!=count || CopyBuffer(hTrL,0,0,count,maTrL)!=count ||
      CopyBuffer(hTrT,0,0,count,maTrT)!=count || CopyBuffer(hSgH,0,0,count,maSgH)!=count ||
      CopyBuffer(hSgL,0,0,count,maSgL)!=count || CopyBuffer(hSgT,0,0,count,maSgT)!=count)
      return(prev_calculated);

   if(cpOn && !CalcCarpet(rates_total,start,time,high,low,close))
      return(prev_calculated);                 // carpet EMA data not ready yet -> retry next tick

   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=maTrH[i-1-from], l=maTrL[i-1-from];
         if(Valid(h) && close[i]>h) trend[i]= 1;
         if(Valid(l) && close[i]<l) trend[i]=-1;
        }
      double t=maTrT[i-from];
      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=maSgH[i-1-from], l=maSgL[i-1-from];
         if(Valid(h) && close[i]>h) signal[i]= 1;
         if(Valid(l) && close[i]<l) signal[i]=-1;
        }
      double s=maSgT[i-from];
      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; }
      WickHi[i]=high[i]; WickLo[i]=low[i];
      BodyHi[i]=MathMax(open[i],close[i]); BodyLo[i]=MathMin(open[i],close[i]);
      if(CarpetSrc==CSRC_CARPET)
         dir=3+CandleIdx(cscore[i],close[i]>=open[i]);          // carpet shade (colour index 3..6)
      else if(CarpetSrc==CSRC_MATCH)
        {
         // carpet candle colour family: shade 0,1 = bull (blue family), 2,3 = bear (red family)
         int  ci      =CandleIdx(cscore[i],close[i]>=open[i]);
         bool carpetUp=(ci<=1), carpetDn=(ci>=2);
         if(xtrend[i]== 1 && carpetUp)      dir=7;             // both UP   -> blue
         else if(xtrend[i]==-1 && carpetDn) dir=8;             // both DOWN -> red
         else                               dir=9;             // anything else -> white
        }
      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;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);
  }
//+------------------------------------------------------------------+
