//https://www.mql5.com/en/forum/179807/page321
//+------------------------------------------------------------------+
//|                                                      QQE new.mq4 |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_chart_window
#property indicator_buffers 4
#property indicator_buffers 4
#property indicator_color1  Red
#property indicator_color2  Blue
#property indicator_color3  Red
#property indicator_color4  Blue
#property indicator_width1  1
#property indicator_width2  1
#property indicator_width3  2
#property indicator_width4  2

//
//
//
//
//

#import "dynamicZone.dll"
   double dzBuy(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i );
   double dzSell(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i );
#import

//
//
//
//
//

extern string TimeFrame                    = "Current time frame";
extern double SF                           = 5;
extern double CfbPrice                     = 0;
extern double CfbDepth                     = 3;
extern double CfbNormLength                = 15;
extern double CfbSmooth                    = 8;
extern double CfbSmoothLength              = 5;
extern double CfbSmoothPhase               = 0.0;
extern bool   CfbSmoothDouble              = false;
extern int    ShortLimit                   = 10;
extern int    LongLimit                    = 30;
extern double RsiPrice                     = 0;
extern string _rsimethods                  = "0=Rsi,1=Wilders,2=Rsx,3=Cuttler";
extern int    RsiMethod                    = 2;
extern double WP                           = 4.236;
extern int    DzLookBackBars               = 35;
extern double DzBuyProbability             = 0.20;
extern double DzSellProbability            = 0.20;
extern bool   ColorsOnOuterZones           = true;
extern bool   Interpolate                  = true;

extern string _                            = "Alerts Settings";
extern bool   alertsOn                     = false;
extern bool   alertsOnZeroCross            = false;
extern bool   alertsOnLowerLevelCross      = false;
extern bool   alertsOnUpperLevelCross      = false;
extern bool   alertsOnRsiMaCross           = false;
extern bool   alertsOnCurrent              = false;
extern bool   alertsMessage                = false;
extern bool   alertsSound                  = false;
extern bool   alertsEmail                  = false;

extern bool   arrowsVisible                = false;
extern string arrowsIdentifier             = "QqeCfbAdaptArrows1";
extern double arrowsDisplacement           = 1.0;

extern bool   arrowsOnZeroCross            = false;
extern color  arrowsUpZeroCrossColor       = Aqua;
extern color  arrowsDnZeroCrossColor       = Yellow;
extern int    arrowsUpZeroCrossCode        = 233;
extern int    arrowsDnZeroCrossCode        = 234;
extern int    arrowsUpZeroCrossSize        = 1;
extern int    arrowsDnZeroCrossSize        = 1;

extern bool   arrowsOnLowerLevelCross      = false;
extern color  arrowsLowerLevelCrossUpColor = Aqua;
extern color  arrowsLowerLevelCrossDnColor = Yellow;
extern int    arrowsLowerLevelCrossUpCode  = 119;
extern int    arrowsLowerLevelCrossDnCode  = 119;
extern int    arrowsLowerLevelCrossUpSize  = 1;
extern int    arrowsLowerLevelCrossDnSize  = 1;

extern bool   arrowsOnUpperLevelCross      = false;
extern color  arrowsUpperLevelCrossUpColor = Aqua;
extern color  arrowsUpperLevelCrossDnColor = Yellow;
extern int    arrowsUpperLevelCrossUpCode  = 119;
extern int    arrowsUpperLevelCrossDnCode  = 119;
extern int    arrowsUpperLevelCrossUpSize  = 1;
extern int    arrowsUpperLevelCrossDnSize  = 1;

extern bool   arrowsOnRsiMaCross           = false;
extern color  arrowsUpRsiMaCrossColor      = Aqua;
extern color  arrowsDnRsiMaCrossColor      = Yellow;
extern int    arrowsUpRsiMaCrossCode       = 119;
extern int    arrowsDnRsiMaCrossCode       = 119;
extern int    arrowsUpRsiMaCrossSize       = 2;
extern int    arrowsDnRsiMaCrossSize       = 2;

//
//
//
//
//

double RsiMa[];
double Trend[];
double trendhu[];
double trendhd[];
double trendhbu[];
double trendhbd[];
double bli[];
double sli[];

double trends[][4];
#define _tmi1 0
#define _tup1 1
#define _tdn1 2
#define _ttr1 3

