//+------------------------------------------------------------------+
//|                                       XU-MA v3 - Jurik BGD zones |
//|   Reduced version of "XU-MA v3" (XARD UNIVERSE):                 |
//|   - BGD background zones coloured from the Jurik moving average  |
//|     TREND state (close vs the Jurik high / low lines), optional  |
//|     higher timeframe (BgdZonesTF)                                |
//|   - Jurik MA slope candle colouring (jurik_filter by mladen)     |
//|     matched to the background zones (blue zone: no red candles,  |
//|     red zone: no blue candles)                                   |
//|   - 3D carpet canvas (EMA surface) in the background layer,      |
//|     ON / OFF button on the chart                                 |
//|   - UP arrow: blue candle on blue background, DOWN arrow: red    |
//|     candle on red background (type / size / colours adjustable)  |
//+------------------------------------------------------------------+
#property link        "https://forex-station.com/viewtopic.php?p=1295409935#p1295409935"
#property version     "3.30"
#property description "[XU-MA v3] reduced: Jurik BGD background zones + Jurik slope candle colouring"
#property description "+ UP / DOWN arrows when candle colour and background zone colour match (blue / red family)"
#property description "+ 3D carpet canvas (EMA surface) in the background layer, ON/OFF button"
#property description "THIS IS A FREE INDICATOR"
#property description " "
#property description "Welcome to XARD UNIVERSE"

#property indicator_chart_window
#property indicator_buffers 9
#property indicator_plots   4

// 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 : MATCH arrow UP   (blue candle + blue background)   buffer 6
// plot 3 : MATCH arrow DOWN (red candle  + red background)    buffer 7
// calc   : trend                                  buffer  8
#property indicator_type1 DRAW_COLOR_HISTOGRAM2
#property indicator_type2 DRAW_COLOR_HISTOGRAM2
#property indicator_type3 DRAW_ARROW
#property indicator_type4 DRAW_ARROW

#define ID "XUMA_"

#include <Canvas\Canvas.mqh>

//+------------------------------------------------------------------+
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] TREND (Jurik) settings - drives the BGD zones ====>>>"
input ENUM_TIMEFRAMES   TRENDtf    = PERIOD_H1;        // TREND timeframe (current = chart)
input int               TRENDper   = 1;
input int               TRENDshft  = 0;
input double            TRENDphase = 0;                 // Jurik phase (-100 .. +100)
input ENUM_APPLIED_PRICE TRENDtype = PRICE_MEDIAN;
input bool              ScalePerByTF = false;           // true = multiply TRENDper by M1:5 M5:3 M15:4 M30:2 H1:1
input bool              MTFclosedBar = false;           // use last CLOSED higher-TF bar (no repaint)

input group "<<<==== [03] BGDzones Settings ====>>>"
input bool            showBGDzones = true;
input color           ColorUp      = C'18,45,58';
input color           ColorDown    = C'58,28,58';
input color           ColorWait    = C'91,103,112';
input int             ZonesMaxBars = 5000;              // limit zones to last N bars (0 = all)
input bool            BgCandleFilterOn = true;          // blue background: red candles white; red background: blue candles white
input ENUM_TIMEFRAMES BgdZonesTF   = PERIOD_D1;         // BGD zones timeframe (D1 colours on all lower timeframes)
input bool            BgMtfClosed  = false;             // true = a higher-TF bar uses the last CLOSED higher-TF bar (no repaint)

input group "<<<==== [04] Jurik slope candle filter (jurik_filter by mladen) ====>>>"
// slope = Jurik value of the current higher-TF bar vs the previous higher-TF bar
//   slope UP -> candle blue (CandleUp), slope DOWN -> candle red (CandleDn), flat -> white (CandleWt)
input ENUM_TIMEFRAMES   JsTF            = PERIOD_H1;     // Jurik MA timeframe (current = chart)
input int               JsLength        = 6;             // Jurik MA period (jurik_filter "Length")
input double            JsPhase         = 0;             // Jurik MA phase (-100 .. +100)
input ENUM_APPLIED_PRICE JsPrice        = PRICE_CLOSE;   // Jurik MA applied price

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

//--- applied price of the 3D carpet EMAs (full list of the original carpet indicator)
enum enCarpetPrice
  {
   cp_close,      // Close
   cp_open,       // Open
   cp_high,       // High
   cp_low,        // Low
   cp_median,     // Median
   cp_typical,    // Typical
   cp_weighted,   // Weighted
   cp_average,    // Average (high+low+open+close)/4
   cp_medianb,    // Average median body (open+close)/2
   cp_tbiased,    // Trend biased price
   cp_tbiased2,   // Trend biased (extreme) price
   cp_haclose,    // Heiken ashi close
   cp_haopen ,    // Heiken ashi open
   cp_hahigh,     // Heiken ashi high
   cp_halow,      // Heiken ashi low
   cp_hamedian,   // Heiken ashi median
   cp_hatypical,  // Heiken ashi typical
   cp_haweighted, // Heiken ashi weighted
   cp_haaverage,  // Heiken ashi average
   cp_hamedianb,  // Heiken ashi median body
   cp_hatbiased,  // Heiken ashi trend biased price
   cp_hatbiased2  // Heiken ashi trend biased (extreme) price
  };

