//+------------------------------------------------------------------+
//|                                             JackJill(bar)_MTF.mq5|
//|  MQL5 conversion of:                                             |
//|    TASC Issue: December 2026                                     |
//|       Article: A Trend Indicator                                 |
//|                The Jack & Jill Indicator                         |
//|    Article By: John F. Ehlers                                    |
//|                                                                  |
//|  Multi-Timeframe (MTF) full-height sub-window thick histogram    |
//|  bars (0 to 1) spanning the full candle width, colored by        |
//|  Jack vs Jill trend & slope.                                     |
//+------------------------------------------------------------------+
#property copyright "Conversion of John F. Ehlers (TASC Dec 2026) Jack & Jill Indicator"
#property link      ""
#property version   "1.02"
#property description "Jack & Jill (bar) MTF - Full-height sub-window bars across candle width"

#include <Canvas\Canvas.mqh>

#property indicator_separate_window
#property indicator_minimum 0.0
#property indicator_maximum 1.0
#property indicator_buffers 9
#property indicator_plots   1

//--- Plot 1: Data / Fallback Histogram (0..1)
#property indicator_label1  "J&J (bar) MTF"
#property indicator_type1   DRAW_COLOR_HISTOGRAM
#property indicator_width1  5

//+------------------------------------------------------------------+
//| Timeframe Enumeration (Awesome oscillator - extended MTF style)  |
//+------------------------------------------------------------------+
enum enTimeFrames
  {
   tf_cu  = PERIOD_CURRENT, // Current time frame
   tf_m1  = PERIOD_M1,      // 1 minute
   tf_m2  = PERIOD_M2,      // 2 minutes
   tf_m3  = PERIOD_M3,      // 3 minutes
   tf_m4  = PERIOD_M4,      // 4 minutes
   tf_m5  = PERIOD_M5,      // 5 minutes
   tf_m6  = PERIOD_M6,      // 6 minutes
   tf_m10 = PERIOD_M10,     // 10 minutes
   tf_m12 = PERIOD_M12,     // 12 minutes
   tf_m15 = PERIOD_M15,     // 15 minutes
   tf_m20 = PERIOD_M20,     // 20 minutes
   tf_m30 = PERIOD_M30,     // 30 minutes
   tf_h1  = PERIOD_H1,      // 1 hour
   tf_h2  = PERIOD_H2,      // 2 hours
   tf_h3  = PERIOD_H3,      // 3 hours
   tf_h4  = PERIOD_H4,      // 4 hours
   tf_h6  = PERIOD_H6,      // 6 hours
   tf_h8  = PERIOD_H8,      // 8 hours
   tf_h12 = PERIOD_H12,     // 12 hours
   tf_d1  = PERIOD_D1,      // daily
   tf_w1  = PERIOD_W1,      // weekly
   tf_mn  = PERIOD_MN1,     // monthly
   tf_cp1 = -1,             // Next higher time frame
   tf_cp2 = -2,             // Second higher time frame
   tf_cp3 = -3              // Third higher time frame
  };

//+------------------------------------------------------------------+
//| Input Parameters (no input groups so iCustom parameters align)   |
//+------------------------------------------------------------------+
//--- Inputs
input enTimeFrames       InpTimeFrame      = tf_cu;          // Time frame
input ENUM_APPLIED_PRICE InpAppliedPrice   = PRICE_CLOSE;    // Source (Price field)
input double             InpPeriod0        = 20.0;           // Base period (>= 2.0)
input int                InpRMSLength      = 81;             // RMS length (>= 2)

//--- Thick Histogram Settings
input bool               InpUseThickCanvas = true;           // Full-Width Thick Bars (Canvas)
input int                InpBarGap         = 1;              // Gap Between Bars in Pixels (0 = solid ribbon)
input int                InpOpacity        = 230;            // Bar Opacity (0-255)
input bool               InpUseGradient    = true;           // Vertical 3D Shading Gradient
input bool               InpDrawOutline    = false;          // Draw 1px Bar Outline
input color              InpOutlineColor   = clrBlack;       // Bar Outline Color