//
//
//
//
//

string indicatorFileName;
int    timeFrame;
bool   returnBars;
bool   calculateValue;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(8);
   SetIndexBuffer(0,trendhu);  SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexBuffer(1,trendhd);  SetIndexStyle(1,DRAW_HISTOGRAM);
   SetIndexBuffer(2,trendhbu); SetIndexStyle(2,DRAW_HISTOGRAM);
   SetIndexBuffer(3,trendhbd); SetIndexStyle(3,DRAW_HISTOGRAM);
   SetIndexBuffer(4,RsiMa);    SetIndexLabel(4, "QQE");
   SetIndexBuffer(5,Trend);    SetIndexLabel(5, "QQE trend");                               
   SetIndexBuffer(6,bli);
   SetIndexBuffer(7,sli);
   SetLevelValue(0,0);
      
      //
      //
      //
      //
      //
      
      indicatorFileName = WindowExpertName();
      calculateValue    = (TimeFrame=="calculateValue"); if (calculateValue) return(0);
      returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
      timeFrame         = stringToTimeFrame(TimeFrame);
         CfbDepth = MathMax(MathMin(CfbDepth,7),1)+7;
      
      //
      //
      //
      //
      //
      
      IndicatorShortName(timeFrameToString(timeFrame)+" QqeCfb "+getRsiName(RsiMethod)+"");
return(0);
}

//
//
//
//
//