input group "<<<==== [05] 3D Carpet Canvas (EMA surface in the background) ====>>>"
// A surface of EMAs (rows = EMA periods stepping upward) painted on a canvas bitmap in the chart background,
// above the BGD zones and below the candles. The button on the chart switches it ON / OFF at any time.
input bool            ShowCarpet        = true;           // Carpet ON at start (the chart button toggles it)
input int             CarpetBtnX        = 10;             // Toggle button X (pixels from the left)
input int             CarpetBtnY        = 20;             // Toggle button Y (pixels from the top)
input bool            CarpetSeparate    = true;           // true = 3 SEPARATE carpets (one per EMA below), false = single surface front->back
input int             CarpetEma1Period  = 20;             // Separate mode: carpet 1 EMA period
input int             CarpetEma2Period  = 50;             // Separate mode: carpet 2 EMA period
input int             CarpetEma3Period  = 200;            // Separate mode: carpet 3 EMA period
input int             CarpetRibbonLayers= 6;              // Separate mode: depth rows of each carpet (2..30)
input color           CarpetCol1Up      = clrGreen;   // Carpet 1 (20)  rising colour
input color           CarpetCol1Down    = clrDarkOrange;  // Carpet 1 (20)  falling colour
input color           CarpetCol2Up      = clrTeal;  // Carpet 2 (50)  rising colour
input color           CarpetCol2Down    = clrCrimson;     // Carpet 2 (50)  falling colour
input color           CarpetCol3Up      = clrSeaGreen;        // Carpet 3 (200) rising colour
input color           CarpetCol3Down    = clrMagenta;     // Carpet 3 (200) falling colour
input int             CarpetEmaPeriod   = 20;             // EMA period (front edge of the carpet)
input enCarpetPrice   CarpetEmaPrice    = cp_close;       // Average price
input int             CarpetLayers      = 12;             // Carpet depth rows (2..30)
input int             CarpetBackPeriod  = 200;            // EMA period at the BACK edge (0 = off, use CarpetPeriodStep instead)
input int             CarpetPeriodStep  = 4;              // EMA period added per depth row (only used when CarpetBackPeriod = 0)
input bool            CarpetPinEdges    = true;           // true = front row sits exactly on EMA front, back row exactly on EMA back (depth shift arches in between)
input int             CarpetDepthX      = 3;              // Depth shift per row, pixels right (negative = left)
input int             CarpetDepthY      = 5;              // Depth shift per row, pixels up (negative = down)
input int             CarpetThickness   = 8;              // Front face thickness, pixels (0 = none)
input int             CarpetMaxBars     = 400;            // Max visible bars to draw
input color           CarpetColUp       = clrLimeGreen;   // Rising colour
input color           CarpetColDown     = clrDarkOrange;  // Falling colour
input color           CarpetColFlat     = clrDarkGray;    // Flat colour
input bool            CarpetLighting    = true;           // Slope based lighting
input int             CarpetFadeBack    = 70;             // Fade to background at the back, % (0..100)
input bool            CarpetShowMesh    = true;           // Draw mesh lines on rows
input color           CarpetMeshColor   = clrWhite;       // Mesh colour
input int             CarpetMeshAlpha   = 70;             // Mesh opacity (0..255)
input int             CarpetAlpha       = 255;            // Carpet opacity (0..255, below 255 may show seams)
input int             CarpetRedrawMs    = 200;            // Min ms between redraws on ticks

input group "<<<==== [06] Candle / background MATCH arrows ====>>>"
// blue candle + blue (up) background zone -> UP   arrow below the candle
// red  candle + red  (down) background zone -> DOWN arrow above the candle
input bool            ShowMatchArrows = true;           // Draw the match arrows
input bool            ArrowFirstOnly  = true;           // true = only the FIRST candle of every match run, false = every matching candle
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      = clrLime;        // UP arrow colour
input color           ArrowDnClr      = clrRed;         // DOWN arrow colour

//+------------------------------------------------------------------+
//| 3D CARPET CANVAS  (extracted from "EMA 3D Carpet (Canvas)")       |
//| A surface of EMAs (rows = EMA periods stepping upward) drawn on a |
//| canvas bitmap with oblique projection, per-cell lighting, depth   |
//| fade and a thick front edge. The bitmap lives in the chart        |
//| BACKGROUND layer together with the BGD zones (above the zones,    |
//| below the candles). An on-chart button switches it ON / OFF.      |
//+------------------------------------------------------------------+
#define CARPET_MAX_LAYERS 30
#define CARPET_BTN        "XUMA_CarpetBtn"

struct SCarpetLayer { double v[]; };

SCarpetLayer cpL[CARPET_MAX_LAYERS];   // EMA of every carpet row (row 0 = front edge)
SCarpetLayer cpE[3];                    // separate mode: one EMA per carpet (20 / 50 / 200)
datetime     cpTime[];                 // bar times
int          cpTotal=0;                // bars stored
int          cpN=12;                   // rows in use
CCanvas      cpCanvas;
string       cpObj="";                 // name of the bitmap object
bool         cpReady=false;            // canvas exists
bool         g_carpetOn=false;         // current ON / OFF state (button)
bool         g_zoneTouched=false;      // a zone rectangle was created -> canvas must go back on top
ulong        cpLastDraw=0;
int          cpSeq=0;
double       cpHa[][4];                // Heiken Ashi work array for the HA price options
double       cpPx[];                   // carpet applied price of every chart bar

//+------------------------------------------------------------------+
//| colour helpers                                                   |
//+------------------------------------------------------------------+
uint CpARGB(int r,int g,int b,int a)
  {
   r=MathMax(0,MathMin(255,r)); g=MathMax(0,MathMin(255,g)); b=MathMax(0,MathMin(255,b));
   a=MathMax(0,MathMin(255,a));
   return(((uint)a<<24)|((uint)r<<16)|((uint)g<<8)|(uint)b);
  }
//+------------------------------------------------------------------+
uint CpShade(color c,double light,color bg,double mix,int alpha)
  {
   double r=(double)(c&0xFF), g=(double)((c>>8)&0xFF), b=(double)((c>>16)&0xFF);
   double br=(double)(bg&0xFF), bgc=(double)((bg>>8)&0xFF), bb=(double)((bg>>16)&0xFF);
   r*=light; g*=light; b*=light;
   r=r+(br -r)*mix;
   g=g+(bgc-g)*mix;
   b=b+(bb -b)*mix;
   return(CpARGB((int)r,(int)g,(int)b,alpha));
  }

//+------------------------------------------------------------------+
//| canvas life cycle                                                |
//+------------------------------------------------------------------+
void CarpetDestroyCanvas()
  {
   cpReady=false;
   cpCanvas.Destroy();
   if(cpObj!="") { ObjectDelete(0,cpObj); cpObj=""; }
  }
//+------------------------------------------------------------------+
//| (Re)creates the bitmap. Creating it again also moves it to the   |
//| top of the background objects, i.e. above the zone rectangles.   |
//+------------------------------------------------------------------+
bool CarpetCreateCanvas()
  {
   CarpetDestroyCanvas();
   int w=(int)ChartGetInteger(0,CHART_WIDTH_IN_PIXELS);
   int h=(int)ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0);
   if(w<10) w=10;
   if(h<10) h=10;
   cpSeq++;
   cpObj=ID+"Carpet_"+IntegerToString(cpSeq)+"_"+IntegerToString((long)GetMicrosecondCount());
   if(!cpCanvas.CreateBitmapLabel(0,0,cpObj,0,0,w,h,COLOR_FORMAT_ARGB_NORMALIZE))
     {
      Print("XU-MA v3: 3D carpet canvas creation failed, error ",GetLastError());
      cpObj="";
      return(false);
     }
   ObjectSetInteger(0,cpObj,OBJPROP_BACK,true);          // price / candles are drawn above the carpet
   ObjectSetInteger(0,cpObj,OBJPROP_SELECTABLE,false);
   ObjectSetInteger(0,cpObj,OBJPROP_HIDDEN,true);
   cpReady=true;
   g_zoneTouched=false;
   return(true);
  }