//--- FX Color Settings
input bool               InpUse4Colors     = true;           // Use 4 colors (strong/weak)
input color              InpCandleUp       = C'96,170,204';  // Strong Bullish (Jack > Jill, rising)
input color              InpCandleUpWeak   = C'35,100,130';  // Bullish Retracement (Jack > Jill, falling)
input color              InpCandleDn       = C'255,140,255'; // Strong Bearish (Jack < Jill, falling)
input color              InpCandleDnWeak   = C'180,70,180';  // Bearish Retracement (Jack < Jill, rising)
input color              InpCandleWt       = C'34,34,34';    // Neutral

//+------------------------------------------------------------------+
//| Fast Canvas subclass for direct pixel memory buffer access       |
//+------------------------------------------------------------------+
class CThickHistoCanvas : public CCanvas
  {
public:
   inline void EraseFast(const uint clr = 0)
     {
      ArrayFill(m_pixels, 0, ArraySize(m_pixels), clr);
     }

   void FillRectShaded(const int x1, const int y1, const int x2, const int y2,
                       const color baseClr, const uchar alpha,
                       const bool useGrad, const bool outline, const color outClr)
     {
      int left   = MathMax(0, x1);
      int right  = MathMin(m_width - 1, x2);
      int top    = MathMax(0, y1);
      int bottom = MathMin(m_height - 1, y2);
      if(left > right || top > bottom)
         return;

      int rBase = (int)(baseClr & 0x0000FF);
      int gBase = (int)((baseClr & 0x00FF00) >> 8);
      int bBase = (int)((baseClr & 0xFF0000) >> 16);

      int height = bottom - top + 1;
      double invH = (height > 1) ? (1.0 / (double)(height - 1)) : 0.0;

      uint outARGB = ((uint)alpha << 24) |
                     ((uint)(outClr & 0x0000FF) << 16) |
                     ((uint)(outClr & 0x00FF00)) |
                     ((uint)((outClr & 0xFF0000) >> 16));

      for(int y = top; y <= bottom; y++)
        {
         uint rowARGB;
         if(!useGrad)
           {
            rowARGB = ((uint)alpha << 24) | ((uint)rBase << 16) | ((uint)gBase << 8) | (uint)bBase;
           }
         else
           {
            double t = (double)(y - top) * invH;
            double shade = 1.0 - 0.35 * MathAbs(t - 0.35);
            int r = (int)MathMin(255, MathMax(0, MathRound(rBase * shade)));
            int g = (int)MathMin(255, MathMax(0, MathRound(gBase * shade)));
            int b = (int)MathMin(255, MathMax(0, MathRound(bBase * shade)));
            rowARGB = ((uint)alpha << 24) | ((uint)r << 16) | ((uint)g << 8) | (uint)b;
           }

         int idx = y * m_width + left;
         bool isEdgeY = (outline && (y == top || y == bottom));
         for(int x = left; x <= right; x++, idx++)
           {
            if(outline && (isEdgeY || x == left || x == right))
               m_pixels[idx] = outARGB;
            else
               m_pixels[idx] = rowARGB;
           }
        }
     }
  };

//+------------------------------------------------------------------+
//| Indicator Buffers                                                |
//+------------------------------------------------------------------+
double HistBuffer[];       // Plot 1: 1.0 (full-height bar)
double HistColorBuffer[];  // Plot 1 color index (0..4)
double OscBuffer[];        // Jack - Jill
double TrendBuffer[];      // 1 = Bull, -1 = Bear, 0 = Neutral
double JackBuffer[];       // Adaptive SuperSmoother
double JillBuffer[];       // Contra-adaptive SuperSmoother
double JackNextPeriod[];   // Next bar period for Jack
double JillNextPeriod[];   // Next bar period for Jill
double CountBuffer[];      // Changed bar count for MTF sync

