//+------------------------------------------------------------------+
//|                                                        dtosc.mq4 |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"


#property indicator_separate_window
#property indicator_buffers 5
#property indicator_minimum -30
#property indicator_maximum 130
#property indicator_color1  LimeGreen
#property indicator_color2  DeepPink
#property indicator_color3  DarkSlateGray
#property indicator_color4  DarkSlateGray
#property indicator_color5  DarkSlateGray
#property indicator_width1  2
#property indicator_style2  STYLE_DASHDOTDOT
#property indicator_style3  STYLE_DOT
#property indicator_style4  STYLE_DOT
#property indicator_style5  STYLE_DOT

//
//
//
//
//

extern string TimeFrame                     = "Current time frame";
extern int    RsiPrice                      = 8;
extern int    RsiPeriod                     = 10;
extern string _rsimethods                   = "0=rsi,1=wilder rsi,2=rsx2,3=cuttler rsi ";
extern int    RsiMethod                     = 0;
extern int    Depth                         = 2;    
extern double Speed                         = 0.05;    
extern double PeriodStoch                   = 10;
extern int    PeriodSK                      = 2;
extern int    PeriodSD                      = 2;
extern int    MAMode                        = 0;
extern double Phase                         = 0;
extern bool   Double                        = false;
extern int    MinMaxPeriod                  = 34;
extern double LevelUp                       = 90;
extern double LevelDn                       = 10;
extern int    LinearRegressionLength        = 150;
extern double LinearRegressionChannelWidth  = 2.0;
extern string IndicatorUniqueID             = "dtosc slope divergence";
extern color  ChartLineColor                = Gold;
extern int    ChartLineMiddleStyle          = STYLE_DOT;
extern int    ChartLineStyle                = STYLE_SOLID;
extern color  dtoscLineColor                = Gold;
extern int    dtoscLineMiddleStyle          = STYLE_DOT;
extern int    dtoscLineStyle                = STYLE_SOLID;
extern bool   Interpolate                   = true;
   
extern bool   alertsOn                      = true;
extern bool   alertsOnCurrent               = false;
extern bool   alertsMessage                 = true;
extern bool   alertsSound                   = false;
extern bool   alertsEmail                   = false;
   
extern bool   arrowsVisible                 = false;
extern string arrowsIdentifier              = "dtosc Arrows1";
extern double arrowsDisplacement            = 1.0;
extern color  arrowsUpColor                 = LimeGreen;
extern color  arrowsDnColor                 = Red;
extern int    arrowsUpCode                  = 241;
extern int    arrowsDnCode                  = 242;
   
   
//
//
//
//
//

double SK[];
double SD[];
double levelUp[];
double levelMi[];
double levelDn[];
double StoRSI[];
double RSI[];
double trend[];

//
//
//
//
//

string shortName;
string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(8);
      SetIndexBuffer(0,SK);
      SetIndexBuffer(1,SD);
      SetIndexBuffer(2,levelUp);
      SetIndexBuffer(3,levelMi);
      SetIndexBuffer(4,levelDn);
      SetIndexBuffer(5,StoRSI);
      SetIndexBuffer(6,RSI);
      SetIndexBuffer(7,trend);

      //
      //
      //
      //
      //
   
      indicatorFileName = WindowExpertName();
      returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
      calculateValue    = (TimeFrame=="calculateValue");
      if (calculateValue)
      {
         int s = StringFind(IndicatorUniqueID,":",0);
               shortName = IndicatorUniqueID;
               IndicatorUniqueID = StringSubstr(IndicatorUniqueID,0,s);
               return(0);
      }            
      timeFrame = stringToTimeFrame(TimeFrame);
      
   shortName = IndicatorUniqueID+": "+timeFrameToString(timeFrame)+"  smoothed Dtosc"+getRsiName(RsiMethod)+"  ("+RsiPeriod+","+DoubleToStr(PeriodStoch,2)+","+PeriodSK+","+PeriodSD+")";
   IndicatorShortName(shortName);
return(0);
}

//
//
//
//
//