//+------------------------------------------------------------------+
//| ON / OFF button                                                  |
//+------------------------------------------------------------------+
void CarpetButtonUpdate()
  {
   string nm=CARPET_BTN;
   if(ObjectFind(0,nm)<0)
     {
      ObjectCreate(0,nm,OBJ_BUTTON,0,0,0);
      ObjectSetInteger(0,nm,OBJPROP_CORNER,CORNER_LEFT_UPPER);
      ObjectSetInteger(0,nm,OBJPROP_XSIZE,120);
      ObjectSetInteger(0,nm,OBJPROP_YSIZE,22);
      ObjectSetInteger(0,nm,OBJPROP_FONTSIZE,9);
      ObjectSetString (0,nm,OBJPROP_FONT,"Arial");
      ObjectSetInteger(0,nm,OBJPROP_BACK,false);
      ObjectSetInteger(0,nm,OBJPROP_SELECTABLE,false);
      ObjectSetInteger(0,nm,OBJPROP_HIDDEN,true);
      ObjectSetInteger(0,nm,OBJPROP_ZORDER,100);
      ObjectSetString (0,nm,OBJPROP_TOOLTIP,"Click: switch the 3D carpet canvas ON / OFF");
     }
   ObjectSetInteger(0,nm,OBJPROP_XDISTANCE,CarpetBtnX);
   ObjectSetInteger(0,nm,OBJPROP_YDISTANCE,CarpetBtnY);
   ObjectSetInteger(0,nm,OBJPROP_STATE,g_carpetOn);
   ObjectSetString (0,nm,OBJPROP_TEXT,g_carpetOn?"3D Carpet : ON":"3D Carpet : OFF");
   ObjectSetInteger(0,nm,OBJPROP_BGCOLOR,g_carpetOn?C'30,110,60':C'70,70,70');
   ObjectSetInteger(0,nm,OBJPROP_BORDER_COLOR,g_carpetOn?clrLimeGreen:clrDimGray);
   ObjectSetInteger(0,nm,OBJPROP_COLOR,clrWhite);
  }
//+------------------------------------------------------------------+
void CarpetSetState(const bool on)
  {
   g_carpetOn=on;
   if(on)
     {
      if(CarpetCreateCanvas()) { CarpetRender(); cpLastDraw=GetTickCount64(); }
      else g_carpetOn=false;
     }
   else
      CarpetDestroyCanvas();
   CarpetButtonUpdate();
   ChartRedraw();
  }

//+------------------------------------------------------------------+
//| depth weight of row j. Pinned: 0 at the front AND at the back row |
//| (so both edges are drawn on their true EMA position), arching in  |
//| between. Not pinned: old behaviour, grows linearly with j.        |
//+------------------------------------------------------------------+
double CarpetDepthW(const int j)
  {
   if(CarpetPinEdges && cpN>1) return((double)j*(cpN-1-j)/(double)(cpN-1));
   return((double)j);
  }
//+------------------------------------------------------------------+
//| separate mode: EMA period / colours of carpet m (0,1,2)           |
//+------------------------------------------------------------------+
int CarpetEmaPeriodOf(const int m)
  { return((m==0)?CarpetEma1Period:(m==1)?CarpetEma2Period:CarpetEma3Period); }
color CarpetUpOf(const int m)   { return((m==0)?CarpetCol1Up  :(m==1)?CarpetCol2Up  :CarpetCol3Up);   }
color CarpetDownOf(const int m) { return((m==0)?CarpetCol1Down:(m==1)?CarpetCol2Down:CarpetCol3Down); }

//+------------------------------------------------------------------+
//| EMA period of carpet row j: row 0 = front edge = CarpetEmaPeriod, |
//| last row = back edge = CarpetBackPeriod, rows in between spread   |
//| evenly (linear). CarpetBackPeriod = 0 -> old fixed step.          |
//+------------------------------------------------------------------+
int CarpetRowPeriod(const int j)
  {
   if(CarpetBackPeriod>0 && cpN>1)
      return(MathMax((int)MathRound(CarpetEmaPeriod+(double)j*(CarpetBackPeriod-CarpetEmaPeriod)/(cpN-1)),1));
   return(MathMax(CarpetEmaPeriod+j*CarpetPeriodStep,1));
  }
//+------------------------------------------------------------------+
//| EMA surface calculation (incremental, runs from OnCalculate)     |
//+------------------------------------------------------------------+
void CarpetCalc(const int total,const int prev,const datetime &time[],
                const double &open[],const double &high[],const double &low[],const double &close[])
  {
   if(total<2) return;

   int start=(ArraySize(cpTime)==0)?0:(int)MathMax(prev-1,0);     // arrays were freed -> everything again
   if(ArraySize(cpTime)!=total)
     {
      ArrayResize(cpTime,total);
      for(int j=0;j<cpN;j++) ArrayResize(cpL[j].v,total);
      for(int m=0;m<3;m++)   ArrayResize(cpE[m].v,total);
      ArrayResize(cpPx,total);
     }
   cpTotal=total;

   for(int i=start;i<total && !IsStopped();i++)
     {
      cpTime[i]=time[i];
      double price=CpPrice(CarpetEmaPrice,open,close,high,low,i,total);
      cpPx[i]=price;
      for(int j=0;j<cpN;j++)
        {
         int    period=CarpetRowPeriod(j);
         double alpha =2.0/(1.0+period);
         cpL[j].v[i]=(i>0)?cpL[j].v[i-1]+alpha*(price-cpL[j].v[i-1]):price;
        }
      for(int m=0;m<3;m++)
        {
         int    pe=MathMax(CarpetEmaPeriodOf(m),1);
         double al=2.0/(1.0+pe);
         cpE[m].v[i]=(i>0)?cpE[m].v[i-1]+al*(price-cpE[m].v[i-1]):price;
        }
     }
  }

//+------------------------------------------------------------------+
//| redraw (throttled) - also puts the canvas back on top of any     |
//| zone rectangle that was created since the last drawing           |
//+------------------------------------------------------------------+
void CarpetUpdate(const bool force)
  {
   if(!g_carpetOn) return;
   bool must=force;
   if(g_zoneTouched)
     {
      if(!CarpetCreateCanvas()) return;
      must=true;
     }
   if(!cpReady) return;
   ulong now=GetTickCount64();
   if(must || now-cpLastDraw>=(ulong)MathMax(CarpetRedrawMs,0))
     {
      CarpetRender();
      cpLastDraw=now;
     }
  }