//+------------------------------------------------------------------+
//| Global & MTF Variables                                           |
//+------------------------------------------------------------------+
CThickHistoCanvas g_canvas;
string            g_canvasName    = "";
bool              g_canvasCreated = false;
int               g_subwin        = -1;
int               g_width         = 0;
int               g_height        = 0;
int               g_scale         = -1;
int               g_firstVis      = -1;
int               g_visBars       = 0;
int               g_ratesTotal    = 0;
string            g_shortName     = "";

ENUM_TIMEFRAMES   _indicatorTimeFrame;
string            _indicatorName;
int               _indicatorHandle = INVALID_HANDLE;

#define _mtfCall iCustom(_Symbol,_indicatorTimeFrame,_indicatorName,tf_cu,InpAppliedPrice,InpPeriod0,InpRMSLength,false,InpBarGap,InpOpacity,InpUseGradient,InpDrawOutline,InpOutlineColor,InpUse4Colors,InpCandleUp,InpCandleUpWeak,InpCandleDn,InpCandleDnWeak,InpCandleWt)

//+------------------------------------------------------------------+
//| MTF Helpers (Awesome oscillator - extended MTF style)            |
//+------------------------------------------------------------------+
ENUM_TIMEFRAMES _tfsPer[] = {PERIOD_M1,PERIOD_M2,PERIOD_M3,PERIOD_M4,PERIOD_M5,PERIOD_M6,PERIOD_M10,PERIOD_M12,PERIOD_M15,PERIOD_M20,PERIOD_M30,PERIOD_H1,PERIOD_H2,PERIOD_H3,PERIOD_H4,PERIOD_H6,PERIOD_H8,PERIOD_H12,PERIOD_D1,PERIOD_W1,PERIOD_MN1};

ENUM_TIMEFRAMES timeFrameGet(int period)
  {
   int _shift = (period < 0 ? MathAbs(period) : 0);
   if(period <= 0)
      period = _Period;
   int i;
   for(i = 0; i < ArraySize(_tfsPer); i++)
      if(period == _tfsPer[i])
         break;
   return(_tfsPer[(int)MathMin(i + _shift, ArraySize(_tfsPer) - 1)]);
  }

string getIndicatorName()
  {
   string path = MQL5InfoString(MQL5_PROGRAM_PATH);
   string parts[];
   int totalParts = StringSplit(path, '\\', parts);
   if(totalParts > 0)
     {
      string name = parts[totalParts - 1];
      for(int n = totalParts - 2; n >= 0; n--)
        {
         string folder = parts[n];
         StringToLower(folder);
         if(folder == "indicators")
            break;
         name = parts[n] + "\\" + name;
        }
      return(name);
     }
   return(MQL5InfoString(MQL5_PROGRAM_NAME));
  }

bool _checkHandle(int _handle, string _description)
  {
   static int  _chandles[];
   int         _size   = ArraySize(_chandles);
   bool        _answer = (_handle != INVALID_HANDLE);
   if(_answer)
     {
      ArrayResize(_chandles, _size + 1);
      _chandles[_size] = _handle;
     }
   else
     {
      for(int i = _size - 1; i >= 0; i--)
         IndicatorRelease(_chandles[i]);
      ArrayResize(_chandles, 0);
      Alert(_description + " initialization failed");
     }
   return(_answer);
  }

//+------------------------------------------------------------------+
//| Helper Functions                                                 |
//+------------------------------------------------------------------+
string GetStringTimeframe(ENUM_TIMEFRAMES timeframe)
  {
   return(StringSubstr(EnumToString(timeframe), 7));
  }

int BarPitchPixels(int chartScale)
  {
   if(chartScale < 0) chartScale = 0;
   if(chartScale > 5) chartScale = 5;
   return(1 << chartScale);
  }

