//+------------------------------------------------------------------+
//|                                     JackJill(gradient_histo).mq5 |
//|  MQL5 conversion of:                                             |
//|    TASC Issue: December 2026                                     |
//|       Article: A Trend Indicator                                 |
//|                The Jack & Jill Indicator                         |
//|    Article By: John F. Ehlers                                    |
//|    Original: TradingView Pine Script v6 (PineCoders)             |
//|                                                                  |
//|  Oscillator sub-window version: plots the Jack-Jill difference   |
//|  with 4-state Gradient Histogram bars (Boss_Volume style),       |
//|  single 4-color slope Oscillator Line (width 2), and Zero line.  |
//+------------------------------------------------------------------+
#property copyright "Conversion of John F. Ehlers (TASC Dec 2026) Jack & Jill Indicator"
#property link      ""
#property version   "1.30"
#property description "TASC Issue: December 2026 - Jack & Jill (gradient_histo)"
#property description "4-State Gradient Histogram (Boss_Volume style) + 4-Color Slope Line"

//--- Place in separate indicator subwindow
#property indicator_separate_window
#property indicator_buffers 9
#property indicator_plots   3

//--- Plot 1: Hidden/Scaling Histogram (drives subwindow scale & Data Window)
#property indicator_label1  "Jack-Jill Histo"
#property indicator_type1   DRAW_COLOR_HISTOGRAM
#property indicator_color1  clrNONE, clrNONE, clrNONE, clrNONE
#property indicator_width1  1

//--- Plot 2: Single 4-Color Slope Oscillator Line
#property indicator_type2   DRAW_COLOR_LINE
#property indicator_width2  2
#property indicator_label2  "Osc Line"

//--- Plot 3: Zero reference line
#property indicator_type3   DRAW_LINE
#property indicator_color3  clrGold
#property indicator_width3  1
#property indicator_label3  "Zero"

//+------------------------------------------------------------------+
//| Input Parameters                                                 |
//+------------------------------------------------------------------+
input group "--- Inputs ---"
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)

input group "--- Gradient Outline Settings ---"
input bool               InpAutoAroundLine = false;              // Auto Draw Line Around Histogram
input int                InpValueColor     = 4;                  // Level Draw Line Around Histogram (pixels)
input bool               InpAroundLine     = true;               // Draw Line Around Histogram

input group "--- 1: Above Zero & Rising (Bullish Acceleration) ---"
input color              InpLo0            = clrMediumSeaGreen;  // Top Gradient (Peak)
input color              InpHi0            = clrWhiteSmoke;      // Bottom Gradient (Zero line)
input color              InpLn0            = clrLime;            // Outline Color
input int                InpOp0            = 160;                // Start Opaque (0..255)
input int                InpOP0            = 48;                 // End Opaque (0..255)

input group "--- 2: Above Zero & Falling (Bullish Deceleration) ---"
input color              InpLo1            = clrDarkGreen;       // Top Gradient (Peak)
input color              InpHi1            = clrWhiteSmoke;      // Bottom Gradient (Zero line)
input color              InpLn1            = clrMediumSeaGreen;  // Outline Color
input int                InpOp1            = 140;                // Start Opaque (0..255)
input int                InpOP1            = 40;                 // End Opaque (0..255)

input group "--- 3: Below Zero & Falling (Bearish Acceleration) ---"
input color              InpLo2            = clrRed;             // Peak Gradient (Below Zero)
input color              InpHi2            = clrWhiteSmoke;      // Zero Line Gradient
input color              InpLn2            = clrLightCoral;      // Outline Color
input int                InpOp2            = 144;                // Start Opaque (0..255)
input int                InpOP2            = 64;                 // End Opaque (0..255)

input group "--- 4: Below Zero & Rising (Bearish Deceleration) ---"
input color              InpLo3            = clrMaroon;          // Peak Gradient (Below Zero)
input color              InpHi3            = clrWhiteSmoke;      // Zero Line Gradient
input color              InpLn3            = clrPlum;            // Outline Color
input int                InpOp3            = 130;                // Start Opaque (0..255)
input int                InpOP3            = 48;                 // End Opaque (0..255)

