//+------------------------------------------------------------------+
//|                                                SQZMOM_LB_100.mq5 |
//|                                              Bugscoder Studio    |
//|                                       https://www.bugscoder.com/ |
//+------------------------------------------------------------------+
#property copyright "Bugscoder Studio"
#property link      "https://www.tradingview.com/script/nqQ1DT5a-Squeeze-Momentum-Indicator-LazyBear/"
#property version   "1.00"
#property indicator_separate_window

#property indicator_buffers 10
#property indicator_plots   7

#property indicator_type1   DRAW_HISTOGRAM
#property indicator_color1  clrLime
#property indicator_width1  5
#property indicator_label1  "upup (1)"

#property indicator_type2   DRAW_HISTOGRAM
#property indicator_color2  clrGreen
#property indicator_width2  5
#property indicator_label2  "updn (2)"

#property indicator_type3   DRAW_HISTOGRAM
#property indicator_color3  clrRed
#property indicator_width3  5
#property indicator_label3  "dndn (3)"

#property indicator_type4   DRAW_HISTOGRAM
#property indicator_color4  clrMaroon
#property indicator_width4  5
#property indicator_label4  "dnup (4)"

#property indicator_type5   DRAW_ARROW
#property indicator_color5  clrBlue
#property indicator_width5  3
#property indicator_label5  "noSqz (5)"

#property indicator_type6   DRAW_ARROW
#property indicator_color6  clrOrange
#property indicator_width6  1
#property indicator_label6  "sqzOn (6)"

#property indicator_type7   DRAW_ARROW
#property indicator_color7  clrGray
#property indicator_width7  3
#property indicator_label7  "sqzOff (7)"

input int    length       = 20;   // BB Length
input double mult         = 2.0;  // BB MultFactor
input int    lengthKC     = 20;   // KC Length
input double multKC       = 1.5;  // KC MultFactor
input bool   useTrueRange = true; // Use TrueRange (KC)
input int    noSqzArrowCode  = 158; // Wingdings arrow code for noSqz
input int    sqzOnArrowCode  = 172; // Wingdings arrow code for sqzOn
input int    sqzOffArrowCode = 158; // Wingdings arrow code for sqzOff

//--- plot buffers
double upup[], updn[], dndn[], dnup[];
double no[], On[], Off[];
//--- calculation buffers (not drawn)
double range[], linregsrc[], linreg[];

string obj_prefix = "SQZMOM_LB_";

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
   IndicatorSetInteger(INDICATOR_DIGITS, _Digits);

   SetIndexBuffer(0, upup,  INDICATOR_DATA);
   SetIndexBuffer(1, updn,  INDICATOR_DATA);
   SetIndexBuffer(2, dndn,  INDICATOR_DATA);
   SetIndexBuffer(3, dnup,  INDICATOR_DATA);
   SetIndexBuffer(4, no,    INDICATOR_DATA);
   SetIndexBuffer(5, On,    INDICATOR_DATA);
   SetIndexBuffer(6, Off,   INDICATOR_DATA);
   SetIndexBuffer(7, range, INDICATOR_CALCULATIONS);
   SetIndexBuffer(8, linregsrc, INDICATOR_CALCULATIONS);
   SetIndexBuffer(9, linreg,    INDICATOR_CALCULATIONS);

   PlotIndexSetInteger(4, PLOT_ARROW, noSqzArrowCode);
   PlotIndexSetInteger(5, PLOT_ARROW, sqzOnArrowCode);
   PlotIndexSetInteger(6, PLOT_ARROW, sqzOffArrowCode);

   for(int i=0; i<7; i++)
      PlotIndexSetDouble(i, PLOT_EMPTY_VALUE, EMPTY_VALUE);

   IndicatorSetString(INDICATOR_SHORTNAME, "SQZMOM");
   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[])
  {
   int maxPeriod = MathMax(length, lengthKC);
   if(rates_total <= maxPeriod + 2)
      return(0);

//--- series indexing: index 0 is the current bar (same as the MQL4 version)
   ArraySetAsSeries(time,   true);
   ArraySetAsSeries(high,   true);
   ArraySetAsSeries(low,    true);
   ArraySetAsSeries(close,  true);
   ArraySetAsSeries(upup,   true);
   ArraySetAsSeries(updn,   true);
   ArraySetAsSeries(dndn,   true);
   ArraySetAsSeries(dnup,   true);
   ArraySetAsSeries(no,     true);
   ArraySetAsSeries(On,     true);
   ArraySetAsSeries(Off,    true);
   ArraySetAsSeries(range,  true);
   ArraySetAsSeries(linregsrc, true);
   ArraySetAsSeries(linreg, true);

   int startPos = rates_total - prev_calculated - lengthKC - 2;
   if(startPos > rates_total - maxPeriod - 2)
      startPos = rates_total - maxPeriod - 2;
   if(startPos <= 1)
      startPos = 1;

   for(int pos=startPos; pos>=0; pos--)
     {
      //--- Bollinger Bands
      double basis   = SMAOf(close, pos, length);
      double dev     = mult * StdDevOf(close, pos, length);
      double upperBB = basis + dev;
      double lowerBB = basis - dev;

      //--- Keltner Channel
      double ma      = SMAOf(close, pos, lengthKC);
      range[pos]     = useTrueRange ? TrueRange(high, low, close, pos) : (high[pos] - low[pos]);
      double rangema = SMAOf(range, pos, lengthKC);
      double upperKC = ma + rangema * multKC;
      double lowerKC = ma - rangema * multKC;

      bool sqzOn  = (lowerBB > lowerKC) && (upperBB < upperKC);
      bool sqzOff = (lowerBB < lowerKC) && (upperBB > upperKC);
      bool noSqz  = (sqzOn == false) && (sqzOff == false);

      double highest = HighestOf(high, pos, lengthKC);
      double lowest  = LowestOf(low, pos, lengthKC);
      double sma     = ma;

      linregsrc[pos] = close[pos] - (((highest + lowest) / 2.0) + sma) / 2.0;
      linreg[pos]    = LinRegValue(linregsrc, lengthKC, pos);

      upup[pos] = linreg[pos] > 0 && linreg[pos] > nz(linreg[pos+1]) ? linreg[pos] : EMPTY_VALUE;
      updn[pos] = linreg[pos] > 0 && linreg[pos] < nz(linreg[pos+1]) ? linreg[pos] : EMPTY_VALUE;
      dndn[pos] = linreg[pos] < 0 && linreg[pos] < nz(linreg[pos+1]) ? linreg[pos] : EMPTY_VALUE;
      dnup[pos] = linreg[pos] < 0 && linreg[pos] > nz(linreg[pos+1]) ? linreg[pos] : EMPTY_VALUE;

      no[pos]  = (noSqz == true)  ? 0 : EMPTY_VALUE;
      On[pos]  = (sqzOn == true)  ? 0 : EMPTY_VALUE;
      Off[pos] = (sqzOff == true) ? 0 : EMPTY_VALUE;
     }

   return(rates_total);
  }