inline double GetAppliedPrice(const int index,
                              const double &open[],
                              const double &high[],
                              const double &low[],
                              const double &close[])
  {
   switch(InpAppliedPrice)
     {
      case PRICE_OPEN:     return open[index];
      case PRICE_HIGH:     return high[index];
      case PRICE_LOW:      return low[index];
      case PRICE_MEDIAN:   return (high[index] + low[index]) * 0.5;
      case PRICE_TYPICAL:  return (high[index] + low[index] + close[index]) / 3.0;
      case PRICE_WEIGHTED: return (high[index] + low[index] + 2.0 * close[index]) * 0.25;
      case PRICE_CLOSE:
      default:             return close[index];
     }
  }

double SuperSmootherValue(const double src, const double srcPrev, const int i,
                          const double period, const double r1, const double r2)
  {
   double w  = 1.414 * M_PI / period;
   double q  = MathExp(-w);
   double c1 = 2.0 * q * MathCos(w);
   double c2 = q * q;
   double a0 = (1.0 - c1 + c2) / 2.0;

   if(i >= 4)
      return(a0 * (src + srcPrev) + c1 * r1 - c2 * r2);

   return(src);
  }

double RMSOfBuffer(const double &buf[], const int i)
  {
   int cnt = MathMin(InpRMSLength, i);
   if(cnt <= 0)
      return(0.0);

   double s2 = 0.0;
   for(int k = i - cnt + 1; k <= i; k++)
     {
      double d = buf[k] - buf[k - 1];
      s2 += d * d;
     }

   if(s2 == 0.0)
      return(0.0);

   return(MathSqrt(s2 / cnt));
  }

color PaletteColorByIndex(const int colorIdx)
  {
   switch(colorIdx)
     {
      case 0:  return InpCandleUp;
      case 2:  return InpCandleDn;
      case 3:  return InpCandleUpWeak;
      case 4:  return InpCandleDnWeak;
      default: return InpCandleWt;
     }
  }

int ResolveSubwindow()
  {
   int sw = ChartWindowFind();
   if(sw > 0)
      return sw;

   if(g_shortName != "")
     {
      sw = ChartWindowFind(0, g_shortName);
      if(sw > 0)
         return sw;
     }

   int total = (int)ChartGetInteger(0, CHART_WINDOWS_TOTAL);
   for(int w = 1; w < total; w++)
     {
      int cnt = ChartIndicatorsTotal(0, w);
      for(int i = 0; i < cnt; i++)
        {
         if(StringFind(ChartIndicatorName(0, w, i), "Jack & Jill (bar) MTF") >= 0)
            return w;
        }
     }
   return -1;
  }