input group "--- Oscillator Line ---"
input bool               InpShowLine       = true;               // Show Oscillator Line
input int                InpLineWidth      = 2;                  // Line width (1-5)

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

input group "--- Zero Line ---"
input color              InpZeroColor      = clrGold;            // Zero line color
input int                InpZeroWidth      = 1;                  // Zero line width (1-5)

//+------------------------------------------------------------------+
//| Internal Gradient Structure                                      |
//+------------------------------------------------------------------+
struct Gradient
  {
   uint              R[2], G[2], B[2], O[2], Line;
  };

Gradient Storage[4];

//+------------------------------------------------------------------+
//| Indicator Buffers                                                |
//+------------------------------------------------------------------+
double OscBuffer[];        double OscColorBuffer[];    // Plot 1 (scaling + DataWindow)
double OscLineBuffer[];    double OscLineColors[];     // Plot 2 (single 4-color line)
double BufferZero[];                                   // Plot 3 (Zero reference)

double JackBuffer[];                                   // Calculation: adaptive SuperSmoother
double JillBuffer[];                                   // Calculation: contra-adaptive SuperSmoother
double JackNextPeriod[];                               // Period state for jack on next bar
double JillNextPeriod[];                               // Period state for jill on next bar

//+------------------------------------------------------------------+
//| Global Variables                                                 |
//+------------------------------------------------------------------+
long     g_chart_id      = 0;
int      g_subwin        = -1;
int      g_subHeight     = 0;
int      g_subWidth      = 0;
int      g_scale         = 0;
int      g_rates_total   = 0;
int      g_max_drawn_bar = 0;
bool     g_initialized   = false;
string   g_bmp_prefix    = "";
string   g_shortName     = "";
int      g_lastFVB       = -1;
int      g_lastVB        = -1;
int      g_lastChartSc   = -1;
double   g_lastPMin      = 0.0;
double   g_lastPMax      = 0.0;

//+------------------------------------------------------------------+
//| Clamp a line width to the 1-5 range                              |
//+------------------------------------------------------------------+
int ClampWidth(const int w)
  {
   return (int)MathMin(MathMax(w, 1), 5);
  }

//+------------------------------------------------------------------+
//| Get Timeframe Name String                                        |
//+------------------------------------------------------------------+
string GetStringTimeframe(ENUM_TIMEFRAMES timeframe)
  {
   return(StringSubstr(EnumToString(timeframe), 7));
  }

//+------------------------------------------------------------------+
//| Chart geometry & subwindow helpers                               |
//+------------------------------------------------------------------+
int ChartFirstVisibleBar(const long chart_ID = 0)
  {
   long result = -1;
   if(!ChartGetInteger(chart_ID, CHART_FIRST_VISIBLE_BAR, 0, result))
      return -1;
   return((int)result);
  }

int ChartVisibleBars(const long chart_ID = 0)
  {
   long result = -1;
   if(!ChartGetInteger(chart_ID, CHART_VISIBLE_BARS, 0, result))
      return -1;
   return((int)result);
  }

int ChartScaleGet(const long chart_ID = 0)
  {
   long result = -1;
   if(!ChartGetInteger(chart_ID, CHART_SCALE, 0, result))
      return -1;
   return((int)result);
  }

int GetSubwindow()
  {
   int win = ChartWindowFind();
   if(win <= 0 && g_shortName != "")
      win = ChartWindowFind(0, g_shortName);
   if(win <= 0)
     {
      int total = (int)ChartGetInteger(0, CHART_WINDOWS_TOTAL);
      for(int w = 1; w < total; w++)
        {
         int total_ind = ChartIndicatorsTotal(0, w);
         for(int i = 0; i < total_ind; i++)
           {
            string indName = ChartIndicatorName(0, w, i);
            if(StringFind(indName, "Jack & Jill (gradient_histo)") >= 0 &&
               StringFind(indName, "BT") < 0)
               return w;
           }
        }
     }
   if(win <= 0)
      win = g_subwin;
   return(win);
  }