//+------------------------------------------------------------------+
//| separate mode: 3 independent carpets (ribbons), one per EMA.      |
//| The FRONT edge of every carpet lies exactly on its EMA, the carpet|
//| extends backwards (depth shift). Painted 200 -> 50 -> 20 so the   |
//| fastest EMA ends up on top.                                       |
//+------------------------------------------------------------------+
void CarpetRenderSeparate(const int w,const int h,const double pmax,const double pmin,
                          const int step,const int iL,const int iR,const int xr)
  {
   int    n     =iR-iL+1;
   int    R     =MathMax(2,MathMin(CARPET_MAX_LAYERS,CarpetRibbonLayers));
   double scaleY=(h-1)/(pmax-pmin);
   color  bg    =(color)ChartGetInteger(0,CHART_COLOR_BACKGROUND);
   double fadeMax=MathMax(0,MathMin(100,CarpetFadeBack))/100.0;
   int    ca    =MathMax(0,MathMin(255,CarpetAlpha));
   uint   meshClr=CpARGB((int)(CarpetMeshColor&0xFF),(int)((CarpetMeshColor>>8)&0xFF),(int)((CarpetMeshColor>>16)&0xFF),CarpetMeshAlpha);

   int xs[]; ArrayResize(xs,n);
   int ys[]; ArrayResize(ys,n);

   for(int m=2;m>=0;m--)
     {
      if(ArraySize(cpE[m].v)<cpTotal) continue;
      color cUp=CarpetUpOf(m), cDn=CarpetDownOf(m);
      for(int k=0;k<n;k++)
        {
         xs[k]=xr-(iR-(iL+k))*step;
         ys[k]=(int)MathRound((pmax-cpE[m].v[iL+k])*scaleY);
        }

      for(int j=R-2;j>=0;j--)
        {
         double t =(double)j/(R-2);
         double mx=fadeMax*t;
         int    oj=j*CarpetDepthX,   oj1=(j+1)*CarpetDepthX;
         int    pj=-j*CarpetDepthY,  pj1=-(j+1)*CarpetDepthY;

         for(int k=0;k<n-1;k++)
           {
            int x0=xs[k]  +oj,  y0=ys[k]  +pj;
            int x1=xs[k+1]+oj,  y1=ys[k+1]+pj;
            int x2=xs[k+1]+oj1, y2=ys[k+1]+pj1;
            int x3=xs[k]  +oj1, y3=ys[k]  +pj1;

            if(MathMax(MathMax(y0,y1),MathMax(y2,y3))<0 || MathMin(MathMin(y0,y1),MathMin(y2,y3))>=h) continue;
            if(MathMax(MathMax(x0,x1),MathMax(x2,x3))<0 || MathMin(MathMin(x0,x1),MathMin(x2,x3))>=w) continue;

            double d   =cpE[m].v[iL+k+1]-cpE[m].v[iL+k];
            color  base=(d>0)?cUp:(d<0)?cDn:CarpetColFlat;
            double lit =1.0;
            if(CarpetLighting) lit=MathMax(0.6,MathMin(1.3,1.0-(double)(y1-y0)*0.05));
            uint   c   =CpShade(base,lit,bg,mx,ca);

            cpCanvas.FillTriangle(x0,y0,x1,y1,x2,y2,c);
            cpCanvas.FillTriangle(x0,y0,x2,y2,x3,y3,c);
            cpCanvas.Line(x0,y0,x1,y1,c);
            cpCanvas.Line(x1,y1,x2,y2,c);
           }

         if(CarpetShowMesh)
            for(int k=0;k<n-1;k++)
               cpCanvas.LineAA(xs[k]+oj1,ys[k]+pj1,xs[k+1]+oj1,ys[k+1]+pj1,meshClr);
        }

      //--- front face (thickness) and bright front edge = the true EMA line
      for(int k=0;k<n-1;k++)
        {
         int x0=xs[k],   y0=ys[k];
         int x1=xs[k+1], y1=ys[k+1];
         double d   =cpE[m].v[iL+k+1]-cpE[m].v[iL+k];
         color  base=(d>0)?cUp:(d<0)?cDn:CarpetColFlat;
         if(CarpetThickness>0)
           {
            uint cf=CpShade(base,0.45,bg,0.0,ca);
            cpCanvas.FillTriangle(x0,y0,x1,y1,x1,y1+CarpetThickness,cf);
            cpCanvas.FillTriangle(x0,y0,x1,y1+CarpetThickness,x0,y0+CarpetThickness,cf);
            cpCanvas.Line(x0,y0+CarpetThickness,x1,y1+CarpetThickness,cf);
            cpCanvas.Line(x1,y1,x1,y1+CarpetThickness,cf);
           }
         uint ce=CpShade(base,1.15,bg,0.0,255);
         cpCanvas.Line(x0,y0,x1,y1,ce);
         cpCanvas.Line(x0,y0-1,x1,y1-1,ce);
        }
     }
  }