//+------------------------------------------------------------------+
//| Redraw Full-Width Thick Histogram Canvas                         |
//+------------------------------------------------------------------+
void RedrawCanvas()
  {
   if(!InpUseThickCanvas || g_ratesTotal <= 0)
      return;

   if(g_subwin <= 0)
      g_subwin = ResolveSubwindow();
   if(g_subwin <= 0)
      return;

   int w  = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS, g_subwin);
   int h  = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, g_subwin);
   int sc = (int)ChartGetInteger(0, CHART_SCALE, 0);
   int fb = (int)ChartGetInteger(0, CHART_FIRST_VISIBLE_BAR, 0);
   int vb = (int)ChartGetInteger(0, CHART_VISIBLE_BARS, 0);

   if(w <= 0 || h <= 0 || fb < 0)
      return;

   int pitch = BarPitchPixels(sc);
   if(vb <= 0)
      vb = w / MathMax(1, pitch) + 2;

   g_width    = w;
   g_height   = h;
   g_scale    = sc;
   g_firstVis = fb;
   g_visBars  = vb;

   if(!g_canvasCreated || ObjectFind(0, g_canvasName) < 0)
     {
      if(g_canvasName == "")
         g_canvasName = "JJ_bar_MTF_" + IntegerToString(ChartID()) + "_" + IntegerToString(g_subwin);
      ObjectDelete(0, g_canvasName);
      if(!g_canvas.CreateBitmapLabel(0, g_subwin, g_canvasName, 0, 0, g_width, g_height, COLOR_FORMAT_ARGB_NORMALIZE))
         return;
      ObjectSetInteger(0, g_canvasName, OBJPROP_SELECTABLE, false);
      ObjectSetInteger(0, g_canvasName, OBJPROP_SELECTED, false);
      ObjectSetInteger(0, g_canvasName, OBJPROP_HIDDEN, true);
      ObjectSetInteger(0, g_canvasName, OBJPROP_BACK, true);
      ObjectSetInteger(0, g_canvasName, OBJPROP_ZORDER, 0);
      g_canvasCreated = true;
     }
   else if(g_canvas.Width() != g_width || g_canvas.Height() != g_height)
     {
      g_canvas.Resize(g_width, g_height);
     }

   g_canvas.EraseFast(0);

   int bufSize = ArraySize(HistColorBuffer);
   if(bufSize <= 0)
     {
      g_canvas.Update(false);
      return;
     }

   // Anchor exact X position of firstVisibleBar via ChartTimePriceToXY
   int  anchorX   = 0;
   bool hasAnchor = false;
   datetime anchorTime = iTime(_Symbol, _Period, fb);
   if(anchorTime > 0)
     {
      double cMin = ChartGetDouble(0, CHART_PRICE_MIN, 0);
      double cMax = ChartGetDouble(0, CHART_PRICE_MAX, 0);
      double midP = (cMax > cMin) ? (cMin + cMax) * 0.5 : iClose(_Symbol, _Period, fb);
      int cx = 0, cy = 0;
      if(ChartTimePriceToXY(0, 0, anchorTime, midP, cx, cy))
        {
         anchorX   = cx;
         hasAnchor = true;
        }
     }

   int gap = MathMax(0, InpBarGap);
   int barW = (pitch > gap + 1) ? (pitch - gap) : pitch;
   if(barW < 1) barW = 1;
   int halfW = barW / 2;

   uchar alpha = (uchar)MathMin(255, MathMax(0, InpOpacity));
   int padY = (g_height > 6) ? 2 : 0;
   int yTop = padY;
   int yBot = g_height - 1 - padY;

   int startShift = MathMax(0, fb - vb - 1);
   int endShift   = MathMin(bufSize - 1, fb + 1);

   for(int shift = endShift; shift >= startShift; shift--)
     {
      int idx = bufSize - 1 - shift;
      if(idx < 0 || idx >= bufSize)
         continue;
      if(HistBuffer[idx] == EMPTY_VALUE || HistBuffer[idx] == 0.0)
         continue;

      int cx = hasAnchor ? (anchorX + (fb - shift) * pitch)
                         : ((fb - shift) * pitch + pitch / 2);
      int x1 = cx - halfW;
      int x2 = x1 + barW - 1;
      if(x2 < 0 || x1 >= g_width)
         continue;

      color clr = PaletteColorByIndex((int)HistColorBuffer[idx]);
      g_canvas.FillRectShaded(x1, yTop, x2, yBot, clr, alpha,
                              InpUseGradient, InpDrawOutline, InpOutlineColor);
     }

   g_canvas.Update(true);
  }

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(InpPeriod0 < 2.0)
     {
      PrintFormat("JackJill(bar)_MTF: Base period must be >= 2. Received: %.2f", InpPeriod0);
      return(INIT_PARAMETERS_INCORRECT);
     }
   if(InpRMSLength < 2)
     {
      PrintFormat("JackJill(bar)_MTF: RMS length must be >= 2. Received: %d", InpRMSLength);
      return(INIT_PARAMETERS_INCORRECT);
     }

   SetIndexBuffer(0, HistBuffer,      INDICATOR_DATA);
   SetIndexBuffer(1, HistColorBuffer, INDICATOR_COLOR_INDEX);
   SetIndexBuffer(2, OscBuffer,       INDICATOR_CALCULATIONS);
   SetIndexBuffer(3, TrendBuffer,     INDICATOR_CALCULATIONS);
   SetIndexBuffer(4, JackBuffer,      INDICATOR_CALCULATIONS);
   SetIndexBuffer(5, JillBuffer,      INDICATOR_CALCULATIONS);
   SetIndexBuffer(6, JackNextPeriod,  INDICATOR_CALCULATIONS);
   SetIndexBuffer(7, JillNextPeriod,  INDICATOR_CALCULATIONS);
   SetIndexBuffer(8, CountBuffer,     INDICATOR_CALCULATIONS);

   ArraySetAsSeries(HistBuffer,      false);
   ArraySetAsSeries(HistColorBuffer, false);
   ArraySetAsSeries(OscBuffer,       false);
   ArraySetAsSeries(TrendBuffer,     false);
   ArraySetAsSeries(JackBuffer,      false);
   ArraySetAsSeries(JillBuffer,      false);
   ArraySetAsSeries(JackNextPeriod,  false);
   ArraySetAsSeries(JillNextPeriod,  false);
   ArraySetAsSeries(CountBuffer,     false);

   PlotIndexSetInteger(0, PLOT_COLOR_INDEXES, 5);
   PlotIndexSetInteger(0, PLOT_LINE_COLOR, 0, InpCandleUp);
   PlotIndexSetInteger(0, PLOT_LINE_COLOR, 1, InpCandleWt);
   PlotIndexSetInteger(0, PLOT_LINE_COLOR, 2, InpCandleDn);
   PlotIndexSetInteger(0, PLOT_LINE_COLOR, 3, InpCandleUpWeak);
   PlotIndexSetInteger(0, PLOT_LINE_COLOR, 4, InpCandleDnWeak);
   PlotIndexSetDouble(0,  PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(0, PLOT_DRAW_TYPE, InpUseThickCanvas ? DRAW_NONE : DRAW_COLOR_HISTOGRAM);
   PlotIndexSetInteger(0, PLOT_SHOW_DATA, true);

   ENUM_TIMEFRAMES targetTf = timeFrameGet(InpTimeFrame);
   _indicatorTimeFrame = (PeriodSeconds(targetTf) > PeriodSeconds(_Period)) ? targetTf : (ENUM_TIMEFRAMES)_Period;

   if(_indicatorTimeFrame != _Period)
     {
      _indicatorName   = getIndicatorName();
      _indicatorHandle = _mtfCall;
      if(!_checkHandle(_indicatorHandle, "Target time frame instance"))
         return(INIT_FAILED);

      if(BarsCalculated(_indicatorHandle) <= 0)
         EventSetTimer(1);
     }

   IndicatorSetInteger(INDICATOR_DIGITS, _Digits);
   g_shortName = StringFormat("[%s] [%s] Jack & Jill (bar) MTF (%.1f, %d)",
                              Symbol(), GetStringTimeframe(_indicatorTimeFrame), InpPeriod0, InpRMSLength);
   IndicatorSetString(INDICATOR_SHORTNAME, g_shortName);

   g_subwin        = ResolveSubwindow();
   g_canvasName    = (g_subwin > 0) ? ("JJ_bar_MTF_" + IntegerToString(ChartID()) + "_" + IntegerToString(g_subwin)) : "";
   g_canvasCreated = false;

   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   EventKillTimer();
   if(_indicatorHandle != INVALID_HANDLE)
      IndicatorRelease(_indicatorHandle);

   g_canvas.Destroy();
   g_canvasCreated = false;
   if(g_canvasName != "")
      ObjectDelete(0, g_canvasName);
   ChartRedraw(0);
  }