int deinit() 
{  
   if (!calculateValue && arrowsVisible) deleteArrows();
    
return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double work[][6];
#define iEma 0
#define iEmm 1
#define iQqe 2
#define iRsi 3
#define tQqe 4
#define tCfb 5

//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
   int i,r,limit;
   
   if(counted_bars < 0) return(-1);
   if(counted_bars > 0) counted_bars--;
           limit = MathMin(Bars-counted_bars,Bars-1);
           if (returnBars) { trendhu[0] = limit+1; return(0); }
           
   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame==Period())
   {
     if (ArrayRange(work,0) != Bars) ArrayResize(work,Bars); 
     if (ArrayRange(trends,0)!=Bars) ArrayResize(trends,Bars); 
     for (i=limit, r=Bars-i-1; i>=0; i--,r++)
     { 
         work[r][tCfb] = iDSmooth(iCfb(getPrice(CfbPrice,i),CfbDepth,CfbSmooth,i),CfbSmoothLength,CfbSmoothPhase,CfbSmoothDouble,i);
    
         //
         //
         //
         //
         //
         
         double max = work[r][tCfb];
         double min = work[r][tCfb];
         for (int k = 1; k<CfbNormLength && (r-k)>=0; k++)
         {
            max = MathMax(work[r-k][tCfb],max);
            min = MathMin(work[r-k][tCfb],min);
         }
         double denominator = max-min;
         if (denominator> 0)
               double ratio = (work[r][tCfb]-min)/denominator;
         else         ratio = 0.5;  
         double RSIPeriod = MathCeil(ShortLimit+ratio*(LongLimit-ShortLimit)); 
         double alpha1    = 2.0/(SF+1.0);
         double alpha2    = 2.0/(RSIPeriod*2.0);  
      
      //
      //
      //
      //
      //
      
      work[r][iRsi] = work[r-1][iRsi] + alpha1*(iRsx(getPrice(RsiPrice,i),RSIPeriod,i,0,RsiMethod)- work[r-1][iRsi]);
      work[r][iEma] = work[r-1][iEma] + alpha2*(MathAbs(work[r-1][iRsi]-work[r][iRsi]) - work[r-1][iEma]);
      work[r][iEmm] = work[r-1][iEmm] + alpha2*(work[r][iEma] - work[r-1][iEmm]);

      //
      //
      //
      //
      //

         double rsi0 = work[r  ][iRsi];
         double rsi1 = work[r-1][iRsi];
         double dar  = work[r  ][iEmm]*WP;
         double tr   = work[r-1][iQqe];
         double dv   = tr;
   
            if (rsi0 < tr) { tr = rsi0 + dar; if ((rsi1 < dv) && (tr > dv)) tr = dv; }
            if (rsi0 > tr) { tr = rsi0 - dar; if ((rsi1 > dv) && (tr < dv)) tr = dv; }
         
      //
      //
      //
      //
      //
         
         work[r][iQqe] = tr;
         work[r][tQqe] = work[r-1][tQqe];
         RsiMa[i]      = work[r][iRsi]-50;
         Trend[i]      = tr           -50;
         if (DzBuyProbability >0) bli[i] =  dzBuy(RsiMa,DzBuyProbability, DzLookBackBars,Bars,i);
         if (DzSellProbability>0) sli[i] = dzSell(RsiMa,DzSellProbability,DzLookBackBars,Bars,i);
         trendhu[i]  = EMPTY_VALUE;
         trendhd[i]  = EMPTY_VALUE;
         trendhbu[i] = EMPTY_VALUE;
         trendhbd[i] = EMPTY_VALUE;
         
         if (ColorsOnOuterZones)
         {
            if (RsiMa[i] < bli[i])                        work[r][tQqe] = 1;
            if (RsiMa[i] > sli[i])                        work[r][tQqe] =-1;
            if (RsiMa[i] <= sli[i] && RsiMa[i] >= bli[i]) work[r][tQqe] = 0;
         }
         else
         {
            if (RsiMa[i] < bli[i])                        work[r][tQqe] = 0;
            if (RsiMa[i] > sli[i])                        work[r][tQqe] = 0;
            if (RsiMa[i] <= sli[i] && RsiMa[i] >= bli[i]) work[r][tQqe] = 1;
         }
                     
         if (work[r][tQqe] == 1)
            { 
              trendhu[i]  = High[i];  trendhd[i] = Low[i]; 
              trendhbu[i] = MathMax(Open[i],Close[i]);
              trendhbd[i] = MathMin(Open[i],Close[i]);
            }
         if (work[r][tQqe] ==-1)
            {
              trendhd[i]  = High[i];  trendhu[i] = Low[i]; 
              trendhbu[i] = MathMin(Open[i],Close[i]);
              trendhbd[i] = MathMax(Open[i],Close[i]);
            }
         setTrends(i,r);
         manageArrow(i,r); 
         
     }    
     manageAlerts();   
     return(0);
     }
     
     //
     //
     //
     //
     //
     
     limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period())); 
     if (ArrayRange(trends,0)!=Bars) ArrayResize(trends,Bars); 
     if (ArrayRange(work,0) != Bars) ArrayResize(work,Bars); 
     for (i=limit, r=Bars-i-1; i>=0; i--,r++)
     { 
    
        int y = iBarShift(NULL,timeFrame,Time[i]);
           RsiMa[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",SF,CfbPrice,CfbDepth,CfbNormLength,CfbSmooth,CfbSmoothLength,CfbSmoothPhase,CfbSmoothDouble,ShortLimit,LongLimit,RsiPrice,"",RsiMethod,WP,DzLookBackBars,DzBuyProbability,DzSellProbability,ColorsOnOuterZones,4,y);
           Trend[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",SF,CfbPrice,CfbDepth,CfbNormLength,CfbSmooth,CfbSmoothLength,CfbSmoothPhase,CfbSmoothDouble,ShortLimit,LongLimit,RsiPrice,"",RsiMethod,WP,DzLookBackBars,DzBuyProbability,DzSellProbability,ColorsOnOuterZones,5,y);
           bli[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",SF,CfbPrice,CfbDepth,CfbNormLength,CfbSmooth,CfbSmoothLength,CfbSmoothPhase,CfbSmoothDouble,ShortLimit,LongLimit,RsiPrice,"",RsiMethod,WP,DzLookBackBars,DzBuyProbability,DzSellProbability,ColorsOnOuterZones,6,y);
           sli[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",SF,CfbPrice,CfbDepth,CfbNormLength,CfbSmooth,CfbSmoothLength,CfbSmoothPhase,CfbSmoothDouble,ShortLimit,LongLimit,RsiPrice,"",RsiMethod,WP,DzLookBackBars,DzBuyProbability,DzSellProbability,ColorsOnOuterZones,7,y);
               if (ColorsOnOuterZones)
               {
                  if (RsiMa[i] < bli[i])                        work[r][tQqe] = 1;
                  if (RsiMa[i] > sli[i])                        work[r][tQqe] =-1;
                  if (RsiMa[i] <= sli[i] && RsiMa[i] >= bli[i]) work[r][tQqe] = 0;
               }
               else
               {
                  if (RsiMa[i] < bli[i])                        work[r][tQqe] = 0;
                  if (RsiMa[i] > sli[i])                        work[r][tQqe] = 0;
                  if (RsiMa[i] <= sli[i] && RsiMa[i] >= bli[i]) work[r][tQqe] = 1;
               }                  
               if (work[r][tQqe] == 1)
               { 
                 trendhu[i]  = High[i];  trendhd[i] = Low[i]; 
                 trendhbu[i] = MathMax(Open[i],Close[i]);
                 trendhbd[i] = MathMin(Open[i],Close[i]);
               }
               if (work[r][tQqe] ==-1)
               {
                 trendhd[i]  = High[i];  trendhu[i] = Low[i]; 
                 trendhbu[i] = MathMin(Open[i],Close[i]);
                 trendhbd[i] = MathMax(Open[i],Close[i]);
               }
               setTrends(i,r);
               manageArrow(i,r);
      }
      manageAlerts();
return(0);
} 

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

//
//
//
//
//

int stringToTimeFrame(string tfs)
{
   tfs = stringUpperCase(tfs);
   for (int i=ArraySize(iTfTable)-1; i>=0; i--)
         if (tfs==sTfTable[i] || tfs==""+iTfTable[i]) return(MathMax(iTfTable[i],Period()));
                                                      return(Period());
}

//
//
//
//
//

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}

//
//
//
//
//

string stringUpperCase(string str)
{
   string   s = str;

   for (int length=StringLen(str)-1; length>=0; length--)
   {
      int char = StringGetChar(s, length);
         if((char > 96 && char < 123) || (char > 223 && char < 256))
                     s = StringSetChar(s, length, char - 32);
         else if(char > -33 && char < 0)
                     s = StringSetChar(s, length, char + 224);
   }
   return(s);
}

//
//
//
//
//

void setTrends(int i, int r)
{
   trends[r][_tmi1] = trends[r-1][_tmi1];
   trends[r][_tup1] = trends[r-1][_tup1];
   trends[r][_tdn1] = trends[r-1][_tdn1];
   trends[r][_ttr1] = trends[r-1][_ttr1];
   
      if (RsiMa[i] > 0)        trends[r][_tmi1] =  1;
      if (RsiMa[i] < 0)        trends[r][_tmi1] = -1;
      if (RsiMa[i] > bli[i])   trends[r][_tup1] =  1;
      if (RsiMa[i] < bli[i])   trends[r][_tup1] = -1;
      if (RsiMa[i] > sli[i])   trends[r][_tdn1] =  1;
      if (RsiMa[i] < sli[i])   trends[r][_tdn1] = -1;
      if (RsiMa[i] > Trend[i]) trends[r][_ttr1] =  1;
      if (RsiMa[i] < Trend[i]) trends[r][_ttr1] = -1;
      
}

//
//
//
//
//

void manageAlerts()
{
   if (!calculateValue && alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar)); 
                             whichBar = Bars-whichBar-1;

      //
      //
      //
      //
      //
            
      static datetime time1 = 0;
      static string   mess1 = "";
      if (alertsOnZeroCross && trends[whichBar][_tmi1] != trends[whichBar-1][_tmi1])
      {
         if (trends[whichBar][_tmi1] ==  1) doAlert(time1,mess1,whichBar,"Cross zero line up");
         if (trends[whichBar][_tmi1] == -1) doAlert(time1,mess1,whichBar,"Cross zero line down");
      }
      
      static datetime time2 = 0;
      static string   mess2 = "";
      if (alertsOnLowerLevelCross && trends[whichBar][_tup1] != trends[whichBar-1][_tup1])
      {
         if (trends[whichBar][_tup1] ==  1) doAlert(time2,mess2,whichBar,"Cross Lower Level up");
         if (trends[whichBar][_tup1] == -1) doAlert(time2,mess2,whichBar,"Cross Lower Level down");
      }
      static datetime time3 = 0;
      static string   mess3 = "";
      if (alertsOnUpperLevelCross && trends[whichBar][_tdn1] != trends[whichBar-1][_tdn1])
      {
         if (trends[whichBar][_tdn1] ==  1) doAlert(time3,mess3,whichBar,"Cross Upper Level up");
         if (trends[whichBar][_tdn1] == -1) doAlert(time3,mess3,whichBar,"Cross Upper Level down");
      }
      
      static datetime time4 = 0;
      static string   mess4 = "";
      if (alertsOnRsiMaCross && trends[whichBar][_ttr1] != trends[whichBar-1][_ttr1])
      {
         if (trends[whichBar][_ttr1] ==  1) doAlert(time4,mess4,whichBar,"RsiMa cross up");
         if (trends[whichBar][_ttr1] == -1) doAlert(time4,mess4,whichBar,"RsiMa cross down");
      }
      
   }
}