//+------------------------------------------------------------------+
//| the 3D renderer                                                  |
//+------------------------------------------------------------------+
void CarpetRender()
  {
   if(!cpReady || cpTotal<3 || ArraySize(cpTime)<cpTotal) return;

   int w=(int)ChartGetInteger(0,CHART_WIDTH_IN_PIXELS);
   int h=(int)ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0);
   if(w<10 || h<10) return;
   if(w!=cpCanvas.Width() || h!=cpCanvas.Height()) cpCanvas.Resize(w,h);
   cpCanvas.Erase(0);

   double pmax=ChartGetDouble(0,CHART_PRICE_MAX,0);
   double pmin=ChartGetDouble(0,CHART_PRICE_MIN,0);
   if(pmax<=pmin) { cpCanvas.Update(); return; }

   int step=1<<(int)ChartGetInteger(0,CHART_SCALE);
   int fs  =(int)ChartGetInteger(0,CHART_FIRST_VISIBLE_BAR);
   int vis =(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
   int sR  =MathMax(fs-vis+1,0);
   int iR  =cpTotal-1-sR;
   int iL  =MathMax(cpTotal-1-fs,0);
   iL=MathMax(iL,iR-MathMax(CarpetMaxBars,2)+1);
   if(iR-iL<1) { cpCanvas.Update(); return; }

   int xr,yr;
   if(!ChartTimePriceToXY(0,0,cpTime[iR],(pmax+pmin)/2.0,xr,yr)) return;
   if(CarpetSeparate) { CarpetRenderSeparate(w,h,pmax,pmin,step,iL,iR,xr); cpCanvas.Update(); return; }

   int n=iR-iL+1;
   int xs[]; ArrayResize(xs,n);
   int ys[]; ArrayResize(ys,n*cpN);
   double scaleY=(h-1)/(pmax-pmin);
   for(int k=0;k<n;k++)
     {
      xs[k]=xr-(iR-(iL+k))*step;
      for(int j=0;j<cpN;j++)
         ys[j*n+k]=(int)MathRound((pmax-cpL[j].v[iL+k])*scaleY);
     }

   color  bg     =(color)ChartGetInteger(0,CHART_COLOR_BACKGROUND);
   double fadeMax=MathMax(0,MathMin(100,CarpetFadeBack))/100.0;
   int    ca     =MathMax(0,MathMin(255,CarpetAlpha));
   uint   meshClr=CpARGB((int)(CarpetMeshColor&0xFF),(int)((CarpetMeshColor>>8)&0xFF),(int)((CarpetMeshColor>>16)&0xFF),CarpetMeshAlpha);

   //--- surface strips, painted from the back row to the front row
   for(int j=cpN-2;j>=0;j--)
     {
      double t =(double)j/(cpN-2);
      double mx=fadeMax*t;
      double wj=CarpetDepthW(j), wj1=CarpetDepthW(j+1);
      int    oj=(int)MathRound(wj*CarpetDepthX),   oj1=(int)MathRound(wj1*CarpetDepthX);
      int    pj=-(int)MathRound(wj*CarpetDepthY),  pj1=-(int)MathRound(wj1*CarpetDepthY);

      for(int k=0;k<n-1;k++)
        {
         int x0=xs[k]  +oj,  y0=ys[j*n+k]      +pj;
         int x1=xs[k+1]+oj,  y1=ys[j*n+k+1]    +pj;
         int x2=xs[k+1]+oj1, y2=ys[(j+1)*n+k+1]+pj1;
         int x3=xs[k]  +oj1, y3=ys[(j+1)*n+k]  +pj1;

         // cull cells that are completely off the canvas
         if(MathMax(MathMax(y0,y1),MathMax(y2,y3))<0 || MathMin(MathMin(y0,y1),MathMin(y2,y3))>=h) continue;
         if(MathMax(MathMax(x0,x1),MathMax(x2,x3))<0 || MathMin(MathMin(x0,x1),MathMin(x2,x3))>=w) continue;

         double d   =cpL[j].v[iL+k+1]-cpL[j].v[iL+k];
         color  base=(d>0)?CarpetColUp:(d<0)?CarpetColDown:CarpetColFlat;
         double lit =1.0;
         if(CarpetLighting) lit=MathMax(0.6,MathMin(1.3,1.0-(double)(y1-y0)*0.05));
         uint   c   =CpShade(base,lit,bg,mx,ca);

         cpCanvas.FillTriangle(x0,y0,x1,y1,x2,y2,c);
         cpCanvas.FillTriangle(x0,y0,x2,y2,x3,y3,c);
         cpCanvas.Line(x0,y0,x1,y1,c);     // close hairline gaps between cells
         cpCanvas.Line(x1,y1,x2,y2,c);
        }

      if(CarpetShowMesh)       // mesh line on the far edge of this strip (row j+1)
        {
         for(int k=0;k<n-1;k++)
            cpCanvas.LineAA(xs[k]+oj1,ys[(j+1)*n+k]+pj1,xs[k+1]+oj1,ys[(j+1)*n+k+1]+pj1,meshClr);
        }
     }

   //--- front face (thickness) and the bright front edge
   for(int k=0;k<n-1;k++)
     {
      int x0=xs[k],   y0=ys[k];
      int x1=xs[k+1], y1=ys[k+1];
      double d   =cpL[0].v[iL+k+1]-cpL[0].v[iL+k];
      color  base=(d>0)?CarpetColUp:(d<0)?CarpetColDown:CarpetColFlat;

      if(CarpetThickness>0)
        {
         uint cf=CpShade(base,0.45,bg,0.0,ca);
         cpCanvas.FillTriangle(x0,y0,x1,y1,x1,y1+CarpetThickness,cf);
         cpCanvas.FillTriangle(x0,y0,x1,y1+CarpetThickness,x0,y0+CarpetThickness,cf);
         cpCanvas.Line(x0,y0+CarpetThickness,x1,y1+CarpetThickness,cf);
         cpCanvas.Line(x1,y1,x1,y1+CarpetThickness,cf);
        }
      uint ce=CpShade(base,1.15,bg,0.0,255);
      cpCanvas.Line(x0,y0,x1,y1,ce);
      cpCanvas.Line(x0,y0-1,x1,y1-1,ce);
     }

   cpCanvas.Update();
  }

//+------------------------------------------------------------------+
//| applied price of the carpet EMAs (incl. Heiken Ashi variants)    |
//+------------------------------------------------------------------+
double CpPriceH(const int tprice,const double &open[],const double &close[],const double &high[],const double &low[],const int i,const int _bars,double &ha[][4])
  {
   if(tprice>=cp_haclose)
     {
      if(ArrayRange(ha,0)!=_bars) ArrayResize(ha,_bars);

      double haOpen;
      if(i>0) haOpen=(ha[i-1][2]+ha[i-1][3])/2.0;
      else    haOpen=(open[i]+close[i])/2;
      double haClose=(open[i]+high[i]+low[i]+close[i])/4.0;
      double haHigh =MathMax(high[i],MathMax(haOpen,haClose));
      double haLow  =MathMin(low[i] ,MathMin(haOpen,haClose));

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

      switch(tprice)
        {
         case cp_haclose:     return(haClose);
         case cp_haopen:      return(haOpen);
         case cp_hahigh:      return(haHigh);
         case cp_halow:       return(haLow);
         case cp_hamedian:    return((haHigh+haLow)/2.0);
         case cp_hamedianb:   return((haOpen+haClose)/2.0);
         case cp_hatypical:   return((haHigh+haLow+haClose)/3.0);
         case cp_haweighted:  return((haHigh+haLow+haClose+haClose)/4.0);
         case cp_haaverage:   return((haHigh+haLow+haClose+haOpen)/4.0);
         case cp_hatbiased:
            if(haClose>haOpen) return((haHigh+haClose)/2.0);
            else               return((haLow+haClose)/2.0);
         case cp_hatbiased2:
            if(haClose>haOpen) return(haHigh);
            if(haClose<haOpen) return(haLow);
            return(haClose);
        }
     }

   switch(tprice)
     {
      case cp_close:     return(close[i]);
      case cp_open:      return(open[i]);
      case cp_high:      return(high[i]);
      case cp_low:       return(low[i]);
      case cp_median:    return((high[i]+low[i])/2.0);
      case cp_medianb:   return((open[i]+close[i])/2.0);
      case cp_typical:   return((high[i]+low[i]+close[i])/3.0);
      case cp_weighted:  return((high[i]+low[i]+close[i]+close[i])/4.0);
      case cp_average:   return((high[i]+low[i]+close[i]+open[i])/4.0);
      case cp_tbiased:
         if(close[i]>open[i]) return((high[i]+close[i])/2.0);
         else                 return((low[i]+close[i])/2.0);
      case cp_tbiased2:
         if(close[i]>open[i]) return(high[i]);
         if(close[i]<open[i]) return(low[i]);
         return(close[i]);
     }
   return(0);
  }