int deinit()
{  
    for (int i=ObjectsTotal(); i>=0; i--)
    {
       string name = ObjectName(i); if (StringFind(name,IndicatorUniqueID)==0) ObjectDelete(name);
    }
    if (!calculateValue && arrowsVisible) deleteArrows();  
    
return(0); 
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

#define iPrc 3

int start()
{
   int i,limit;
   int counted_bars = IndicatorCounted();

   if(counted_bars < 0) return(-1);
   if(counted_bars > 0) counted_bars--;
             limit=MathMin(Bars-counted_bars,Bars-1);
             if (returnBars) { SK[0] = limit; return(0); }

   //
   //
   //
   //
   //

   if (calculateValue || timeFrame == Period())
   {
      for(i=limit; i>=0; i--)
      {
         RSI[i]    = iRsi(getPrice(RsiPrice,i),RsiPeriod,RsiMethod,i); 
         double lo = RSI[ArrayMinimum(RSI,PeriodStoch,i)];
         double hi = RSI[ArrayMaximum(RSI,PeriodStoch,i)];
         if (hi!=lo)
               StoRSI[i] = iDSmooth(100.0*(RSI[i] - lo)/(hi - lo),PeriodStoch,Phase,Double,i);
         else  StoRSI[i] = iDSmooth(0                            ,PeriodStoch,Phase,Double,i);      
      } 
        
      for(i=limit; i>=0; i--) SK[i] = iMAOnArray(StoRSI,0,PeriodSK,0,MAMode,i);
      
      for(i=limit; i>=0; i--)
      {
         SD[i] = iMAOnArray(SK,0,PeriodSD,0,MAMode,i);
         double skMin = SK[ArrayMinimum(SK,MinMaxPeriod,i)];
         double skMax = SK[ArrayMaximum(SK,MinMaxPeriod,i)];
         double range = skMax-skMin;
                  levelUp[i] = skMin+range*LevelDn/100.0;
                  levelMi[i] = skMin+range*0.5;
                  levelDn[i] = skMin+range*LevelUp/100.0;
         trend[i] = trend[i+1];
            if (SK[i] > SD[i] && SK[i] >= levelUp[i] && SK[i+1] < levelUp[i+1]) trend[i] =  1;
            if (SK[i] < SD[i] && SK[i] <= levelDn[i] && SK[i+1] > levelDn[i+1]) trend[i] = -1;
            fillLrArray(i,0,SK[i]);
            fillLrArray(i,1,getPrice(RsiPrice,i));
            manageArrow(i);
      } 
      double dtoscError; double dtoscSlope; double lrdtosc = iLrValue(SK[0],               LinearRegressionLength,dtoscSlope,dtoscError,0,0);
      double prcError;   double prcSlope;   double lrPrc   = iLrValue(getPrice(RsiPrice,0),LinearRegressionLength,prcSlope,  prcError,  0,1);
      int window = WindowFind(shortName);
      createLine(window,lrdtosc,lrdtosc-(LinearRegressionLength-1.0)*dtoscSlope,"dtoscLine",dtoscLineColor ,dtoscLineStyle ,dtoscLineMiddleStyle ,dtoscError*LinearRegressionChannelWidth);
      createLine(0     ,lrPrc,  lrPrc  -(LinearRegressionLength-1.0)*prcSlope,  "prcLine",  ChartLineColor, ChartLineStyle, ChartLineMiddleStyle, prcError  *LinearRegressionChannelWidth);
      manageAlerts();        
      return(0);      
   }
   
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   for(i=limit; i>=0; i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         SK[i]      = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPrice,RsiPeriod,"",RsiMethod,Depth,Speed,PeriodStoch,PeriodSK,PeriodSD,MAMode,Phase,Double,MinMaxPeriod,LevelUp,LevelDn,LinearRegressionLength,LinearRegressionChannelWidth,shortName,ChartLineColor,ChartLineMiddleStyle,ChartLineStyle,dtoscLineColor,dtoscLineMiddleStyle,dtoscLineStyle,0,y);
         SD[i]      = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPrice,RsiPeriod,"",RsiMethod,Depth,Speed,PeriodStoch,PeriodSK,PeriodSD,MAMode,Phase,Double,MinMaxPeriod,LevelUp,LevelDn,LinearRegressionLength,LinearRegressionChannelWidth,shortName,ChartLineColor,ChartLineMiddleStyle,ChartLineStyle,dtoscLineColor,dtoscLineMiddleStyle,dtoscLineStyle,1,y);
         levelUp[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPrice,RsiPeriod,"",RsiMethod,Depth,Speed,PeriodStoch,PeriodSK,PeriodSD,MAMode,Phase,Double,MinMaxPeriod,LevelUp,LevelDn,LinearRegressionLength,LinearRegressionChannelWidth,shortName,ChartLineColor,ChartLineMiddleStyle,ChartLineStyle,dtoscLineColor,dtoscLineMiddleStyle,dtoscLineStyle,2,y);
         levelMi[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPrice,RsiPeriod,"",RsiMethod,Depth,Speed,PeriodStoch,PeriodSK,PeriodSD,MAMode,Phase,Double,MinMaxPeriod,LevelUp,LevelDn,LinearRegressionLength,LinearRegressionChannelWidth,shortName,ChartLineColor,ChartLineMiddleStyle,ChartLineStyle,dtoscLineColor,dtoscLineMiddleStyle,dtoscLineStyle,3,y);
         levelDn[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPrice,RsiPeriod,"",RsiMethod,Depth,Speed,PeriodStoch,PeriodSK,PeriodSD,MAMode,Phase,Double,MinMaxPeriod,LevelUp,LevelDn,LinearRegressionLength,LinearRegressionChannelWidth,shortName,ChartLineColor,ChartLineMiddleStyle,ChartLineStyle,dtoscLineColor,dtoscLineMiddleStyle,dtoscLineStyle,4,y);
         trend[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPrice,RsiPeriod,"",RsiMethod,Depth,Speed,PeriodStoch,PeriodSK,PeriodSD,MAMode,Phase,Double,MinMaxPeriod,LevelUp,LevelDn,LinearRegressionLength,LinearRegressionChannelWidth,shortName,ChartLineColor,ChartLineMiddleStyle,ChartLineStyle,dtoscLineColor,dtoscLineMiddleStyle,dtoscLineStyle,7,y);
         
         manageArrow(i);
            
         //
         //
         //
         //
         //
      
         if (!Interpolate || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,timeFrame,y);
            for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
            for(int k = 1; k < n; k++)
            {
               SK[i+k]      = SK[i]      + (SK[i+n]      - SK[i])      * k/n;
               SD[i+k]      = SD[i]      + (SD[i+n]      - SD[i])      * k/n;
               levelUp[i+k] = levelUp[i] + (levelUp[i+n] - levelUp[i]) * k/n;
               levelMi[i+k] = levelMi[i] + (levelMi[i+n] - levelMi[i]) * k/n;
               levelDn[i+k] = levelDn[i] + (levelDn[i+n] - levelDn[i]) * k/n;
         
            }               
   }               

   manageAlerts();          