//
//
//
//
//

void doAlert(datetime& previousTime, string& previousAlert, int forBar, string doWhat)
{
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[forBar]) {
       previousAlert  = doWhat;
       previousTime   = Time[forBar];

       //
       //
       //
       //
       //

       message =  StringConcatenate(Symbol()," ",timeFrameToString(timeFrame)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," Dz QQE ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," Dz QQE "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void manageArrow(int i, int r)
{
   if (!calculateValue && arrowsVisible)
   {
      deleteArrow(arrowsIdentifier+":1a"+Time[i]);
      deleteArrow(arrowsIdentifier+":2a"+Time[i]);
      deleteArrow(arrowsIdentifier+":3a"+Time[i]);
      deleteArrow(arrowsIdentifier+":4a"+Time[i]);
      
      if (arrowsOnZeroCross && trends[r][_tmi1]!=trends[r-1][_tmi1])
      {
         if (trends[r][_tmi1] == 1) drawArrow("1a",i,arrowsUpZeroCrossColor,arrowsUpZeroCrossCode,arrowsUpZeroCrossSize,false);
         if (trends[r][_tmi1] ==-1) drawArrow("1a",i,arrowsDnZeroCrossColor,arrowsDnZeroCrossCode,arrowsDnZeroCrossSize,true);
      }
      
      if (arrowsOnLowerLevelCross && trends[r][_tup1]!=trends[r-1][_tup1])
      {
         if (trends[r][_tup1] == 1) drawArrow("2a",i,arrowsLowerLevelCrossUpColor,arrowsLowerLevelCrossUpCode,arrowsLowerLevelCrossUpSize,false);
         if (trends[r][_tup1] ==-1) drawArrow("2a",i,arrowsLowerLevelCrossDnColor,arrowsLowerLevelCrossDnCode,arrowsLowerLevelCrossDnSize,true);
      }
      if (arrowsOnUpperLevelCross && trends[r][_tdn1]!=trends[r-1][_tdn1])
      {
         if (trends[r][_tdn1] == 1) drawArrow("3a",i,arrowsUpperLevelCrossUpColor,arrowsUpperLevelCrossUpCode,arrowsUpperLevelCrossUpSize,false);
         if (trends[r][_tdn1] ==-1) drawArrow("3a",i,arrowsUpperLevelCrossDnColor,arrowsUpperLevelCrossDnCode,arrowsUpperLevelCrossDnSize,true);
      }
      
      if (arrowsOnRsiMaCross && trends[r][_ttr1]!=trends[r-1][_ttr1])
      {
         if (trends[r][_ttr1] == 1) drawArrow("4a",i,arrowsUpRsiMaCrossColor,arrowsUpRsiMaCrossCode,arrowsUpRsiMaCrossSize,false);
         if (trends[r][_ttr1] ==-1) drawArrow("4a",i,arrowsDnRsiMaCrossColor,arrowsDnRsiMaCrossCode,arrowsDnRsiMaCrossSize,true);
      }
   }
}               

//
//
//
//
//

void drawArrow(string add, int i,color theColor,int theCode,int theSize, bool up)
{
   string name = arrowsIdentifier+":"+add+Time[i];
   double gap  = iATR(NULL,0,20,i);   
   
      //
      //
      //
      //
      //
      
      ObjectCreate(name,OBJ_ARROW,0,Time[i],0);
         ObjectSet(name,OBJPROP_ARROWCODE,theCode);
         ObjectSet(name,OBJPROP_COLOR,   theColor);
         ObjectSet(name,OBJPROP_WIDTH,    theSize);      
         
         if (up)
               ObjectSet(name,OBJPROP_PRICE1,High[i] + arrowsDisplacement * gap);
         else  ObjectSet(name,OBJPROP_PRICE1, Low[i] - arrowsDisplacement * gap);
}

//
//
//
//
//

void deleteArrows()
{
   string lookFor       = arrowsIdentifier+":";
   int    lookForLength = StringLen(lookFor);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
}

//
//
//
//
//

void deleteArrow(datetime time)
{
   string lookFor = arrowsIdentifier+":"+time; ObjectDelete(lookFor);
}



//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//
//

double getPrice(int type, int i)
{
   switch (type)
   {
      case 7:     return((Open[i]+Close[i])/2.0);
      case 8:     return((Open[i]+High[i]+Low[i]+Close[i])/4.0);
      default :   return(iMA(NULL,0,1,0,MODE_SMA,type,i));
   }      
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int    Depths[] = {2,3,4,6,8,12,16,24,32,48,64,96,128,192};
double workCfb[][28];

//
//
//
//
//

double iCfb(double price, int depth, int smooth, int r)
{
   if (ArrayRange(workCfb,0) != Bars) ArrayResize(workCfb,Bars);
   int i = Bars-r-1;
         
   //
   //
   //
   //
   //

   double suma     = 0;
   double sumb     = 0;
   double cfb      = 0;
   double evenCoef = 1;
   double oddCoef  = 1;
   double avg      = 0;
         
      if (i>=smooth)
         for (int k=depth-1; k>=0; k--)
         {
            workCfb[i][k]    = iCfbFunc(price,i,Depths[k],k);
            workCfb[i][k+14] = workCfb[i-1][k+14] + (workCfb[i][k]-workCfb[i-smooth][k])/smooth;

                  if ((k%2)==0)
                        { avg = oddCoef  * workCfb[i][k+14]; oddCoef  = oddCoef  * (1 - avg); }
                  else  { avg = evenCoef * workCfb[i][k+14]; evenCoef = evenCoef * (1 - avg); }
               
               suma += avg*avg*Depths[k];
               sumb += avg;
         }
      else for (k=depth-1; k>=0; k--) { workCfb[i][k] = 0; workCfb[i][k+14] = 0; }            

   //
   //
   //
   //
   //

   if (sumb != 0) cfb = suma/sumb;
   return(cfb);
}

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

double  workCfbFunc[][70];
#define _prices 0
#define _roc    1
#define _value1 2
#define _value2 3
#define _value3 4

//
//
//
//

double iCfbFunc(double price, int r, int depth, int k)
{
   k *= 5;
      if (ArrayRange(workCfbFunc,0) != Bars) ArrayResize(workCfbFunc,Bars);
      if (r<=(depth+1))
      {
         workCfbFunc[r][k+_prices] = 0;
         workCfbFunc[r][k+_roc]    = 0;
         workCfbFunc[r][k+_value1] = 0;
         workCfbFunc[r][k+_value2] = 0;
         workCfbFunc[r][k+_value3] = 0;
         return(0);
      }         
      workCfbFunc[r][k+_prices] = price; 

   //
   //
   //
   //
   //

      workCfbFunc[r][k+_roc]    = MathAbs(workCfbFunc[r][k+_prices] - workCfbFunc[r-1][k+_prices]);
      workCfbFunc[r][k+_value1] = workCfbFunc[r-1][k+_value1] - workCfbFunc[r-depth][k+_roc] + workCfbFunc[r][k+_roc];
      workCfbFunc[r][k+_value2] = workCfbFunc[r-1][k+_value2] - workCfbFunc[r-1][k+_value1] + workCfbFunc[r][k+_roc]*depth;
      workCfbFunc[r][k+_value3] = workCfbFunc[r-1][k+_value3] - workCfbFunc[r-1-depth][k+_prices] + workCfbFunc[r-1][k+_prices];
   
      double dividend = MathAbs(depth*workCfbFunc[r][k+_prices]-workCfbFunc[r][k+_value3]);

      //
      //
      //
      //
      //
         
   if (workCfbFunc[r][k+_value2] != 0)
         return( dividend / workCfbFunc[r][k+_value2]);
   else  return(0.00);            
}

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//
//

string rsiMethodNames[] = {"Rsi","Wilders","Rsx","Cuttler"};
string getRsiName(int& method)
{
   int max = ArraySize(rsiMethodNames)-1;
      method=MathMax(MathMin(method,max),0); return(rsiMethodNames[method]);
}

//
//
//
//
//

double workRsi[][13];
#define _price  0
#define _change 1
#define _changa 2

double iRsx(double price, double period, int i, int instanceNo=0, int rsiMode=0)
{
   if (ArrayRange(workRsi,0)!=Bars) ArrayResize(workRsi,Bars);
      int z = instanceNo*13; 
      int r = Bars-i-1;
   
   //
   //
   //
   //
   //
   
   workRsi[r][z+_price] = price;
   switch (rsiMode)
   {
      case 0:
         double alpha = 1.0/period; 
         if (r<period)
            {
               int k; double sum = 0; for (k=0; k<period && (r-k-1)>=0; k++) sum += MathAbs(workRsi[r-k][z+_price]-workRsi[r-k-1][z+_price]);
                  workRsi[r][z+_change] = (workRsi[r][z+_price]-workRsi[0][z+_price])/MathMax(k,1);
                  workRsi[r][z+_changa] =                                         sum/MathMax(k,1);
            }
         else
            {
               double change = workRsi[r][z+_price]-workRsi[r-1][z+_price];
                               workRsi[r][z+_change] = workRsi[r-1][z+_change] + alpha*(        change  - workRsi[r-1][z+_change]);
                               workRsi[r][z+_changa] = workRsi[r-1][z+_changa] + alpha*(MathAbs(change) - workRsi[r-1][z+_changa]);
            }
         if (workRsi[r][z+_changa] != 0)
               return(50.0*(workRsi[r][z+_change]/workRsi[r][z+_changa]+1));
         else  return(50.0);
         
      //
      //
      //
      //
      //
      
      case 1 :
         workRsi[r][z+1] = iSmma(0.5*(MathAbs(workRsi[r][z+_price]-workRsi[r-1][z+_price])+(workRsi[r][z+_price]-workRsi[r-1][z+_price])),0.5*(period-1),Bars-i-1,0);
         workRsi[r][z+2] = iSmma(0.5*(MathAbs(workRsi[r][z+_price]-workRsi[r-1][z+_price])-(workRsi[r][z+_price]-workRsi[r-1][z+_price])),0.5*(period-1),Bars-i-1,1);
         if((workRsi[r][z+1] + workRsi[r][z+2]) != 0) 
               return(100.0 * workRsi[r][z+1]/(workRsi[r][z+1] + workRsi[r][z+2]));
         else  return(50);

      //
      //
      //
      //
      //

      case 2 :     
         double Kg = (3.0)/(2.0+period), Hg = 1.0-Kg;
         if (r<period) { for (k=1; k<13; k++) workRsi[r][k+z] = 0; return(50); }  

         //
         //
         //
         //
         //
      
         double mom = workRsi[r][_price+z]-workRsi[r-1][_price+z];
         double moa = MathAbs(mom);
         for (k=0; k<3; k++)
         {
            int kk = k*2;
            workRsi[r][z+kk+1] = Kg*mom                + Hg*workRsi[r-1][z+kk+1];
            workRsi[r][z+kk+2] = Kg*workRsi[r][z+kk+1] + Hg*workRsi[r-1][z+kk+2]; mom = 1.5*workRsi[r][z+kk+1] - 0.5 * workRsi[r][z+kk+2];
            workRsi[r][z+kk+7] = Kg*moa                + Hg*workRsi[r-1][z+kk+7];
            workRsi[r][z+kk+8] = Kg*workRsi[r][z+kk+7] + Hg*workRsi[r-1][z+kk+8]; moa = 1.5*workRsi[r][z+kk+7] - 0.5 * workRsi[r][z+kk+8];
         }
         if (moa != 0)
              return(MathMax(MathMin((mom/moa+1.0)*50.0,100.00),0.00)); 
         else return(50);
            
      //
      //
      //
      //
      //
      
      case 3 :
         double sump = 0;
         double sumn = 0;
         for (k=0; k<period; k++)
         {
            double diff = workRsi[r-k][z+_price]-workRsi[r-k-1][z+_price];
               if (diff > 0) sump += diff;
               if (diff < 0) sumn -= diff;
         }
         if (sumn > 0)
               return(100.0-100.0/(1.0+sump/sumn));
         else  return(50);
   } 
}

//
//
//
//
//
//

double workSmma[][2];
double iSmma(double price, double period, int r, int instanceNo=0)
{
   if (ArrayRange(workSmma,0)!= Bars) ArrayResize(workSmma,Bars);

   //
   //
   //
   //
   //

   if (r<period)
         workSmma[r][instanceNo] = price;
   else  workSmma[r][instanceNo] = workSmma[r-1][instanceNo]+(price-workSmma[r-1][instanceNo])/period;
   return(workSmma[r][instanceNo]);
}


//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

double wrk[][20];

#define bsmax  5
#define bsmin  6
#define volty  7
#define vsum   8
#define avolty 9

//
//
//
//
//

double iDSmooth(double price, double length, double phase, bool isDouble, int i, int s=0)
{
   if (isDouble)
         return (iSmooth(iSmooth(price,MathSqrt(length),phase,i,s),MathSqrt(length),phase,i,s+10));
   else  return (iSmooth(price,length,phase,i,s));
}

//
//
//
//
//

double iSmooth(double price, double length, double phase, int i, int s=0)
{
   if (length <=1) return(price);
   if (ArrayRange(wrk,0) != Bars) ArrayResize(wrk,Bars);
   
   int r = Bars-i-1; 
      if (r==0) { for(int k=0; k<7; k++) wrk[r][k+s]=price; for(; k<10; k++) wrk[r][k+s]=0; return(price); }

   //
   //
   //
   //
   //
   
      double len1   = MathMax(MathLog(MathSqrt(0.5*(length-1)))/MathLog(2.0)+2.0,0);
      double pow1   = MathMax(len1-2.0,0.5);
      double del1   = price - wrk[r-1][bsmax+s];
      double del2   = price - wrk[r-1][bsmin+s];
      double div    = 1.0/(10.0+10.0*(MathMin(MathMax(length-10,0),100))/100);
      int    forBar = MathMin(r,10);
	
         wrk[r][volty+s] = 0;
               if(MathAbs(del1) > MathAbs(del2)) wrk[r][volty+s] = MathAbs(del1); 
               if(MathAbs(del1) < MathAbs(del2)) wrk[r][volty+s] = MathAbs(del2); 
         wrk[r][vsum+s] =	wrk[r-1][vsum+s] + (wrk[r][volty+s]-wrk[r-forBar][volty+s])*div;
         
         //
         //
         //
         //
         //
   
         wrk[r][avolty+s] = wrk[r-1][avolty+s]+(2.0/(MathMax(4.0*length,30)+1.0))*(wrk[r][vsum+s]-wrk[r-1][avolty+s]);
            if (wrk[r][avolty+s] > 0)
               double dVolty = wrk[r][volty+s]/wrk[r][avolty+s]; else dVolty = 0;   
	               if (dVolty > MathPow(len1,1.0/pow1)) dVolty = MathPow(len1,1.0/pow1);
                  if (dVolty < 1)                      dVolty = 1.0;

      //
      //
      //
      //
      //
	        
   	double pow2 = MathPow(dVolty, pow1);
      double len2 = MathSqrt(0.5*(length-1))*len1;
      double Kv   = MathPow(len2/(len2+1), MathSqrt(pow2));

         if (del1 > 0) wrk[r][bsmax+s] = price; else wrk[r][bsmax+s] = price - Kv*del1;
         if (del2 < 0) wrk[r][bsmin+s] = price; else wrk[r][bsmin+s] = price - Kv*del2;
	
   //
   //
   //
   //
   //
      
      double R     = MathMax(MathMin(phase,100),-100)/100.0 + 1.5;
      double beta  = 0.45*(length-1)/(0.45*(length-1)+2);
      double alpha = MathPow(beta,pow2);

         wrk[r][0+s] = price + alpha*(wrk[r-1][0+s]-price);
         wrk[r][1+s] = (price - wrk[r][0+s])*(1-beta) + beta*wrk[r-1][1+s];
         wrk[r][2+s] = (wrk[r][0+s] + R*wrk[r][1+s]);
         wrk[r][3+s] = (wrk[r][2+s] - wrk[r-1][4+s])*MathPow((1-alpha),2) + MathPow(alpha,2)*wrk[r-1][3+s];
         wrk[r][4+s] = (wrk[r-1][4+s] + wrk[r][3+s]); 

   //
   //
   //
   //
   //

   return(wrk[r][4+s]);
}