//+------------------------------------------------------------------
//|
//+------------------------------------------------------------------
#property copyright "www.forex-station.com"
#property link      "www.forex-station.com"

#property indicator_separate_window
#property indicator_buffers 10
#property indicator_color1  clrDimGray
#property indicator_color2  clrDimGray
#property indicator_color3  clrDimGray
#property indicator_color4  clrKhaki
#property indicator_style2  STYLE_DOT
#property strict

enum enPrices
{
   pr_close,      // Close
   pr_open,       // Open
   pr_high,       // High
   pr_low,        // Low
   pr_median,     // Median
   pr_typical,    // Typical
   pr_weighted,   // Weighted
   pr_average,    // Average (high+low+open+close)/4
   pr_medianb,    // Average median body (open+close)/2
   pr_tbiased,    // Trend biased price
   pr_tbiased2,   // Trend biased (extreme) price
   pr_haclose,    // Heiken ashi close
   pr_haopen ,    // Heiken ashi open
   pr_hahigh,     // Heiken ashi high
   pr_halow,      // Heiken ashi low
   pr_hamedian,   // Heiken ashi median
   pr_hatypical,  // Heiken ashi typical
   pr_haweighted, // Heiken ashi weighted
   pr_haaverage,  // Heiken ashi average
   pr_hamedianb,  // Heiken ashi median body
   pr_hatbiased,  // Heiken ashi trend biased price
   pr_hatbiased2, // Heiken ashi trend biased (extreme) price
   pr_habclose,   // Heiken ashi (better formula) close
   pr_habopen ,   // Heiken ashi (better formula) open
   pr_habhigh,    // Heiken ashi (better formula) high
   pr_hablow,     // Heiken ashi (better formula) low
   pr_habmedian,  // Heiken ashi (better formula) median
   pr_habtypical, // Heiken ashi (better formula) typical
   pr_habweighted,// Heiken ashi (better formula) weighted
   pr_habaverage, // Heiken ashi (better formula) average
   pr_habmedianb, // Heiken ashi (better formula) median body
   pr_habtbiased, // Heiken ashi (better formula) trend biased price
   pr_habtbiased2 // Heiken ashi (better formula) trend biased (extreme) price
};
enum enColorOn
{
   cc_onSlope,   // Change color on slope change
   cc_onMiddle,  // Change color on middle line cross
   cc_onLevels   // Change color on outer levels cross
};
enum enLevelType
{
   lvl_floa,  // Floating levels
   lvl_quan,  // Quantile level
};

extern int             Length          = 14;             // Regularized momentum length
extern enPrices        Price           = pr_close;       // Regularized momentum price to use
extern double          Lambda          = 7;              // Lamda for smoothing
extern enLevelType     LevelType       = lvl_quan ;      // Level type : 
extern int             MinMaxPeriod    = 15;             // Floating levels period (<= 1 for fixed levels)
extern double          LevelUp         = 90.0;           // Up level %
extern double          LevelDown       = 10.0;           // Down level %
extern enColorOn       ColorOn         = cc_onSlope;     // Color change on :
extern color           ColorUp         = clrLimeGreen;   // Color for up
extern color           ColorDown       = clrRed;         // Color for down
extern int             LineWidth       = 3;              // Main line width
extern int             ShadowWidth     = 0;              // Shadow width (<=0 main line width+3) 

double mom[],rema[],buffer1da[],buffer1db[],buffer1ua[],buffer1ub[],levup[],levmi[],levdn[],trend[],shadowa[],shadowb[];

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

int init()
{
   int shadowWidth = (ShadowWidth<=0) ? LineWidth+3 : ShadowWidth;
   IndicatorBuffers(12);
   SetIndexBuffer(0, levup);
   SetIndexBuffer(1, levmi);
   SetIndexBuffer(2, levdn);
   SetIndexBuffer(3, mom);       SetIndexStyle(3,EMPTY,EMPTY,LineWidth);
   SetIndexBuffer(4, shadowa);   SetIndexStyle(4,EMPTY,EMPTY,ShadowWidth);
   SetIndexBuffer(5, shadowb);   SetIndexStyle(5,EMPTY,EMPTY,ShadowWidth);
   SetIndexBuffer(6, buffer1ua); SetIndexStyle(6,EMPTY,EMPTY,LineWidth,ColorUp);
   SetIndexBuffer(7, buffer1ub); SetIndexStyle(7,EMPTY,EMPTY,LineWidth,ColorUp);
   SetIndexBuffer(8, buffer1da); SetIndexStyle(8,EMPTY,EMPTY,LineWidth,ColorDown);
   SetIndexBuffer(9, buffer1db); SetIndexStyle(9,EMPTY,EMPTY,LineWidth,ColorDown);
   SetIndexBuffer(10,rema);
   SetIndexBuffer(11,trend);
      
   IndicatorShortName("Regularized momentum ("+(string)Length+")");
return(0);
}
int deinit() { return(0); }

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