//+------------------------------------------------------------------+
double CpPrice(const int tprice,const double &open[],const double &close[],const double &high[],const double &low[],const int i,const int _bars)
  { return(CpPriceH(tprice,open,close,high,low,i,_bars,cpHa)); }

//+------------------------------------------------------------------+
bool Valid(const double v) { return(v!=0.0 && v!=EMPTY_VALUE && MathIsValidNumber(v)); }

//--- match state of one bar: +1 = blue candle on blue background, -1 = red candle on red background, 0 = no match
//    candleIdx : 0 = blue candle, 1 = white, 2 = red candle     bgState : 1 = blue zone, -1 = red zone, 0 = wait
int MatchOf(const int candleIdx,const int bgState)
  {
   if(candleIdx==0 && bgState== 1) return( 1);
   if(candleIdx==2 && bgState==-1) 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;
     }
  }

//+------------------------------------------------------------------+
//| 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
   double             m_mp[];              // applied-price value of the PREVIOUS higher-TF bar, 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); ArrayFree(m_mp);
     }

   //--- 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); ArrayResize(m_mp,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; m_mp[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); m_mp[i]=(x-1>=m_len)?m_jt.Get(x-1,n):EMPTY_VALUE; }
        }
      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]); }
   double TP(const int idx,const int total) const { return((idx<0||idx>=total||idx>=ArraySize(m_mp))?EMPTY_VALUE:m_mp[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);
  }

//+------------------------------------------------------------------+
//| globals                                                          |
//+------------------------------------------------------------------+
int    bgZ[];                          // BGD zone state per chart bar (1 / -1 / 0)
ENUM_TIMEFRAMES bgTfZ=PERIOD_CURRENT;
//--- BGD zones on a higher timeframe: the TREND state is calculated on the bars of that timeframe
CMtfJurik mBgd;                        // TREND Jurik lines on the BGD timeframe
datetime  bdT[];                       // bars of the BGD timeframe (times / OHLC)
double    bdO[],bdH[],bdL[],bdC[];
double    bdTrend[];                   // trend state (1 / -1 / 0) per BGD-timeframe bar
int       bdN=0;                       // bars copied
datetime  bdFirst=0;                   // time of the oldest bar copied (detects history changes)

double WickHi[],WickLo[],WickClr[];
double BodyHi[],BodyLo[],BodyClr[];
double ArrUp[],ArrDn[];                // match arrows (plots 2 / 3)
double trend[];

CMtfJurik       mTrend;                   // TREND Jurik lines on the chart timeframe / TREND timeframe
ENUM_TIMEFRAMES tfTrend;
CMtfJurik       mJsJur;                   // Jurik MA (jurik_filter) of the slope filter
ENUM_TIMEFRAMES tfJsJur;

int             trendPer,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_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

//+------------------------------------------------------------------+
//| BACKGROUND TIMEFRAME (MTF) helpers                               |
//| Current / lower than the chart -> chart timeframe.               |
//+------------------------------------------------------------------+
ENUM_TIMEFRAMES BgResolveTF(const ENUM_TIMEFRAMES tf)
  {
   ENUM_TIMEFRAMES cur=(ENUM_TIMEFRAMES)_Period;
   ENUM_TIMEFRAMES r=(tf==PERIOD_CURRENT)?cur:tf;
   if(PeriodSeconds(r)<=PeriodSeconds(cur)) return(cur);
   return(r);
  }
//+------------------------------------------------------------------+
//| 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);
      g_zoneTouched=true;                     // new rectangle: the carpet canvas must be put back on top of it
     }
   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 && bgZ[rs-1]==bgZ[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 && bgZ[k-1]==bgZ[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 && bgZ[i]!=bgZ[i-1]) rs=i;
      if(i==total-1 || bgZ[i+1]!=bgZ[i])
         DrawZone(ZoneName(time[rs]),time[rs>0?rs-1:rs],time[i],maxV,ZoneColor(bgZ[i]));
     }
  }
//+------------------------------------------------------------------+
//| BGD zones on a higher timeframe                                  |
//| The bars of the BGD timeframe are copied and the TREND state is  |
//| calculated on THEM with the same rule as on the chart (close vs  |
//| the high / low of the TREND Jurik line) - so an H4 BGD timeframe |
//| paints on every lower chart the colours an H4 chart shows.       |
//+------------------------------------------------------------------+
bool BgdBaseSync(int &n,int &prevOut)
  {
   ENUM_TIMEFRAMES tf=bgTfZ;
   n=Bars(_Symbol,tf);
   int maxb=(int)TerminalInfoInteger(TERMINAL_MAXBARS);
   if(maxb>0 && n>maxb) n=maxb;
   if(n<3) return(false);
   datetime ft[1];
   if(CopyTime(_Symbol,tf,n-1,1,ft)!=1) return(false);
   bool sameFirst=(bdN>0 && ft[0]==bdFirst && ArraySize(bdT)==bdN);

   if(sameFirst && n==bdN)                                    // nothing new: refresh only the last bars
     {
      int k=MathMin(3,n);
      datetime t[]; double o[],h[],l[],c[];
      if(CopyTime(_Symbol,tf,0,k,t)!=k || CopyOpen (_Symbol,tf,0,k,o)!=k || CopyHigh(_Symbol,tf,0,k,h)!=k ||
         CopyLow (_Symbol,tf,0,k,l)!=k || CopyClose(_Symbol,tf,0,k,c)!=k) return(false);
      for(int j=0;j<k;j++)
        {
         int r=n-k+j;
         bdT[r]=t[j]; bdO[r]=o[j]; bdH[r]=h[j]; bdL[r]=l[j]; bdC[r]=c[j];
        }
      prevOut=n;
      return(true);
     }

   int oldN=bdN;
   if(CopyTime (_Symbol,tf,0,n,bdT)!=n || CopyOpen(_Symbol,tf,0,n,bdO)!=n || CopyHigh(_Symbol,tf,0,n,bdH)!=n ||
      CopyLow  (_Symbol,tf,0,n,bdL)!=n || CopyClose(_Symbol,tf,0,n,bdC)!=n) { bdN=0; return(false); }
   prevOut=(sameFirst && n>oldN)?oldN:0;                      // new higher-TF bars appended: keep the old results
   bdN=n; bdFirst=ft[0];
   return(true);
  }