//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   ObjectsDeleteAll(0, obj_prefix);
  }

//+------------------------------------------------------------------+
//| Simple moving average of src[start .. start+period-1]            |
//+------------------------------------------------------------------+
double SMAOf(const double &src[], const int start, const int period)
  {
   double sum = 0;
   for(int k=0; k<period; k++)
      sum += src[start+k];
   return(sum / period);
  }

//+------------------------------------------------------------------+
//| Population standard deviation (same as MQL4 iStdDev, MODE_SMA)   |
//+------------------------------------------------------------------+
double StdDevOf(const double &src[], const int start, const int period)
  {
   double mean = SMAOf(src, start, period);
   double sum  = 0;
   for(int k=0; k<period; k++)
     {
      double d = src[start+k] - mean;
      sum += d * d;
     }
   return(MathSqrt(sum / period));
  }

//+------------------------------------------------------------------+
//| Highest high over high[start .. start+period-1]                  |
//+------------------------------------------------------------------+
double HighestOf(const double &src[], const int start, const int period)
  {
   double res = src[start];
   for(int k=1; k<period; k++)
      if(src[start+k] > res)
         res = src[start+k];
   return(res);
  }

//+------------------------------------------------------------------+
//| Lowest low over low[start .. start+period-1]                     |
//+------------------------------------------------------------------+
double LowestOf(const double &src[], const int start, const int period)
  {
   double res = src[start];
   for(int k=1; k<period; k++)
      if(src[start+k] < res)
         res = src[start+k];
   return(res);
  }

//+------------------------------------------------------------------+
//| True range of bar 'shift'                                        |
//+------------------------------------------------------------------+
double TrueRange(const double &h[], const double &l[], const double &c[], const int shift)
  {
   double t1 = h[shift] - l[shift];
   double t2 = MathAbs(h[shift] - c[shift+1]);
   double t3 = MathAbs(l[shift] - c[shift+1]);
   return(MathMax(MathMax(t1, t2), t3));
  }

//+------------------------------------------------------------------+
//| Linear regression end-point value of src over p bars from i      |
//+------------------------------------------------------------------+
double LinRegValue(const double &src[], const int p, const int i)
  {
   double SumY  = 0;
   double Sum1  = 0;
   double Slope = 0;

   for(int x=0; x<=p-1; x++)
     {
      double c = src[x+i];
      SumY += c;
      Sum1 += x * c;
     }

   double SumBars    = p * (p - 1) * 0.5;
   double SumSqrBars = (p - 1) * p * (2 * p - 1) / 6;
   double Sum2       = SumBars * SumY;
   double Num1       = p * Sum1 - Sum2;
   double Num2       = SumBars * SumBars - p * SumSqrBars;

   if(Num2 != 0)
      Slope = Num1 / Num2;
   else
      Slope = 0;

   double Intercept = (SumY - Slope * SumBars) / p;
   return(Intercept + Slope * (p - 1));
  }

//+------------------------------------------------------------------+
//| Replace EMPTY_VALUE with the given default                       |
//+------------------------------------------------------------------+
double nz(const double check, const double val = 0)
  {
   if(check == EMPTY_VALUE)
      return(val);
   return(check);
  }
//+------------------------------------------------------------------+