int start()
{
   int i,limit,counted_bars=IndicatorCounted();
   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
         limit = fmin(Bars-counted_bars,Bars-1);

   //
   //
   //
   //
   //

   double alpha  = 2.0/(1.0+Length);      
   double regf1  = (1.0+Lambda*2.0);
   double regf2  = (1.0+Lambda);
   int    colorOn = (MinMaxPeriod>0) ? ColorOn : cc_onSlope;
   if (trend[limit]==-1) { CleanPoint(limit,buffer1da,buffer1db); CleanPoint(limit,shadowa,shadowb); }
   if (trend[limit]== 1) { CleanPoint(limit,buffer1ua,buffer1ub); CleanPoint(limit,shadowa,shadowb); }
   for(i=limit; i>=0; i--) 
   {
       double price = getPrice(Price,Open,Close,High,Low,i,Bars);
       rema[i] = (i<Bars-2) ? (regf1*rema[i+1]+alpha*(price-rema[i+1])-Lambda*rema[i+2])/regf2 : price;
       if (i<Bars-1) mom[i] = (rema[i]-rema[i+1])/rema[i];   
       buffer1da[i] = EMPTY_VALUE;
       buffer1db[i] = EMPTY_VALUE;
       buffer1ua[i] = EMPTY_VALUE;
       buffer1ub[i] = EMPTY_VALUE;
       shadowa[i]   = EMPTY_VALUE;
       shadowb[i]   = EMPTY_VALUE;
       double hi = mom[i]; double lo = mom[i];
          switch (LevelType)
          {
                case lvl_floa:                     
                {               
                    if (MinMaxPeriod>0)
                    {
                      hi = mom[ArrayMaximum(mom,MinMaxPeriod,i)];
                      lo = mom[ArrayMinimum(mom,MinMaxPeriod,i)];
                      hi = lo+(hi-lo)*LevelUp/100;
                      lo = lo+(hi-lo)*LevelDown/100;
                    }                     
                      levup[i] = hi;
                      levdn[i] = lo;
                      levmi[i] = (levup[i]+levdn[i])/2.0;
                      break;
                 }
                 default:                                                
                       levup[i] = iQuantile(mom[i],MinMaxPeriod, LevelUp               ,i,Bars);
                       levdn[i] = iQuantile(mom[i],MinMaxPeriod, LevelDown             ,i,Bars);
                       levmi[i] = iQuantile(mom[i],MinMaxPeriod,(LevelUp+LevelDown)*0.5,i,Bars);
                       break;
            }  
            switch(colorOn)
            {
               case cc_onLevels:         trend[i] = (mom[i]>levup[i]) ? 1 : (mom[i]<levdn[i]) ? -1 : 0; break;
               case cc_onMiddle:         trend[i] = (mom[i]>levmi[i]) ? 1 : (mom[i]<levmi[i]) ? -1 : 0; break;
               default :  if (i<Bars-1)  trend[i] = (mom[i]>mom[i+1]) ? 1 : (mom[i]<mom[i+1]) ? -1 : trend[i+1];
            }                  
            if (trend[i] == -1) { PlotPoint(i,buffer1da,buffer1db,mom); PlotPoint(i,shadowa,shadowb,mom); }
            if (trend[i] ==  1) { PlotPoint(i,buffer1ua,buffer1ub,mom); PlotPoint(i,shadowa,shadowb,mom); }             
   }      
return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

#define _prHABF(_prtype) (_prtype>=pr_habclose && _prtype<=pr_habtbiased2)
#define _priceInstances     1
#define _priceInstancesSize 4
double workHa[][_priceInstances*_priceInstancesSize];
double getPrice(int tprice, const double& open[], const double& close[], const double& high[], const double& low[], int i, int bars, int instanceNo=0)
{
  if (tprice>=pr_haclose)
   {
      if (ArrayRange(workHa,0)!= Bars) ArrayResize(workHa,Bars); instanceNo*=_priceInstancesSize; int r = bars-i-1;
         
         //
         //
         //
         //
         //
         
         double haOpen  = (r>0) ? (workHa[r-1][instanceNo+2] + workHa[r-1][instanceNo+3])/2.0 : (open[i]+close[i])/2;;
         double haClose = (open[i]+high[i]+low[i]+close[i]) / 4.0;
         if (_prHABF(tprice))
               if (high[i]!=low[i])
                     haClose = (open[i]+close[i])/2.0+(((close[i]-open[i])/(high[i]-low[i]))*MathAbs((close[i]-open[i])/2.0));
               else  haClose = (open[i]+close[i])/2.0; 
         double haHigh  = fmax(high[i], fmax(haOpen,haClose));
         double haLow   = fmin(low[i] , fmin(haOpen,haClose));

         //
         //
         //
         //
         //
         
         if(haOpen<haClose) { workHa[r][instanceNo+0] = haLow;  workHa[r][instanceNo+1] = haHigh; } 
         else               { workHa[r][instanceNo+0] = haHigh; workHa[r][instanceNo+1] = haLow;  } 
                              workHa[r][instanceNo+2] = haOpen;
                              workHa[r][instanceNo+3] = haClose;
         //
         //
         //
         //
         //
         
         switch (tprice)
         {
            case pr_haclose:
            case pr_habclose:    return(haClose);
            case pr_haopen:   
            case pr_habopen:     return(haOpen);
            case pr_hahigh: 
            case pr_habhigh:     return(haHigh);
            case pr_halow:    
            case pr_hablow:      return(haLow);
            case pr_hamedian:
            case pr_habmedian:   return((haHigh+haLow)/2.0);
            case pr_hamedianb:
            case pr_habmedianb:  return((haOpen+haClose)/2.0);
            case pr_hatypical:
            case pr_habtypical:  return((haHigh+haLow+haClose)/3.0);
            case pr_haweighted:
            case pr_habweighted: return((haHigh+haLow+haClose+haClose)/4.0);
            case pr_haaverage:  
            case pr_habaverage:  return((haHigh+haLow+haClose+haOpen)/4.0);
            case pr_hatbiased:
            case pr_habtbiased:
               if (haClose>haOpen)
                     return((haHigh+haClose)/2.0);
               else  return((haLow+haClose)/2.0);        
            case pr_hatbiased2:
            case pr_habtbiased2:
               if (haClose>haOpen)  return(haHigh);
               if (haClose<haOpen)  return(haLow);
                                    return(haClose);        
         }
   }
   
   //
   //
   //
   //
   //
   
   switch (tprice)
   {
      case pr_close:     return(close[i]);
      case pr_open:      return(open[i]);
      case pr_high:      return(high[i]);
      case pr_low:       return(low[i]);
      case pr_median:    return((high[i]+low[i])/2.0);
      case pr_medianb:   return((open[i]+close[i])/2.0);
      case pr_typical:   return((high[i]+low[i]+close[i])/3.0);
      case pr_weighted:  return((high[i]+low[i]+close[i]+close[i])/4.0);
      case pr_average:   return((high[i]+low[i]+close[i]+open[i])/4.0);
      case pr_tbiased:   
               if (close[i]>open[i])
                     return((high[i]+close[i])/2.0);
               else  return((low[i]+close[i])/2.0);        
      case pr_tbiased2:   
               if (close[i]>open[i]) return(high[i]);
               if (close[i]<open[i]) return(low[i]);
                                     return(close[i]);        
   }
   return(0);
}

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

#define _quantileInstances 1
double _sortQuant[];
double _workQuant[][_quantileInstances];

double iQuantile(double value, int period, double qp, int i, int bars, int instanceNo=0)
{
   if (period<1) return(value);
   if (ArrayRange(_workQuant,0)!=bars) ArrayResize(_workQuant,bars); 
   if (ArraySize(_sortQuant)!=period)  ArrayResize(_sortQuant,period); 
            i=bars-i-1; _workQuant[i][instanceNo]=value;
            int k=0; for (; k<period && (i-k)>=0; k++) _sortQuant[k] = _workQuant[i-k][instanceNo];
                     for (; k<period            ; k++) _sortQuant[k] = 0;
                     ArraySort(_sortQuant);

   //
   //
   //
   //
   //
   
   double index = (period-1.0)*qp/100.00;
   int    ind   = (int)index;
   double delta = index - ind;
   if (ind == NormalizeDouble(index,5))
         return(            _sortQuant[ind]);
   else  return((1.0-delta)*_sortQuant[ind]+delta*_sortQuant[ind+1]);
}   

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   if (i>=Bars-3) return;
   if ((second[i]  != EMPTY_VALUE) && (second[i+1] != EMPTY_VALUE))
        second[i+1] = EMPTY_VALUE;
   else
      if ((first[i] != EMPTY_VALUE) && (first[i+1] != EMPTY_VALUE) && (first[i+2] == EMPTY_VALUE))
          first[i+1] = EMPTY_VALUE;
}

void PlotPoint(int i,double& first[],double& second[],double& from[])
{
   if (i>=Bars-2) return;
   if (first[i+1] == EMPTY_VALUE)
      if (first[i+2] == EMPTY_VALUE) 
            { first[i]  = from[i]; first[i+1]  = from[i+1]; second[i] = EMPTY_VALUE; }
      else  { second[i] = from[i]; second[i+1] = from[i+1]; first[i]  = EMPTY_VALUE; }
   else     { first[i]  = from[i];                          second[i] = EMPTY_VALUE; }
}
