//+------------------------------------------------------------------+
//|                                        JackJill(thick_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   |
//|  styled with 3D FX Histogram, 3D FX Line, and Zero reference.    |
//+------------------------------------------------------------------+
#property copyright "Conversion of John F. Ehlers (TASC Dec 2026) Jack & Jill Indicator"
#property link      ""
#property version   "1.20"
#property description "TASC Issue: December 2026"
#property description "Article: A Trend Indicator - The Jack & Jill Indicator"
#property description "Article By: John F. Ehlers"

//--- Place in separate indicator subwindow
#property indicator_separate_window
#property indicator_buffers 17
#property indicator_plots   7

//--- Plot 1,2,3: 3D Oscillator Histogram
#property indicator_type1   DRAW_COLOR_HISTOGRAM
#property indicator_width1  5
#property indicator_label1  "Osc Hist Outer"

#property indicator_type2   DRAW_COLOR_HISTOGRAM
#property indicator_width2  3
#property indicator_label2  "Osc Hist Core"

#property indicator_type3   DRAW_COLOR_HISTOGRAM
#property indicator_width3  1
#property indicator_label3  "Osc Hist Highlight"

//--- Plot 4,5,6: 3D Oscillator Line
#property indicator_type4   DRAW_COLOR_LINE
#property indicator_width4  5
#property indicator_label4  "Osc Line Outer"

#property indicator_type5   DRAW_COLOR_LINE
#property indicator_width5  3
#property indicator_label5  "Osc Line Core"

#property indicator_type6   DRAW_COLOR_LINE
#property indicator_width6  1
#property indicator_label6  "Osc Line Highlight"

//--- Plot 7: Zero reference line
#property indicator_type7   DRAW_LINE
#property indicator_color7  clrGold
#property indicator_width7  1
#property indicator_label7  "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 "--- 3D Histogram Widths ---"
input int                InpHistOuterWidth = 5;              // Histogram outer width (1-5)
input int                InpHistCoreWidth  = 3;              // Histogram core width (1-5)
input int                InpHistInnerWidth = 1;              // Histogram highlight width (1-5)

input group "--- 3D Line Widths ---"
input int                InpLineOuterWidth = 5;              // Line outer width (1-5)
input int                InpLineCoreWidth  = 3;              // Line core width (1-5)
input int                InpLineInnerWidth = 1;              // Line highlight width (1-5)

input group "--- FX 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)

//+------------------------------------------------------------------+
//| Indicator Buffers                                                |
//+------------------------------------------------------------------+
double HistDarkBuffer[];   double HistDarkColors[];    // Plot 1
double HistBaseBuffer[];   double HistBaseColors[];    // Plot 2
double HistLightBuffer[];  double HistLightColors[];   // Plot 3

double LineDarkBuffer[];   double LineDarkColors[];    // Plot 4
double LineBaseBuffer[];   double LineBaseColors[];    // Plot 5
double LineLightBuffer[];  double LineLightColors[];   // Plot 6

double BufferZero[];                                   // Plot 7

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