//+------------------------------------------------------------------+
//| returns the first chart bar to redraw, -1 when data not ready    |
//+------------------------------------------------------------------+
int BgdHtfMap(const int total,const int from,const datetime &time[])
  {
   int n=0,pv=0;
   if(total<2 || !BgdBaseSync(n,pv)) return(-1);
   int st=mBgd.Update(n,pv,bdT,bdO,bdH,bdL,bdC);              // the higher-TF bars play the role of "chart" bars here
   if(st<0) return(-1);
   if(ArraySize(bdTrend)!=n) ArrayResize(bdTrend,n);
   int ts=(pv>0)?MathMin(st,pv-1):0;
   if(ts<0) ts=0;
   for(int i=ts;i<n;i++)
     {
      double tr=(i>0)?bdTrend[i-1]:0.0;
      if(i>0)
        {
         double h=mBgd.H(i-1-TRENDshft,n), l=mBgd.L(i-1-TRENDshft,n);
         if(Valid(h) && bdC[i]>h) tr= 1.0;
         if(Valid(l) && bdC[i]<l) tr=-1.0;
        }
      bdTrend[i]=tr;
     }

   //--- higher-TF bar -> chart bars (every chart bar of one higher-TF bar gets its colour)
   if(ArraySize(bgZ)!=total) ArrayResize(bgZ,total);
   int lo=MathMax(MathMin(from,total-1),0);
   int hi=BsLastLE(bdT,n,time[lo]);
   if(hi>=0) while(lo>0 && time[lo-1]>=bdT[hi]) lo--;        // restart at the first chart bar of that higher-TF bar
   hi=BsLastLE(bdT,n,time[lo]);
   for(int i=lo;i<total;i++)
     {
      while(hi+1<n && bdT[hi+1]<=time[i]) hi++;
      int x=hi-(BgMtfClosed?1:0);                            // BgMtfClosed: the last CLOSED higher-TF bar
      bgZ[i]=(x>=0)?(int)MathRound(bdTrend[x]):0;
     }
   return(lo);
  }

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

   // the period is exactly what the user typed in the input (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;
   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;
     }
   trendPer=MathMax(trendPer,2);                    // Jurik length must be > 1

   // ---- 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,ArrUp,INDICATOR_DATA);
   SetIndexBuffer(7,ArrDn,INDICATOR_DATA);
   SetIndexBuffer(8,trend,INDICATOR_CALCULATIONS);

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

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

   //--- TREND Jurik lines on the chart-timeframe path (used when the BGD timeframe is the chart timeframe)
   mTrend.Init(tfTrend,trendPer,TRENDphase,TRENDtype,MTFclosedBar);

   //--- Jurik MA of the slope candle filter, on its own timeframe
   tfJsJur=ResolveTF(JsTF,"Jurik slope filter Jurik MA");
   mJsJur.Init(tfJsJur,MathMax(JsLength,1),JsPhase,JsPrice,false);

   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
   IndicatorSetString(INDICATOR_SHORTNAME,"XU-MA v3 Jurik BGD");
   fSetBuffers();
   g_dirty=true; g_lastOk=true; g_total=0; g_retry=0; g_firstTime=0; g_lastFull=0; g_zoneAcc=0; g_passes=0; g_sig=0.0;

   //--- 3D carpet: reset the calculation state, restore the ON/OFF state after a timeframe change, create button + canvas
   cpN=MathMax(2,MathMin(CARPET_MAX_LAYERS,CarpetLayers));
   if(CarpetSeparate) Print("XU-MA v3 carpet: 3 separate carpets, EMA ",CarpetEma1Period," / ",CarpetEma2Period," / ",CarpetEma3Period);
   else Print("XU-MA v3 carpet: front edge EMA ",CarpetRowPeriod(0)," -> back edge EMA ",CarpetRowPeriod(cpN-1)," (",cpN," rows)");
   ArrayFree(cpTime); ArrayFree(cpHa); ArrayFree(cpPx); cpTotal=0;
   for(int j=0;j<CARPET_MAX_LAYERS;j++) ArrayFree(cpL[j].v);
   for(int m=0;m<3;m++) ArrayFree(cpE[m].v);
   g_carpetOn=ShowCarpet;
   string gvCarpet="XUMA_CARPET_"+IntegerToString((long)ChartID());
   if(GlobalVariableCheck(gvCarpet)) { g_carpetOn=(GlobalVariableGet(gvCarpet)!=0.0); GlobalVariableDel(gvCarpet); }
   cpReady=false; cpObj=""; g_zoneTouched=false; cpLastDraw=0;
   if(g_carpetOn && !CarpetCreateCanvas()) g_carpetOn=false;
   CarpetButtonUpdate();

   ArrayFree(bgZ);
   bgTfZ=BgResolveTF(BgdZonesTF);
   {
      //--- BGD zones on bgTfZ: the TREND line runs exactly as it does on a chart of that timeframe
      //    (a TREND timeframe lower than bgTfZ means bgTfZ itself, as ResolveTF does on that chart)
      ENUM_TIMEFRAMES lineTf=(TRENDtf==PERIOD_CURRENT || PeriodSeconds(TRENDtf)<=PeriodSeconds(bgTfZ))?bgTfZ:TRENDtf;
      int perZ=TRENDper;
      if(ScalePerByTF && lineTf==bgTfZ)
        {
         int mulZ=0;
         switch(bgTfZ)
           {
            case PERIOD_M1:  mulZ=5; break;
            case PERIOD_M5:  mulZ=3; break;
            case PERIOD_M15: mulZ=4; break;
            case PERIOD_M30: mulZ=2; break;
            case PERIOD_H1:  mulZ=1; break;
            default: break;
           }
         if(mulZ>0) perZ*=mulZ;
        }
      perZ=MathMax(perZ,2);
      mBgd.Init(lineTf,perZ,TRENDphase,TRENDtype,MTFclosedBar);
      ArrayFree(bdT); ArrayFree(bdO); ArrayFree(bdH); ArrayFree(bdL); ArrayFree(bdC); ArrayFree(bdTrend);
      bdN=0; bdFirst=0;
   }
   Print("XU-MA v3 background timeframe: BGD zones ",EnumToString(bgTfZ),BgMtfClosed?" (closed higher-TF bar)":"");

   EventSetMillisecondTimer(RETRY_MS);               // finishes the calculation when late data arrives, no tick needed
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   EventKillTimer();
   if(reason==REASON_CHARTCHANGE)                    // keep the carpet ON/OFF choice over a timeframe / symbol change
     {
      string gvCarpet="XUMA_CARPET_"+IntegerToString((long)ChartID());
      GlobalVariableTemp(gvCarpet);
      GlobalVariableSet(gvCarpet,g_carpetOn?1.0:0.0);
     }
   CarpetDestroyCanvas();
   ObjectsDeleteAll(0,ID);
   ChartRedraw();
  }