void UpdateDimensions()
  {
   if(g_subwin <= 0)
      g_subwin = GetSubwindow();
   if(g_subwin > 0)
     {
      g_subHeight = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, g_subwin);
      g_subWidth  = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS, g_subwin);
     }
  }

void UpdateScale()
  {
   int chartScale = ChartScaleGet(0);
   switch(chartScale)
     {
      case 5:  g_scale = 3; break;
      case 4:  g_scale = 2; break;
      case 3:  g_scale = 1; break;
      case 2:  g_scale = 1; break;
      default: g_scale = 0; break;
     }
  }

int PriceToY(const double price, const double pMin, const double pMax, const int height)
  {
   if(pMax <= pMin || height <= 0)
      return 0;
   double ratio = (pMax - price) / (pMax - pMin);
   return (int)(ratio * (double)height);
  }

//+------------------------------------------------------------------+
//| Fill gradient bitmap pixel buffer (Boss_Volume style)            |
//+------------------------------------------------------------------+
void FillMap(uint &MapStorage[], const int iX, const int iY, const Gradient &gColor, const bool invert = false)
  {
   if(iX < 1 || iY < 1)
      return;

   ArrayResize(MapStorage, iX * iY);

   uint bStart = invert ? gColor.B[1] : gColor.B[0];
   uint bEnd   = invert ? gColor.B[0] : gColor.B[1];
   uint gStart = invert ? gColor.G[1] : gColor.G[0];
   uint gEnd   = invert ? gColor.G[0] : gColor.G[1];
   uint rStart = invert ? gColor.R[1] : gColor.R[0];
   uint rEnd   = invert ? gColor.R[0] : gColor.R[1];
   uint oStart = invert ? gColor.O[1] : gColor.O[0];
   uint oEnd   = invert ? gColor.O[0] : gColor.O[1];

   double dB = (bEnd != bStart && iY > 1) ? ((double)bEnd - (double)bStart) / (double)iY : 0.0;
   double dG = (gEnd != gStart && iY > 1) ? ((double)gEnd - (double)gStart) / (double)iY : 0.0;
   double dR = (rEnd != rStart && iY > 1) ? ((double)rEnd - (double)rStart) / (double)iY : 0.0;
   double dO = (oEnd != oStart && iY > 1) ? ((double)oEnd - (double)oStart) / (double)iY : 0.0;

   bool drawAroundLine = InpAroundLine;
   if(InpAutoAroundLine && iX < InpValueColor)
      drawAroundLine = false;

   if(drawAroundLine && iY >= 2 && iX >= 2)
     {
      for(int i = iY - 2; i > 0; i--)
        {
         uint  bVal = (uint)(bStart + (dB != 0.0 ? (double)i * dB : 0.0));
         uint  gVal = (uint)(gStart + (dG != 0.0 ? (double)i * dG : 0.0));
         uint  rVal = (uint)(rStart + (dR != 0.0 ? (double)i * dR : 0.0));
         uchar oVal = (uchar)(oStart + (dO != 0.0 ? (double)i * dO : 0.0));

         color bodyColor = (color)((bVal << 16) | (gVal << 8) | rVal);
         uint  bodyPixel = ColorToARGB(bodyColor, oVal);
         ArrayFill(MapStorage, iX * i, iX, bodyPixel);

         uint linePixel = ColorToARGB((color)gColor.Line, oVal);
         MapStorage[iX * i]          = linePixel;
         MapStorage[iX * i + iX - 1] = linePixel;
        }

      uint topLinePixel = ColorToARGB((color)gColor.Line, (uchar)oStart);
      ArrayFill(MapStorage, 0, iX, topLinePixel);

      uint botLinePixel = ColorToARGB((color)gColor.Line, (uchar)oEnd);
      ArrayFill(MapStorage, iX * (iY - 1), iX, botLinePixel);
     }
   else
     {
      for(int i = 0; i < iY; i++)
        {
         uint  bVal = (uint)(bStart + (dB != 0.0 ? (double)i * dB : 0.0));
         uint  gVal = (uint)(gStart + (dG != 0.0 ? (double)i * dG : 0.0));
         uint  rVal = (uint)(rStart + (dR != 0.0 ? (double)i * dR : 0.0));
         uchar oVal = (uchar)(oStart + (dO != 0.0 ? (double)i * dO : 0.0));

         color bodyColor = (color)((bVal << 16) | (gVal << 8) | rVal);
         uint  bodyPixel = ColorToARGB(bodyColor, oVal);
         ArrayFill(MapStorage, iX * i, iX, bodyPixel);
        }
     }
  }