//+------------------------------------------------------------------+
//| Utility: Blend two colors by a given ratio (for 3D shading)      |
//+------------------------------------------------------------------+
color BlendColor(color c, color blendWith, double ratio)
  {
   int r1 = (int)(c & 0x0000FF);
   int g1 = (int)((c & 0x00FF00) >> 8);
   int b1 = (int)((c & 0xFF0000) >> 16);
   int r2 = (int)(blendWith & 0x0000FF);
   int g2 = (int)((blendWith & 0x00FF00) >> 8);
   int b2 = (int)((blendWith & 0xFF0000) >> 16);

   int r = (int)MathRound(r1 + (r2 - r1) * ratio);
   int g = (int)MathRound(g1 + (g2 - g1) * ratio);
   int b = (int)MathRound(b1 + (b2 - b1) * ratio);
   return (color)(r | (g << 8) | (b << 16));
  }

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

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

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

   //--- Bind indicator buffers (plot order is positional)
   SetIndexBuffer(0,  HistDarkBuffer,   INDICATOR_DATA);
   SetIndexBuffer(1,  HistDarkColors,   INDICATOR_COLOR_INDEX);
   SetIndexBuffer(2,  HistBaseBuffer,   INDICATOR_DATA);
   SetIndexBuffer(3,  HistBaseColors,   INDICATOR_COLOR_INDEX);
   SetIndexBuffer(4,  HistLightBuffer,  INDICATOR_DATA);
   SetIndexBuffer(5,  HistLightColors,  INDICATOR_COLOR_INDEX);

   SetIndexBuffer(6,  LineDarkBuffer,   INDICATOR_DATA);
   SetIndexBuffer(7,  LineDarkColors,   INDICATOR_COLOR_INDEX);
   SetIndexBuffer(8,  LineBaseBuffer,   INDICATOR_DATA);
   SetIndexBuffer(9,  LineBaseColors,   INDICATOR_COLOR_INDEX);
   SetIndexBuffer(10, LineLightBuffer,  INDICATOR_DATA);
   SetIndexBuffer(11, LineLightColors,  INDICATOR_COLOR_INDEX);

   SetIndexBuffer(12, BufferZero,       INDICATOR_DATA);

   SetIndexBuffer(13, JackBuffer,       INDICATOR_CALCULATIONS);
   SetIndexBuffer(14, JillBuffer,       INDICATOR_CALCULATIONS);
   SetIndexBuffer(15, JackNextPeriod,   INDICATOR_CALCULATIONS);
   SetIndexBuffer(16, JillNextPeriod,   INDICATOR_CALCULATIONS);

   //--- Standard chronological indexing (index 0 is oldest bar)
   ArraySetAsSeries(HistDarkBuffer,    false);
   ArraySetAsSeries(HistDarkColors,    false);
   ArraySetAsSeries(HistBaseBuffer,    false);
   ArraySetAsSeries(HistBaseColors,    false);
   ArraySetAsSeries(HistLightBuffer,   false);
   ArraySetAsSeries(HistLightColors,   false);
   ArraySetAsSeries(LineDarkBuffer,    false);
   ArraySetAsSeries(LineDarkColors,    false);
   ArraySetAsSeries(LineBaseBuffer,    false);
   ArraySetAsSeries(LineBaseColors,    false);
   ArraySetAsSeries(LineLightBuffer,   false);
   ArraySetAsSeries(LineLightColors,   false);
   ArraySetAsSeries(BufferZero,        false);
   ArraySetAsSeries(JackBuffer,        false);
   ArraySetAsSeries(JillBuffer,        false);
   ArraySetAsSeries(JackNextPeriod,    false);
   ArraySetAsSeries(JillNextPeriod,    false);

   //--- FX palette: index 0 = strong bull, 1 = neutral, 2 = strong bear,
   //    3 = weak bull, 4 = weak bear
   color baseColors[5] = {InpCandleUp, InpCandleWt, InpCandleDn,
                          InpCandleUpWeak, InpCandleDnWeak};

   for(int p = 0; p < 6; p++)
     {
      PlotIndexSetInteger(p, PLOT_COLOR_INDEXES, 5);
      PlotIndexSetDouble(p, PLOT_EMPTY_VALUE, EMPTY_VALUE);
     }
   PlotIndexSetDouble(6, PLOT_EMPTY_VALUE, EMPTY_VALUE);

   for(int c = 0; c < 5; c++)
     {
      color base  = baseColors[c];
      color dark  = BlendColor(base, clrBlack, 0.4);  // 40% darker edge
      color light = BlendColor(base, clrWhite, 0.6);  // 60% lighter core

      //--- 3D histogram layers: outer (dark) -> core (base) -> highlight (light)
      PlotIndexSetInteger(0, PLOT_LINE_COLOR, c, dark);
      PlotIndexSetInteger(1, PLOT_LINE_COLOR, c, base);
      PlotIndexSetInteger(2, PLOT_LINE_COLOR, c, light);

      //--- 3D oscillator line layers
      PlotIndexSetInteger(3, PLOT_LINE_COLOR, c, dark);
      PlotIndexSetInteger(4, PLOT_LINE_COLOR, c, base);
      PlotIndexSetInteger(5, PLOT_LINE_COLOR, c, light);
     }

   //--- Layer widths (outer -> highlight)
   PlotIndexSetInteger(0, PLOT_LINE_WIDTH, ClampWidth(InpHistOuterWidth));
   PlotIndexSetInteger(1, PLOT_LINE_WIDTH, ClampWidth(InpHistCoreWidth));
   PlotIndexSetInteger(2, PLOT_LINE_WIDTH, ClampWidth(InpHistInnerWidth));

   PlotIndexSetInteger(3, PLOT_LINE_WIDTH, ClampWidth(InpLineOuterWidth));
   PlotIndexSetInteger(4, PLOT_LINE_WIDTH, ClampWidth(InpLineCoreWidth));
   PlotIndexSetInteger(5, PLOT_LINE_WIDTH, ClampWidth(InpLineInnerWidth));

   //--- Zero reference
   PlotIndexSetInteger(6, PLOT_LINE_COLOR, 0, InpZeroColor);
   PlotIndexSetInteger(6, PLOT_LINE_WIDTH, ClampWidth(InpZeroWidth));

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

   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| 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 start  = (prev_calculated > 0) ? prev_calculated - 1 : 0;
   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);

      // RMS of jack's one-bar change, normalized in standard deviations
      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;

      // Period for adaptive SuperSmoother (jack) on next bar
      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;

      // Period for contra-adaptive SuperSmoother (jill) on next bar
      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];
      BufferZero[i] = 0.0;

      //--- 4. FX color mapping from oscillator sign and slope --------
      bool rising  = (i > 0 && osc > LineBaseBuffer[i - 1]);
      bool falling = (i > 0 && osc < LineBaseBuffer[i - 1]);

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

      //--- 5. Populate 3D histogram layers ---------------------------
      HistDarkBuffer[i]  = osc;  HistDarkColors[i]  = colorIdx;
      HistBaseBuffer[i]  = osc;  HistBaseColors[i]  = colorIdx;
      HistLightBuffer[i] = osc;  HistLightColors[i] = colorIdx;

      //--- 6. Populate 3D oscillator line layers ---------------------
      LineDarkBuffer[i]  = osc;  LineDarkColors[i]  = colorIdx;
      LineBaseBuffer[i]  = osc;  LineBaseColors[i]  = colorIdx;
      LineLightBuffer[i] = osc;  LineLightColors[i] = colorIdx;
     }

   // Leave current forming bar blank until candle close
   int cur = rates_total - 1;
   HistDarkBuffer[cur]  = EMPTY_VALUE; HistDarkColors[cur]  = 1;
   HistBaseBuffer[cur]  = EMPTY_VALUE; HistBaseColors[cur]  = 1;
   HistLightBuffer[cur] = EMPTY_VALUE; HistLightColors[cur] = 1;
   LineDarkBuffer[cur]  = EMPTY_VALUE; LineDarkColors[cur]  = 1;
   LineBaseBuffer[cur]  = EMPTY_VALUE; LineBaseColors[cur]  = 1;
   LineLightBuffer[cur] = EMPTY_VALUE; LineLightColors[cur] = 1;
   BufferZero[cur]      = EMPTY_VALUE;

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