//+------------------------------------------------------------------+
//| Timer handler for non-blocking MTF history download              |
//+------------------------------------------------------------------+
void OnTimer()
  {
   if(_indicatorTimeFrame != _Period && _indicatorHandle != INVALID_HANDLE)
     {
      if(BarsCalculated(_indicatorHandle) > 0)
        {
         EventKillTimer();
         ChartSetSymbolPeriod(0, _Symbol, _Period);
        }
     }
  }

//+------------------------------------------------------------------+
//| Chart event handler (redraw on zoom / scroll / resize)           |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
   if(id == CHARTEVENT_CHART_CHANGE && InpUseThickCanvas)
     {
      if(g_subwin <= 0)
         g_subwin = ResolveSubwindow();
      if(g_subwin <= 0)
         return;

      int w  = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS, g_subwin);
      int h  = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, g_subwin);
      int sc = (int)ChartGetInteger(0, CHART_SCALE, 0);
      int fb = (int)ChartGetInteger(0, CHART_FIRST_VISIBLE_BAR, 0);
      int vb = (int)ChartGetInteger(0, CHART_VISIBLE_BARS, 0);

      if(w != g_width || h != g_height || sc != g_scale || fb != g_firstVis || vb != g_visBars)
         RedrawCanvas();
     }
  }