void DeleteIndicatorObjects()
  {
   if(g_bmp_prefix != "")
      ObjectsDeleteAll(0, g_bmp_prefix);
   for(int i = 0; i <= g_max_drawn_bar; i++)
     {
      string MasName = "::" + IntegerToString(g_chart_id) + "_JJGradHisto_Maps_" + IntegerToString(i);
      ResourceFree(MasName);
     }
   g_max_drawn_bar = 0;
  }

//+------------------------------------------------------------------+
//| Get subwindow min/max price with visible-buffer fallback         |
//+------------------------------------------------------------------+
bool GetSubwinMinMax(const int subwin, double &pMin, double &pMax)
  {
   pMin = ChartGetDouble(0, CHART_PRICE_MIN, subwin);
   pMax = ChartGetDouble(0, CHART_PRICE_MAX, subwin);
   if(pMax > pMin)
      return true;

   int FVB = ChartFirstVisibleBar(0);
   int VB  = ChartVisibleBars(0);
   if(FVB < 0 || VB <= 0 || g_rates_total <= 0)
      return false;

   int vB = FVB - VB;
   int startShift = (vB < 0) ? 0 : vB;
   int endShift   = FVB + 3;
   int bufSize    = ArraySize(OscBuffer);

   double minV  = 0.0;
   double maxV  = 0.0;
   bool   found = false;

   for(int shift = startShift; shift <= endShift; shift++)
     {
      int barIdx = g_rates_total - 1 - shift;
      if(barIdx < 0 || barIdx >= bufSize)
         continue;
      double v = OscBuffer[barIdx];
      if(v == EMPTY_VALUE)
         continue;
      if(!found)
        {
         minV  = MathMin(0.0, v);
         maxV  = MathMax(0.0, v);
         found = true;
        }
      else
        {
         if(v < minV) minV = v;
         if(v > maxV) maxV = v;
        }
     }

   if(!found || maxV <= minV)
      return false;

   double span = (maxV - minV) * 0.08;
   pMin = (minV < 0.0) ? (minV - span) : 0.0;
   pMax = (maxV > 0.0) ? (maxV + span) : 0.0;
   return (pMax > pMin);
  }

