//+------------------------------------------------------------------+
//|                                                        dtosc.mq4 |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"


#property indicator_separate_window
#property indicator_buffers    5
#property indicator_minimum    -5
#property indicator_maximum    105
#property indicator_color1     LimeGreen
#property indicator_color2     DarkOrange
#property indicator_color3     DeepSkyBlue
#property indicator_color4     PaleVioletRed
#property indicator_color5     DimGray
#property indicator_width1     2
#property indicator_style5     STYLE_DASH
#property indicator_levelcolor DarkSlateGray

//
//
//
//
//

#import "dynamicZone.dll"
   double dzBuyP(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i, double precision );
   double dzSellP(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i, double precision );
#import

//
//
//
//
//

extern string TimeFrame              = "Current time frame";
extern int    RsiPeriod              = 5;
extern string _rsiprice1             = "0=close,1=open,2=high,3=low,4=HL/2 ";
extern string _rsiprice2             = "5=HLC/3,6=HLCC/4,7=OC/2,8=HLOC/4 ";
extern int    RsiPrice               = 8;
extern string _rsimethods            = "0=rsi,1=wilder rsi,2=rsx,3=cuttler rsi";
extern int    RsiMethod              = 2;
extern int    PeriodStoch            = 5;
extern int    PeriodSK               = 5;
extern int    PeriodSD               = 3;
extern double PaFilter               = 1.0;
extern double PaCycles               = 2.0;
extern double DzStartBuyProbability  = 0.05;
extern double DzStartSellProbability = 0.05;
extern int    MAMode                 = 3;
extern double TMSmoothing            = 5;
extern double TMDamping              = 5;
extern double TMNoise                = 30;
extern int    levelOs                = 10;
extern int    levelOb                = 90;    
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          = true;
extern string arrowsIdentifier       = "dz-pa dtosc Arrows1";
extern double arrowsDisplacement     = 1.0;
extern color  arrowsUpColor          = DeepSkyBlue;
extern color  arrowsDnColor          = PaleVioletRed;
extern int    arrowsUpCode           = 241;
extern int    arrowsDnCode           = 242;
     
//
//
//
//
//

double SK[];
double SD[];
double bl1[];
double sl1[];
double zli[];
double StoRSI[];
double RSI[];
double trend[];

//
//
//
//
//

string IndicatorFileName;
int    timeFrame;
bool   returnBars;
bool   calculateValue;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(8);
      SetIndexBuffer(0,SK);
      SetIndexBuffer(1,SD);
      SetIndexBuffer(2,bl1);
      SetIndexBuffer(3,sl1);
      SetIndexBuffer(4,zli);
      SetIndexBuffer(5,StoRSI);
      SetIndexBuffer(6,RSI);
      SetIndexBuffer(7,trend);
      SetLevelValue(0,levelOs);
      SetLevelValue(1,levelOb);

   //
   //
   //
   //
   //
   
      IndicatorFileName = WindowExpertName();
      returnBars        = (TimeFrame == "returnBars");     if (returnBars)     return(0);
      calculateValue    = (TimeFrame == "calculateValue"); if (calculateValue) return(0);
      timeFrame         = stringToTimeFrame(TimeFrame);   

   //
   //
   //
   //
   //
   
   IndicatorShortName(timeFrameToString(timeFrame)+"  Dynamic Zone-pa TM Dtosc stoch"+getRsiName(RsiMethod)+"  ("+RsiPeriod+","+PeriodStoch+","+PeriodSK+","+PeriodSD+")");
   return(0);
}

//
//
//
//
//