//+------------------------------------------------------------------+
//--- 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[4]; int cntTf=0;
   tf[cntTf++]=tfTrend;
   tf[cntTf++]=tfJsJur;
   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<trendPer+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);
   CarpetCalc(rates_total,prev,time,open,high,low,close);   // EMA surface (cheap, always kept up to date)
   CarpetUpdate(prev==0);                                   // draws only while the button is ON (after the zones: canvas goes on top)
   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
   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;
      CarpetUpdate(false);
      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;
   CarpetUpdate(false);
   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 Jurik lines on their own timeframe, mapped to the chart bars (only needed when the BGD zones
   //    run on the chart timeframe; on a higher BGD timeframe BgdHtfMap calculates its own TREND state).
   //    A forming higher-TF bar changes its value, so every chart bar inside it is recalculated too.
   bool chartTrend=(bgTfZ==(ENUM_TIMEFRAMES)_Period);
   g_wait="";
   if(chartTrend)
     {
      int sT=mTrend.Update(rates_total,prev_calculated,time,open,high,low,close);
      if(sT>=0) start=MathMin(start,sT); else { ready=false; g_wait+="TREND "; }
     }
   //--- Jurik MA (jurik_filter) of the slope candle filter
   int sJ=mJsJur.Update(rates_total,prev_calculated,time,open,high,low,close);
   if(sJ>=0) start=MathMin(start,sJ); else { ready=false; g_wait+="JSJURIK "; }

   //--- prepare BGD-zone states before candle colours are written.
   //    On the chart timeframe the state is filled bar-by-bar below; on a higher timeframe
   //    BgdHtfMap supplies the state of the selected TF for every chart bar.
   bool needBg=(showBGDzones || BgCandleFilterOn || ShowMatchArrows);   // background state is needed by zones, candle filter and arrows
   int bgdZoneStart=-1;
   bool bgdZoneReady=true;
   int bgdFilterFirst=(ZonesMaxBars>0)?MathMax(0,rates_total-ZonesMaxBars):0;
   if(needBg)
     {
      int zs=start;
      if(showBGDzones)
        {
         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;
           }
        }
      int zfrom=MathMax(zs,bgdFilterFirst);
      if(chartTrend)
        {
         if(ArraySize(bgZ)!=rates_total) ArrayResize(bgZ,rates_total);
         bgdZoneStart=zfrom;
        }
      else
        {
         bgdZoneStart=BgdHtfMap(rates_total,zfrom,time);
         if(bgdZoneStart<0)
           {
            bgdZoneReady=false;
            ready=false; g_wait+="BGD ";
            if(showBGDzones) g_zoneAcc=ZONE_REBUILD_BARS;
           }
        }
     }

   for(int i=start;i<rates_total;i++)
     {
      //--- TREND state (close vs the high / low of the TREND Jurik line) - feeds the BGD zones
      trend[i]=(i>0)?trend[i-1]:0;
      if(chartTrend && 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;
        }
      if(chartTrend && needBg)
         bgZ[i]=(int)MathRound(trend[i]);

      //--- candle colour: 0 = up (blue), 1 = neutral (white), 2 = down (red)
      int dir=1;
      //--- Jurik slope candle filter: Jurik slope up -> blue, slope down -> red, flat -> white
      double jv=mJsJur.T(i,rates_total), jp=mJsJur.TP(i,rates_total);
      if(Valid(jv) && Valid(jp))
        {
         if(jv>jp)      dir=0;
         else if(jv<jp) dir=2;
         else           dir=1;
        }
      //--- BACKGROUND candle filter - candles match the background zones:
      //    blue (up) background: red candles -> white
      //    red (down) background: blue candles -> white
      if(BgCandleFilterOn && bgdZoneReady && i>=bgdFilterFirst)
        {
         int bgstate=bgZ[i];
         if(bgstate== 1 && dir==2) dir=1;
         if(bgstate==-1 && 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: blue candle on blue background -> UP, red candle on red background -> DOWN
      ArrUp[i]=EMPTY_VALUE; ArrDn[i]=EMPTY_VALUE;
      if(ShowMatchArrows && bgdZoneReady && i>=bgdFilterFirst)
        {
         int m=MatchOf(dir,bgZ[i]);
         if(m!=0)
           {
            int pm=0;
            if(ArrowFirstOnly && i>bgdFilterFirst) pm=MatchOf((int)WickClr[i-1],bgZ[i-1]);
            if(!ArrowFirstOnly || m!=pm)
              {
               if(m==1) ArrUp[i]=low[i];
               else     ArrDn[i]=high[i];
              }
           }
        }
     }

   //--- draw the prepared BGD zones after their per-bar states are available
   if(showBGDzones && bgdZoneReady && bgdZoneStart>=0)
      UpdateZones(rates_total,bgdZoneStart,time,high);

   bool ok=ready;
   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;
   return(ok);
  }
//+------------------------------------------------------------------+
void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
  {
   if(id==CHARTEVENT_CHART_CHANGE)
     {
      fSetBuffers();
      if(g_carpetOn && cpReady) { CarpetRender(); cpLastDraw=GetTickCount64(); }
     }
   if(id==CHARTEVENT_OBJECT_CLICK && sparam==CARPET_BTN)
      CarpetSetState(!g_carpetOn);
  }
//+------------------------------------------------------------------+
//| 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();
  }
//+------------------------------------------------------------------+