//+------------------------------------------------------------------+
//| Update the current forming bar (bar 0)                           |
//+------------------------------------------------------------------+
void DrawFirstGradient(const datetime barTime, const datetime prevTime, const double oscVal, const int stateIdx)
  {
   if(oscVal == EMPTY_VALUE)
      return;

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

   int subwinHeight = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, g_subwin);
   if(subwinHeight <= 0)
      return;

   double pMin = 0.0, pMax = 0.0;
   if(!GetSubwinMinMax(g_subwin, pMin, pMax))
      return;

   double chartMin = ChartGetDouble(0, CHART_PRICE_MIN, 0);
   double chartMax = ChartGetDouble(0, CHART_PRICE_MAX, 0);
   double midChartPrice = (chartMax > chartMin) ? (chartMin + chartMax) * 0.5 : 0.0;

   int Cx = 0, dummyY = 0, CxP = 0;
   if(!ChartTimePriceToXY(0, 0, barTime, midChartPrice, Cx, dummyY))
      return;
   if(!ChartTimePriceToXY(0, 0, prevTime, midChartPrice, CxP, dummyY))
      return;

   if(Cx <= 0 || CxP <= 0)
      return;

   int LengtOfBar = Cx - CxP;
   if(LengtOfBar <= 0)
      return;

   int barWidth = LengtOfBar - g_scale;
   if(barWidth < 1)
      barWidth = 1;

   int CyZero = PriceToY(0.0, pMin, pMax, subwinHeight);
   int CyVal  = PriceToY(oscVal, pMin, pMax, subwinHeight);

   int yTop = MathMin(CyZero, CyVal);
   int yBot = MathMax(CyZero, CyVal);
   int barHeight = yBot - yTop;
   if(barHeight < 1)
      barHeight = 1;

   if(yTop < 0)
     {
      barHeight += yTop;
      yTop = 0;
     }
   if(barHeight > subwinHeight)
      barHeight = subwinHeight;
   if(barHeight < 1)
      return;

   bool invertGrad = (oscVal < 0.0);
   int state = stateIdx;
   if(state < 0) state = 0;
   if(state > 3) state = 3;

   uint MapStorage[];
   FillMap(MapStorage, barWidth, barHeight, Storage[state], invertGrad);

   string D       = g_bmp_prefix + "0";
   string MasName = "::" + IntegerToString(g_chart_id) + "_JJGradHisto_Maps_0";

   ResourceFree(MasName);
   ResourceCreate(MasName, MapStorage, barWidth, barHeight, 0, 0, 0, COLOR_FORMAT_ARGB_NORMALIZE);

   if(ObjectFind(0, D) < 0)
      ObjectCreate(0, D, OBJ_BITMAP_LABEL, g_subwin, 0, 0);

   ObjectSetString (0, D, OBJPROP_BMPFILE, 0, MasName);
   ObjectSetInteger(0, D, OBJPROP_CORNER, CORNER_LEFT_UPPER);
   ObjectSetInteger(0, D, OBJPROP_XDISTANCE, Cx - barWidth / 2);
   ObjectSetInteger(0, D, OBJPROP_YDISTANCE, yTop);
   ObjectSetInteger(0, D, OBJPROP_BACK, true);
   ObjectSetInteger(0, D, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, D, OBJPROP_SELECTED, false);
   ObjectSetInteger(0, D, OBJPROP_HIDDEN, true);
  }