return(0);
}

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

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

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//
//

string rsiMethodNames[] = {"rsi","Wilders rsi","rsx2","Cuttler RSI"};
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 iRsi(double price, double period, int rsiMode, int i, int instanceNo=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,instanceNo*2+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,instanceNo*2+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<Depth; k++)
      {
         int kk = k*4;
            workRsi[r][kk+1] = Kg*mom                + Hg*workRsi[r-1][kk+1];
            workRsi[r][kk+2] = Kg*workRsi[r][kk+1] + Hg*workRsi[r-1][kk+2]; mom =         1.5*workRsi[r][kk+1] - Speed * workRsi[r][kk+2];
            workRsi[r][kk+3] = Kg*moa                + Hg*workRsi[r-1][kk+3];
            workRsi[r][kk+4] = Kg*workRsi[r][kk+3] + Hg*workRsi[r-1][kk+4]; moa = MathAbs(1.5*workRsi[r][kk+3] - Speed * workRsi[r][kk+4]);
      }
      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);
      }
      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]);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

void createLine(int window, double price1, double price2, string addName, color theColor, int theStyle, int theMiddleStyle, double error)
{
   string name = IndicatorUniqueID+addName+"mid";
      if (ObjectFind(name)==-1)
           ObjectCreate(name,OBJ_TREND,window,0,0,0,0);
              ObjectSet(name,OBJPROP_PRICE1,price1);
              ObjectSet(name,OBJPROP_PRICE2,price2);
              ObjectSet(name,OBJPROP_TIME1,Time[0]);
              ObjectSet(name,OBJPROP_TIME2,Time[LinearRegressionLength-1]);
              ObjectSet(name,OBJPROP_RAY,false);
              ObjectSet(name,OBJPROP_COLOR,theColor);
              ObjectSet(name,OBJPROP_STYLE,theMiddleStyle);
              
                  if (error<=0) return;
      name = IndicatorUniqueID+addName+"up";
      if (ObjectFind(name)==-1)
           ObjectCreate(name,OBJ_TREND,window,0,0,0,0);
              ObjectSet(name,OBJPROP_PRICE1,price1+error);
              ObjectSet(name,OBJPROP_PRICE2,price2+error);
              ObjectSet(name,OBJPROP_TIME1,Time[0]);
              ObjectSet(name,OBJPROP_TIME2,Time[LinearRegressionLength-1]);
              ObjectSet(name,OBJPROP_RAY,false);
              ObjectSet(name,OBJPROP_COLOR,theColor);
              ObjectSet(name,OBJPROP_STYLE,theStyle);
              
      name = IndicatorUniqueID+addName+"down";
      if (ObjectFind(name)==-1)
           ObjectCreate(name,OBJ_TREND,window,0,0,0,0);
              ObjectSet(name,OBJPROP_PRICE1,price1-error);
              ObjectSet(name,OBJPROP_PRICE2,price2-error);
              ObjectSet(name,OBJPROP_TIME1,Time[0]);
              ObjectSet(name,OBJPROP_TIME2,Time[LinearRegressionLength-1]);
              ObjectSet(name,OBJPROP_RAY,false);
              ObjectSet(name,OBJPROP_COLOR,theColor);
              ObjectSet(name,OBJPROP_STYLE,theStyle);
}

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