//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
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 < 5)
      return(0);

   ArraySetAsSeries(time, false);

   bool needRedraw = (prev_calculated != rates_total) || (InpUseThickCanvas && !g_canvasCreated);

   //--- Multi-Timeframe mode
   if(_indicatorTimeFrame != _Period)
     {
      if(BarsCalculated(_indicatorHandle) <= 0)
        {
         EventSetTimer(1);
         return(0);
        }

      double result[];
      if(CopyBuffer(_indicatorHandle, 8, 0, 1, result) < 1)
        {
         EventSetTimer(1);
         return(0);
        }

      g_ratesTotal = rates_total;

      double changedHtf = (MathIsValidNumber(result[0]) && result[0] != EMPTY_VALUE && result[0] >= 1.0)
                          ? MathMin(result[0], (double)rates_total)
                          : 1.0;

      #define _mtfRatio ((double)PeriodSeconds(_indicatorTimeFrame) / PeriodSeconds(_Period))
      int lookback = (int)MathCeil(changedHtf * _mtfRatio) + (int)MathCeil(_mtfRatio);
      int limit    = MathMin(MathMax(prev_calculated - 1, 0), MathMax(rates_total - lookback - 1, 0));

      // On intra-bar ticks for very high timeframes (e.g., W1/MN1 on M1), limit work to the forming HTF bar
      if(prev_calculated == rates_total && changedHtf <= 1.0 && lookback > 200)
        {
         datetime htfCurTime = iTime(_Symbol, _indicatorTimeFrame, 0);
         if(htfCurTime > 0)
           {
            int htfShift = iBarShift(_Symbol, _Period, htfCurTime, false);
            if(htfShift >= 0)
               limit = MathMax(limit, MathMax(0, rates_total - 1 - htfShift - 1));
           }
        }

      int endBar   = rates_total; // include current forming bar & forming HTF bar
      datetime firstHtfDate = (datetime)SeriesInfoInteger(_Symbol, _indicatorTimeFrame, SERIES_FIRSTDATE);

      for(int i = limit; i < endBar && !_StopFlag; i++)
        {
         double prevHist  = HistBuffer[i];
         double prevColor = HistColorBuffer[i];

         if(firstHtfDate > 0 && time[i] < firstHtfDate)
           {
            HistBuffer[i]      = EMPTY_VALUE;
            HistColorBuffer[i] = 1.0;
            OscBuffer[i]       = 0.0;
            TrendBuffer[i]     = 0.0;
            if(HistBuffer[i] != prevHist || HistColorBuffer[i] != prevColor)
               needRedraw = true;
            continue;
           }

         if(CopyBuffer(_indicatorHandle, 0, time[i], 1, result) <= 0)
           {
            HistBuffer[i] = EMPTY_VALUE;
            if(HistBuffer[i] != prevHist)
               needRedraw = true;
            continue;
           }
         HistBuffer[i] = result[0];

         if(CopyBuffer(_indicatorHandle, 1, time[i], 1, result) > 0)
            HistColorBuffer[i] = result[0];

         if(HistBuffer[i] != prevHist || HistColorBuffer[i] != prevColor)
            needRedraw = true;

         if(CopyBuffer(_indicatorHandle, 2, time[i], 1, result) <= 0) continue;
         OscBuffer[i] = result[0];

         if(CopyBuffer(_indicatorHandle, 3, time[i], 1, result) <= 0) continue;
         TrendBuffer[i] = result[0];
        }

      if(InpUseThickCanvas && needRedraw)
         RedrawCanvas();

      return(rates_total);
     }

   //--- Current Timeframe mode
   g_ratesTotal = rates_total;
   int start  = (prev_calculated > 0) ? prev_calculated - 1 : 0;
   int endBar = rates_total; // include current forming bar (0 .. rates_total - 1)

   for(int i = start; i < endBar && !IsStopped(); i++)
     {
      double prevHist  = HistBuffer[i];
      double prevColor = HistColorBuffer[i];

      double src     = GetAppliedPrice(i, open, high, low, close);
      double srcPrev = (i > 0) ? GetAppliedPrice(i - 1, open, high, low, close) : src;

      double jackPeriod = (i > 0) ? JackNextPeriod[i - 1] : InpPeriod0;
      double jillPeriod = (i > 0) ? JillNextPeriod[i - 1] : InpPeriod0;

      //--- 1. Jack: adaptive SuperSmoother ---------------------------
      JackBuffer[i] = SuperSmootherValue(src, srcPrev, i, jackPeriod,
                                         (i > 0) ? JackBuffer[i - 1] : 0.0,
                                         (i > 1) ? JackBuffer[i - 2] : 0.0);

      double jackRMS = RMSOfBuffer(JackBuffer, i);
      double jackD   = (i > 0) ? JackBuffer[i] - JackBuffer[i - 1] : 0.0;
      double jackROC = (jackRMS != 0.0) ? MathMin(2.0, MathAbs(jackD / jackRMS)) : 0.0;

      double jackDM     = 1.0 - 0.5 * jackROC;
      JackNextPeriod[i] = MathMax(2.0, InpPeriod0 * jackDM * jackDM);

      //--- 2. Jill: contra-adaptive SuperSmoother --------------------
      JillBuffer[i] = SuperSmootherValue(src, srcPrev, i, jillPeriod,
                                         (i > 0) ? JillBuffer[i - 1] : 0.0,
                                         (i > 1) ? JillBuffer[i - 2] : 0.0);

      double jillRMS = RMSOfBuffer(JillBuffer, i);
      double jillD   = (i > 0) ? JillBuffer[i] - JillBuffer[i - 1] : 0.0;
      double jillROC = (jillRMS != 0.0) ? MathMin(2.0, MathAbs(jillD / jillRMS)) : 0.0;

      double jillDM     = 1.0 + 0.5 * jillROC;
      JillNextPeriod[i] = MathMax(2.0, InpPeriod0 * jillDM * jillDM);

      //--- 3. Oscillator & Trend state -------------------------------
      double osc = JackBuffer[i] - JillBuffer[i];
      OscBuffer[i]   = osc;
      TrendBuffer[i] = (osc > 0.0) ? 1.0 : ((osc < 0.0) ? -1.0 : 0.0);

      bool rising  = (i > 0 && osc > OscBuffer[i - 1]);
      bool falling = (i > 0 && osc < OscBuffer[i - 1]);

      int colorIdx = 1; // Neutral
      if(osc > 0.0)
         colorIdx = (InpUse4Colors && falling) ? 3 : 0;
      else if(osc < 0.0)
         colorIdx = (InpUse4Colors && rising) ? 4 : 2;

      HistBuffer[i]      = 1.0;
      HistColorBuffer[i] = (double)colorIdx;

      if(HistBuffer[i] != prevHist || HistColorBuffer[i] != prevColor)
         needRedraw = true;
     }

   int cur = rates_total - 1;
   CountBuffer[cur] = MathMax(rates_total - prev_calculated + 1, 1);

   if(InpUseThickCanvas && needRedraw)
      RedrawCanvas();

   return(rates_total);
  }
//+------------------------------------------------------------------+