//+------------------------------------------------------------------+
//| Draw all visible gradient histogram bars                         |
//+------------------------------------------------------------------+
bool DrawFullGradient()
  {
   g_subwin = GetSubwindow();
   if(g_subwin <= 0)
      return false;

   UpdateDimensions();
   UpdateScale();

   int subwinHeight = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, g_subwin);
   if(subwinHeight <= 0)
      return false;

   int FVB = ChartFirstVisibleBar(0);
   int VB  = ChartVisibleBars(0);
   if(FVB < 0 || VB <= 0)
      return false;

   int vB = FVB - VB;
   int startShift = (vB < 0) ? 0 : vB;
   int endShift   = FVB + 3;

   datetime times[];
   ArraySetAsSeries(times, true);
   int copied = CopyTime(_Symbol, _Period, 0, endShift + 3, times);
   if(copied <= 1)
      return false;

   if(endShift >= copied - 1)
      endShift = copied - 2;
   if(startShift > endShift)
      return false;

   double pMin = 0.0, pMax = 0.0;
   if(!GetSubwinMinMax(g_subwin, pMin, pMax))
      return false;

   double chartMin = ChartGetDouble(0, CHART_PRICE_MIN, 0);
   double chartMax = ChartGetDouble(0, CHART_PRICE_MAX, 0);
   double midChartPrice = (chartMax > chartMin) ? (chartMin + chartMax) * 0.5 : 0.0;

   // 1. Delete previous objects and free old resources
   DeleteIndicatorObjects();

   // 2. Draw visible bars
   uint MapStorage[];
   int lastBarWidth = 0;
   int barsDrawn    = 0;

   for(int shift = startShift; shift <= endShift; shift++)
     {
      int barIdx = g_rates_total - 1 - shift;
      if(barIdx < 0 || barIdx >= ArraySize(OscBuffer))
         continue;

      double oscVal = OscBuffer[barIdx];
      if(oscVal == EMPTY_VALUE)
         continue;

      int Cx = 0, CxP = 0, dummyY = 0;
      if(!ChartTimePriceToXY(0, 0, times[shift], midChartPrice, Cx, dummyY))
         continue;

      int LengtOfBar = 0;
      if(ChartTimePriceToXY(0, 0, times[shift + 1], midChartPrice, CxP, dummyY) && Cx > 0 && CxP > 0)
        {
         LengtOfBar = Cx - CxP;
         if(LengtOfBar > 0)
            lastBarWidth = LengtOfBar;
        }
      else if(Cx > 0 && lastBarWidth > 0)
        {
         LengtOfBar = lastBarWidth;
        }
      else
         continue;

      if(LengtOfBar <= 0)
         continue;

      int barWidth = LengtOfBar - g_scale;
      if(barWidth < 1)
         barWidth = 1;

      int CyZero = PriceToY(0.0, pMin, pMax, subwinHeight);
      int CyVal  = PriceToY(oscVal, pMin, pMax, subwinHeight);

      int yTop = MathMin(CyZero, CyVal);
      int yBot = MathMax(CyZero, CyVal);
      int barHeight = yBot - yTop;
      if(barHeight < 1)
         barHeight = 1;

      if(yTop < 0)
        {
         barHeight += yTop;
         yTop = 0;
        }
      if(barHeight > subwinHeight)
         barHeight = subwinHeight;
      if(barHeight < 1)
         continue;

      bool invertGrad = (oscVal < 0.0);
      int state = (int)OscColorBuffer[barIdx];
      if(state < 0) state = 0;
      if(state > 3) state = 3;

      FillMap(MapStorage, barWidth, barHeight, Storage[state], invertGrad);

      string D       = g_bmp_prefix + IntegerToString(shift);
      string MasName = "::" + IntegerToString(g_chart_id) + "_JJGradHisto_Maps_" + IntegerToString(shift);

      ResourceFree(MasName);
      ResourceCreate(MasName, MapStorage, barWidth, barHeight, 0, 0, 0, COLOR_FORMAT_ARGB_NORMALIZE);

      if(ObjectFind(0, D) < 0)
         ObjectCreate(0, D, OBJ_BITMAP_LABEL, g_subwin, 0, 0);

      ObjectSetString (0, D, OBJPROP_BMPFILE, 0, MasName);
      ObjectSetInteger(0, D, OBJPROP_CORNER, CORNER_LEFT_UPPER);
      ObjectSetInteger(0, D, OBJPROP_XDISTANCE, Cx - barWidth / 2);
      ObjectSetInteger(0, D, OBJPROP_YDISTANCE, yTop);
      ObjectSetInteger(0, D, OBJPROP_BACK, true);
      ObjectSetInteger(0, D, OBJPROP_SELECTABLE, false);
      ObjectSetInteger(0, D, OBJPROP_SELECTED, false);
      ObjectSetInteger(0, D, OBJPROP_HIDDEN, true);

      if(shift > g_max_drawn_bar)
         g_max_drawn_bar = shift;
      barsDrawn++;
     }

   g_lastFVB     = FVB;
   g_lastVB      = VB;
   g_lastChartSc = ChartScaleGet(0);
   g_lastPMin    = pMin;
   g_lastPMax    = pMax;

   ChartRedraw(0);
   return (barsDrawn > 0);
  }

//+------------------------------------------------------------------+
//| Helper: Extract selected applied price                           |
//+------------------------------------------------------------------+
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];
     }
  }

//+------------------------------------------------------------------+
//| SuperSmoother - second-order IIR filter (Ehlers)                 |
//| r1, r2 = previous two output values (res[1], res[2] in Pine)     |
//+------------------------------------------------------------------+
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)   // Pine: if bar_index >= 4
      return(a0 * (src + srcPrev) + c1 * r1 - c2 * r2);

   return(src);
  }

//+------------------------------------------------------------------+
//| Root Mean Square of the one-bar changes of a buffer over the     |
//| last InpRMSLength bars (Pine: RMS(Source, 81))                   |
//+------------------------------------------------------------------+
double RMSOfBuffer(const double &buf[], const int i)
  {
   int cnt = MathMin(InpRMSLength, i);   // available one-bar changes
   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));
  }