double workLr[][2];
void fillLrArray(int i, int instanceNo, double value)
{
   if (ArrayRange(workLr,0)!=Bars) ArrayResize(workLr,Bars); i = Bars-i-1; workLr[i][instanceNo] = value;
}
double iLrValue(double value, int period, double& slope, double& error, int r, int instanceNo=0)
{
   if (ArrayRange(workLr,0)!=Bars) ArrayResize(workLr,Bars); r = Bars-r-1; workLr[r][instanceNo] = value;
   if (r<period || period<2) return(value);

   //
   //
   //
   //
   //

      double sumx=0, sumxx=0, sumxy=0, sumy=0, sumyy=0;
         for (int k=0; k<period; k++)
         {
            double price = workLr[r-k][instanceNo];
                   sumx  += k;
                   sumxx += k*k;
                   sumxy += k*price;
                   sumy  +=   price;
                   sumyy +=   price*price;
         }
         slope = (period*sumxy-sumx*sumy)/(sumx*sumx-period*sumxx);
         error = MathSqrt((period*sumyy-sumy*sumy-slope*slope*(period*sumxx-sumx*sumx))/(period*(period-2)));

   //
   //
   //
   //
   //
         
   return((sumy + slope*sumx)/period);
}

//
//
//
//
//

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 tchar = StringGetChar(s, length);
         if((tchar > 96 && tchar < 123) || (tchar > 223 && tchar < 256))
                     s = StringSetChar(s, length, tchar - 32);
         else if(tchar > -33 && tchar < 0)
                     s = StringSetChar(s, length, tchar + 224);
   }
   return(s);
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void manageArrow(int i)
{
   if (arrowsVisible)
   {
      deleteArrow(Time[i]);
      if (trend[i]!=trend[i+1])
      {
         if (trend[i] == 1) drawArrow(i,arrowsUpColor,arrowsUpCode,false);
         if (trend[i] ==-1) drawArrow(i,arrowsDnColor,arrowsDnCode,true);
      }
   }
}               

//
//
//
//
//

//
//
//
//
//

void drawArrow(int i,color theColor,int theCode,bool up)
{
   string name = arrowsIdentifier+":"+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);
         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);
}


//+------------------------------------------------------------------
//|                                                                 
//+------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (!calculateValue && alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar));
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar]== 1) doAlert(whichBar,"sloping up");
         if (trend[whichBar]==-1) doAlert(whichBar,"sloping down");
      }         
   }
}

//
//
//
//
//

void doAlert(int forBar, string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
      if (previousAlert != doWhat || previousTime != Time[forBar]) {
          previousAlert  = doWhat;
          previousTime   = Time[forBar];

          //
          //
          //
          //
          //

          message =  StringConcatenate(Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," dtosc ",doWhat);
             if (alertsMessage) Alert(message);
             if (alertsEmail)   SendMail(StringConcatenate(Symbol()," dtosc "),message);
             if (alertsSound)   PlaySound("alert2.wav");
      }
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

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]);
}

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//