int deinit(){  if (!calculateValue && arrowsVisible) deleteArrows();  return(0); }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

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,i,0,RsiMethod); 
         double lo = RSI[ArrayMinimum(RSI,PeriodStoch,i)];
         double hi = RSI[ArrayMaximum(RSI,PeriodStoch,i)];
         if (hi!=lo)
               StoRSI[i] = MathMax(MathMin(iTmSmooth(100.0*(RSI[i] - lo)/(hi - lo),TMDamping,TMNoise,TMSmoothing,i),100),0);
         else  StoRSI[i] = MathMax(MathMin(iTmSmooth(0                            ,TMDamping,TMNoise,TMSmoothing,i),100),0);      
      }   
      for(i=limit; i>=0; i--) SK[i] = iMAOnArray(StoRSI,0,PeriodSK,0,MAMode,i);
      for(i=limit; i>=0; i--)
      {
         double DzLookBackBars = iHilbertPhase(getPrice(RsiPrice,i),PaFilter,PaCycles,i); 
         SD[i]    = iMAOnArray(SK,0,PeriodSD,0,MAMode,i);
         bl1[i]   = dzBuyP (SK, DzStartBuyProbability,  DzLookBackBars, Bars, i,0.001);
         sl1[i]   = dzSellP(SK, DzStartSellProbability, DzLookBackBars, Bars, i,0.001);
         zli[i]   = dzSellP(SK, 0.5,                    DzLookBackBars, Bars, i,0.001);
         trend[i] = trend[i+1];
         
         if (SK[i] > SD[i]) trend[i] =  1;
         if (SK[i] < SD[i]) trend[i] = -1;
         if (!calculateValue) manageArrow(i);
      } 
      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",RsiPeriod,"","",RsiPrice,"",RsiMethod,PeriodStoch,PeriodSK,PeriodSD,PaFilter,PaCycles,DzStartBuyProbability,DzStartSellProbability,MAMode,TMSmoothing,TMDamping,TMNoise,0,y);
         SD[i]    = iCustom(NULL,timeFrame,IndicatorFileName,"calculateValue",RsiPeriod,"","",RsiPrice,"",RsiMethod,PeriodStoch,PeriodSK,PeriodSD,PaFilter,PaCycles,DzStartBuyProbability,DzStartSellProbability,MAMode,TMSmoothing,TMDamping,TMNoise,1,y);
         bl1[i]   = iCustom(NULL,timeFrame,IndicatorFileName,"calculateValue",RsiPeriod,"","",RsiPrice,"",RsiMethod,PeriodStoch,PeriodSK,PeriodSD,PaFilter,PaCycles,DzStartBuyProbability,DzStartSellProbability,MAMode,TMSmoothing,TMDamping,TMNoise,2,y);
         sl1[i]   = iCustom(NULL,timeFrame,IndicatorFileName,"calculateValue",RsiPeriod,"","",RsiPrice,"",RsiMethod,PeriodStoch,PeriodSK,PeriodSD,PaFilter,PaCycles,DzStartBuyProbability,DzStartSellProbability,MAMode,TMSmoothing,TMDamping,TMNoise,3,y);
         zli[i]   = iCustom(NULL,timeFrame,IndicatorFileName,"calculateValue",RsiPeriod,"","",RsiPrice,"",RsiMethod,PeriodStoch,PeriodSK,PeriodSD,PaFilter,PaCycles,DzStartBuyProbability,DzStartSellProbability,MAMode,TMSmoothing,TMDamping,TMNoise,4,y);
         trend[i] = iCustom(NULL,timeFrame,IndicatorFileName,"calculateValue",RsiPeriod,"","",RsiPrice,"",RsiMethod,PeriodStoch,PeriodSK,PeriodSD,PaFilter,PaCycles,DzStartBuyProbability,DzStartSellProbability,MAMode,TMSmoothing,TMDamping,TMNoise,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;
               bl1[i+k] = bl1[i] + (bl1[i+n] - bl1[i]) * k/n;
               sl1[i+k] = sl1[i] + (sl1[i+n] - sl1[i]) * k/n;
               zli[i+k] = zli[i] + (zli[i+n] - zli[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","rsx","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 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 wrkTm[][3];
#define _price 0
#define _y1    1
#define _y2    2

//
//
//
//
//

double iTmSmooth(double price, double damping, double noise, double length, int i)
{
   if (ArrayRange(wrkTm,0) != Bars) ArrayResize(wrkTm,Bars);
   if (length<=1) return(price);
      int r = Bars-i-1;

   //
   //
   //
   //
   //

      wrkTm[r][_price] = price;

         double y1 = wrkTm[r-1][_y1];
         double y2 = wrkTm[r-1][_y2];
         
         double err = (wrkTm[r][_price]-2.0*y1+y2)/noise; 
         double drv = MathMax(MathMin((1.0/length)*err*err+(1.0/length)*MathAbs(err),0.5),0.0);
         double dmp = MathMax(MathMin((1.0/length)*MathAbs(y1-y2)/noise + damping/100.0,1.0),0.0);
         
         //
         //
         //
         //
         //
         
      double tmAvg  = y1 + noise*err*drv + (y1-y2)*(1.0-dmp);
      wrkTm[r][_y1] = tmAvg;
      wrkTm[r][_y2] = y1;
      return(tmAvg);
}   

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double workHil[][9];
#define _price      0
#define _smooth     1
#define _detrender  2
#define _period     3
#define _instPeriod 4
#define _phase      5
#define _deltaPhase 6
#define _Q1         7
#define _I1         8

#define Pi 3.14159265358979323846264338327950288

//
//
//
//
//

double iHilbertPhase(double price, double filter, double cyclesToReach, int i, int s=0)
{
   if (ArrayRange(workHil,0)!=Bars) ArrayResize(workHil,Bars);
   int r = Bars-i-1; s = s*9;
      
   //
   //
   //
   //
   //
      
      workHil[r][s+_price]      = price;
      workHil[r][s+_smooth]     = (4.0*workHil[r][s+_price]+3.0*workHil[r-1][s+_price]+2.0*workHil[r-2][s+_price]+workHil[r-3][s+_price])/10.0;
      workHil[r][s+_detrender]  = calcComp(r,_smooth,s);
      workHil[r][s+_Q1]         = 0.15*calcComp(r,_detrender,s)  +0.85*workHil[r-1][s+_Q1];
      workHil[r][s+_I1]         = 0.15*workHil[r-3][s+_detrender]+0.85*workHil[r-1][s+_I1];
      workHil[r][s+_phase]      = workHil[r-1][s+_phase];
      workHil[r][s+_instPeriod] = workHil[r-1][s+_instPeriod];

      //
      //
      //
      //
      //
           
         if (MathAbs(workHil[r][s+_I1])>0)
                     workHil[r][s+_phase] = 180.0/Pi*MathArctan(MathAbs(workHil[r][s+_Q1]/workHil[r][s+_I1]));
           
         if (workHil[r][s+_I1]<0 && workHil[r][s+_Q1]>0) workHil[r][s+_phase] = 180.0-workHil[r][s+_phase];
         if (workHil[r][s+_I1]<0 && workHil[r][s+_Q1]<0) workHil[r][s+_phase] = 180.0+workHil[r][s+_phase];
         if (workHil[r][s+_I1]>0 && workHil[r][s+_Q1]<0) workHil[r][s+_phase] = 360.0-workHil[r][s+_phase];

      //
      //
      //
      //
      //
                        
      workHil[r][s+_deltaPhase] = workHil[r-1][s+_phase]-workHil[r][s+_phase];

         if (workHil[r-1][s+_phase]<90.0 && workHil[r][s+_phase]>270.0)
             workHil[r][s+_deltaPhase] = 360.0+workHil[r-1][s+_phase]-workHil[r][s+_phase];
             workHil[r][s+_deltaPhase] = MathMax(MathMin(workHil[r][s+_deltaPhase],60),7);
      
            //
            //
            //
            //
            //
                  
            double alpha    = 2.0/(1.0+MathMax(filter,1));
            double phaseSum = 0; for (int k=0; phaseSum<cyclesToReach*360.0 && (r-k)>0; k++) phaseSum += workHil[r-k][s+_deltaPhase];
         
               if (k>0) workHil[r][s+_instPeriod]= k;
                  workHil[r][s+_period] = workHil[r-1][s+_period]+alpha*(workHil[r][s+_instPeriod]-workHil[r-1][s+_period]);
   return (workHil[r][s+_period]);
}

//
//
//
//
//

double calcComp(int r, int from, int s)
{
   return((0.0962*workHil[r  ][s+from] + 
           0.5769*workHil[r-2][s+from] - 
           0.5769*workHil[r-4][s+from] - 
           0.0962*workHil[r-6][s+from]) * (0.075*workHil[r-1][s+_period] + 0.54));
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

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");
      }
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

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);
}