//+------------------------------------------------------------------+
//| Helper: Store gradient colors for a state                        |
//+------------------------------------------------------------------+
void InitGradientState(Gradient &dst, const color lo, const color hi, const color ln, const int op0, const int op1)
  {
   dst.R[0] = lo & 0xFF;
   dst.G[0] = (lo >> 8) & 0xFF;
   dst.B[0] = (lo >> 16) & 0xFF;
   dst.O[0] = (uint)MathMin(MathMax(op0, 0), 255);

   dst.R[1] = hi & 0xFF;
   dst.G[1] = (hi >> 8) & 0xFF;
   dst.B[1] = (hi >> 16) & 0xFF;
   dst.O[1] = (uint)MathMin(MathMax(op1, 0), 255);

   dst.Line = (uint)ln;
  }

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

   //--- Bind indicator buffers (plot order is positional)
   SetIndexBuffer(0, OscBuffer,      INDICATOR_DATA);
   SetIndexBuffer(1, OscColorBuffer, INDICATOR_COLOR_INDEX);
   SetIndexBuffer(2, OscLineBuffer,  INDICATOR_DATA);
   SetIndexBuffer(3, OscLineColors,  INDICATOR_COLOR_INDEX);
   SetIndexBuffer(4, BufferZero,     INDICATOR_DATA);

   SetIndexBuffer(5, JackBuffer,     INDICATOR_CALCULATIONS);
   SetIndexBuffer(6, JillBuffer,     INDICATOR_CALCULATIONS);
   SetIndexBuffer(7, JackNextPeriod, INDICATOR_CALCULATIONS);
   SetIndexBuffer(8, JillNextPeriod, INDICATOR_CALCULATIONS);

   //--- Standard chronological indexing (index 0 is oldest bar)
   ArraySetAsSeries(OscBuffer,       false);
   ArraySetAsSeries(OscColorBuffer,  false);
   ArraySetAsSeries(OscLineBuffer,   false);
   ArraySetAsSeries(OscLineColors,   false);
   ArraySetAsSeries(BufferZero,      false);
   ArraySetAsSeries(JackBuffer,      false);
   ArraySetAsSeries(JillBuffer,      false);
   ArraySetAsSeries(JackNextPeriod,  false);
   ArraySetAsSeries(JillNextPeriod,  false);

   //--- Plot 1: invisible auto-scaling histogram for gradient overlay + DataWindow
   PlotIndexSetInteger(0, PLOT_COLOR_INDEXES, 4);
   for(int k = 0; k < 4; k++)
      PlotIndexSetInteger(0, PLOT_LINE_COLOR, k, clrNONE);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);

   //--- Plot 2: single 4-color slope oscillator line (width 2 by default)
   color baseColors[5] = {InpCandleUp, InpCandleWt, InpCandleDn,
                          InpCandleUpWeak, InpCandleDnWeak};

   PlotIndexSetInteger(1, PLOT_COLOR_INDEXES, 5);
   PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(1, PLOT_DRAW_TYPE, InpShowLine ? DRAW_COLOR_LINE : DRAW_NONE);
   PlotIndexSetInteger(1, PLOT_SHOW_DATA, InpShowLine);
   PlotIndexSetInteger(1, PLOT_LINE_WIDTH, ClampWidth(InpLineWidth));
   for(int c = 0; c < 5; c++)
      PlotIndexSetInteger(1, PLOT_LINE_COLOR, c, baseColors[c]);

   //--- Plot 3: Zero reference line
   PlotIndexSetDouble(2, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(2, PLOT_LINE_COLOR, 0, InpZeroColor);
   PlotIndexSetInteger(2, PLOT_LINE_WIDTH, ClampWidth(InpZeroWidth));

   //--- Initialize 4 gradient states (Boss_Volume style)
   InitGradientState(Storage[0], InpLo0, InpHi0, InpLn0, InpOp0, InpOP0);
   InitGradientState(Storage[1], InpLo1, InpHi1, InpLn1, InpOp1, InpOP1);
   InitGradientState(Storage[2], InpLo2, InpHi2, InpLn2, InpOp2, InpOP2);
   InitGradientState(Storage[3], InpLo3, InpHi3, InpLn3, InpOp3, InpOP3);

   //--- Visual configuration
   IndicatorSetInteger(INDICATOR_DIGITS, _Digits);
   g_shortName = StringFormat("[%s] [%s] Jack & Jill (gradient_histo) (%.1f, %d)",
                              Symbol(), GetStringTimeframe(_Period), InpPeriod0, InpRMSLength);
   IndicatorSetString(INDICATOR_SHORTNAME, g_shortName);

   g_chart_id    = ChartID();
   g_bmp_prefix  = "JJGradHisto_Bmp_" + IntegerToString(g_chart_id) + "_";
   g_subwin      = GetSubwindow();
   g_initialized = false;

   UpdateDimensions();
   UpdateScale();

   EventSetTimer(2);
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   EventKillTimer();
   DeleteIndicatorObjects();
   ChartRedraw(0);
  }

//+------------------------------------------------------------------+
//| Chart event handler (redraw gradient bars on scroll/zoom/resize) |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
   if(id == CHARTEVENT_CHART_CHANGE && g_initialized)
     {
      if(g_subwin <= 0)
         g_subwin = GetSubwindow();
      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  = ChartScaleGet(0);
      int fvb = ChartFirstVisibleBar(0);
      int vb  = ChartVisibleBars(0);
      double pMin = ChartGetDouble(0, CHART_PRICE_MIN, g_subwin);
      double pMax = ChartGetDouble(0, CHART_PRICE_MAX, g_subwin);

      if(w != g_subWidth || h != g_subHeight || sc != g_lastChartSc ||
         fvb != g_lastFVB || vb != g_lastVB || pMin != g_lastPMin || pMax != g_lastPMax)
        {
         DrawFullGradient();
        }
     }
  }

//+------------------------------------------------------------------+
//| Timer fallback to render gradient bars after initial load        |
//+------------------------------------------------------------------+
void OnTimer()
  {
   if(g_initialized && g_max_drawn_bar <= 0)
      DrawFullGradient();
  }

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

   if(prev_calculated == rates_total)
      return(rates_total);

   int w = ChartWindowFind();
   if(w > 0) g_subwin = w;

   g_rates_total = rates_total;
   ArraySetAsSeries(time, false);

   bool full  = (prev_calculated <= 0 || prev_calculated > rates_total);
   int start  = full ? 0 : (prev_calculated - 1);
   int endBar = rates_total - 1; // closed bars only (0 .. rates_total - 2)

   for(int i = start; i < endBar && !IsStopped(); i++)
     {
      double src     = GetAppliedPrice(i, open, high, low, close);
      double srcPrev = (i > 0) ? GetAppliedPrice(i - 1, open, high, low, close) : src;

      // Period state entering this bar (Pine: var float, InpPeriod0 on bar 0)
      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 (Jack - Jill) and zero baseline -------------
      double osc    = JackBuffer[i] - JillBuffer[i];
      OscBuffer[i]  = osc;
      BufferZero[i] = 0.0;

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

      //--- 4. Gradient histogram 4-state mapping ---------------------
      int gradState;
      if(osc >= 0.0)
         gradState = falling ? 1 : 0;   // 0: Above Zero & Rising, 1: Above Zero & Falling
      else
         gradState = rising  ? 3 : 2;   // 2: Below Zero & Falling, 3: Below Zero & Rising
      OscColorBuffer[i] = (double)gradState;

      //--- 5. Single 4-color slope oscillator line -------------------
      int lineColorIdx = 1;             // neutral at zero
      if(osc > 0.0)
         lineColorIdx = (InpUse4Colors && falling) ? 3 : 0;
      else if(osc < 0.0)
         lineColorIdx = (InpUse4Colors && rising)  ? 4 : 2;

      OscLineBuffer[i] = osc;
      OscLineColors[i] = lineColorIdx;
     }

   // Leave current forming bar blank until candle close
   int cur = rates_total - 1;
   OscBuffer[cur]      = EMPTY_VALUE;
   OscColorBuffer[cur] = 0.0;
   OscLineBuffer[cur]  = EMPTY_VALUE;
   OscLineColors[cur]  = 1.0;
   BufferZero[cur]     = EMPTY_VALUE;

   g_initialized = true;
   DrawFullGradient();

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