//+------------------------------------------------------------------+
//|                                                  OnChart WPR.mq4 |
//|                                                           mladen |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      ""

#property indicator_chart_window
#property indicator_buffers 6
#property indicator_color1  clrCrimson
#property indicator_color2  clrGoldenrod
#property indicator_color3  clrGoldenrod
#property indicator_color4  clrDeepSkyBlue
#property indicator_color5  clrPaleVioletRed
#property indicator_color6  clrPaleVioletRed
#property indicator_width4  2
#property indicator_width5  2
#property indicator_width6  2
#property indicator_style1  STYLE_DASH

//
//
//
//
//

extern string TimeFrame         = "Current time frame";
extern double WprPeriod         = 21;
extern double WprPhase          = 0;
extern bool   WprDouble         = false;
extern int    Price             =  0;
extern double SmoothLength      = 50;
extern double SmoothPhase       = 0; 
extern bool   SmoothDouble      = false;
extern int    AtrLength         = 120;
extern int    overBought        = -10;
extern int    overSold          = -90;
extern bool   arrowsVisible     = true;
extern bool   arrowsOnFirst     = false;
extern bool   arrowsOnSlope     = false;
extern bool   arrowsOnMaCross   = true;
extern string arrowsIdentifier  = "ocwpr arrows1";
extern double arrowsUpperGap    = 0.5;
extern double arrowsLowerGap    = 0.5;
extern color  arrowsUpColor     = clrLimeGreen;
extern color  arrowsDnColor     = clrRed;
extern int    arrowsUpCode      = 241;
extern int    arrowsDnCode      = 242;
extern bool   alertsOn          = true;
extern bool   alertsOnCurrent   = false;
extern bool   alertsOnSlope     = false;
extern bool   alertsOnMaCross   = true;
extern bool   alertsMessage     = true;
extern bool   alertsSound       = false;
extern bool   alertsNotify      = false;
extern bool   alertsEmail       = false;
extern string soundFile         = "alert2.wav";
extern bool   Interpolate       = true;
extern bool   MultiColor        = true;


//
//
//
//
//

double Buffer1[];
double Buffer2[];
double Buffer3[];
double Buffer4[];
double Buffer4Da[];
double Buffer4Db[];
double trend[];
double slope[];

//
//
//
//
//

string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;
int    atrTimeFrame;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int init()
{
   IndicatorBuffers(8);
   SetIndexBuffer(0,Buffer1);
   SetIndexBuffer(1,Buffer2);
   SetIndexBuffer(2,Buffer3);
   SetIndexBuffer(3,Buffer4);
   SetIndexBuffer(4,Buffer4Da);
   SetIndexBuffer(5,Buffer4Db);
   SetIndexBuffer(6,slope);
   SetIndexBuffer(7,trend);
   
      //
      //
      //
      //
      //
      
         timeFrame    = stringToTimeFrame(TimeFrame);
         atrTimeFrame = PERIOD_H4;
              switch (timeFrame)
               {
                 case PERIOD_M1:  atrTimeFrame = PERIOD_H1;  break;
                 case PERIOD_M5:  atrTimeFrame = PERIOD_H4;  break;
                 case PERIOD_M15: atrTimeFrame = PERIOD_H4;  break;
                 case PERIOD_M30: atrTimeFrame = PERIOD_D1;  break;
                 case PERIOD_H1:  atrTimeFrame = PERIOD_D1;  break;
                 case PERIOD_H4:  atrTimeFrame = PERIOD_D1;  break;
                 case PERIOD_D1:  atrTimeFrame = PERIOD_W1;  break;
                 case PERIOD_W1:  atrTimeFrame = PERIOD_MN1; break;
                 default:         atrTimeFrame = PERIOD_H4;
               }
         indicatorFileName = WindowExpertName();
         calculateValue    = TimeFrame=="calculateValue"; if (calculateValue) { return(0); }
         returnBars        = TimeFrame=="returnBars";     if (returnBars)     { return(0); }
      
      //
      //
      //
      //
      //
               
   IndicatorShortName(timeFrameToString(timeFrame)+"   oc%r");
   return(0);
}
int deinit()
{
   deleteArrows();

return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { Buffer1[0] = MathMin(limit+1,Bars-1); return(0); }
      
   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame == Period())
   {
      if (MultiColor && slope[limit]==-1) CleanPoint(limit,Buffer4Da,Buffer4Db);
      for (int i=limit; i>=0; i--) 
      {
         int r = iBarShift(NULL,atrTimeFrame,Time[i]);
            double avgRange = iATR(NULL,atrTimeFrame,AtrLength,r);
            double maValue  = iDSmooth(iMA(NULL,0,1,0,MODE_SMA,Price,i),SmoothLength,SmoothPhase,SmoothDouble,i,0);
            
            double wprValue;
            double hi = High[iHighest(NULL,0,MODE_HIGH,WprPeriod,i)];
            double lo =  Low[iLowest(NULL, 0,MODE_LOW, WprPeriod,i)];
            if (hi!=lo)      
                 wprValue = iDSmooth(-100*(hi-Close[i])/(hi-lo),WprPeriod,WprPhase,WprDouble,i,20);
            else wprValue = iDSmooth(0                         ,WprPeriod,WprPhase,WprDouble,i,20); 
               
            Buffer1[i] = maValue;
            Buffer2[i] = maValue+(avgRange*(overBought+50)/100);
            Buffer3[i] = maValue-(avgRange*(-50-overSold)/100);
            Buffer4[i] = maValue+(wprValue+50)/100*avgRange;
            
            //
            //
            //
            //
            //
            
            Buffer4Da[i] = EMPTY_VALUE;
            Buffer4Db[i] = EMPTY_VALUE;
            slope[i] = slope[i+1];
            trend[i] = trend[i+1];
            if (Buffer4[i]<Buffer4[i+1]) slope[i] = -1;
            if (Buffer4[i]>Buffer4[i+1]) slope[i] =  1;
            if (Buffer4[i]>Buffer1[i])   trend[i] =  1;
            if (Buffer4[i]<Buffer1[i])   trend[i] = -1;
            if (MultiColor && slope[i] == -1) PlotPoint(i,Buffer4Da,Buffer4Db,Buffer4);
           
            //
            //
            //
            //
            //
            
            if (arrowsVisible)
           {
              ObjectDelete(arrowsIdentifier+":1:"+Time[i]);
              ObjectDelete(arrowsIdentifier+":2:"+Time[i]);
              string lookFor = arrowsIdentifier+":"+Time[i]; ObjectDelete(lookFor);
              if (arrowsOnSlope && slope[i] != slope[i+1])
              {
                if (slope[i] == 1) drawArrow("1",0.5,i,arrowsUpColor,arrowsUpCode,false);
                if (slope[i] ==-1) drawArrow("1",0.5,i,arrowsDnColor,arrowsDnCode,true);
              }
              if (arrowsOnMaCross && trend[i] != trend[i+1])
              {
                if (trend[i] == 1) drawArrow("2",1,i,arrowsUpColor,arrowsUpCode,false);
                if (trend[i] ==-1) drawArrow("2",1,i,arrowsDnColor,arrowsDnCode,true);
              }
              
            }
     } 
      
     //
     //
     //
     //
     //
         
     if (alertsOn)
     {
        if (alertsOnCurrent)
             int whichBar = 0;
        else     whichBar = 1;
        static datetime time1 = 0;
        static string   mess1 = "";
        if (alertsOnSlope && slope[whichBar] != slope[whichBar+1])
        {
           if (slope[whichBar] ==  1 ) doAlert(time1,mess1,whichBar,"sloping up");
           if (slope[whichBar] == -1 ) doAlert(time1,mess1,whichBar,"sloping down");
        }         
        static datetime time2 = 0;
        static string   mess2 = "";
        if (alertsOnMaCross && trend[whichBar] != trend[whichBar+1])
        {
           if (trend[whichBar] ==  1 ) doAlert(time2,mess2,whichBar,"crossing Ma up");
           if (trend[whichBar] == -1 ) doAlert(time2,mess2,whichBar,"crossing Ma down");
        }         
     }            
   return(0);
   } 
        
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   if (MultiColor && slope[limit]==-1) CleanPoint(limit,Buffer4Da,Buffer4Db);
   for (i=limit; i>=0; i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         Buffer1[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",WprPeriod,WprPhase,WprDouble,Price,SmoothLength,SmoothPhase,SmoothDouble,AtrLength,overBought,overSold,arrowsVisible,arrowsOnFirst,arrowsOnSlope,arrowsOnMaCross,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnMaCross,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,0,y);
         Buffer2[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",WprPeriod,WprPhase,WprDouble,Price,SmoothLength,SmoothPhase,SmoothDouble,AtrLength,overBought,overSold,arrowsVisible,arrowsOnFirst,arrowsOnSlope,arrowsOnMaCross,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnMaCross,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,1,y);
         Buffer3[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",WprPeriod,WprPhase,WprDouble,Price,SmoothLength,SmoothPhase,SmoothDouble,AtrLength,overBought,overSold,arrowsVisible,arrowsOnFirst,arrowsOnSlope,arrowsOnMaCross,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnMaCross,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,2,y);
         Buffer4[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",WprPeriod,WprPhase,WprDouble,Price,SmoothLength,SmoothPhase,SmoothDouble,AtrLength,overBought,overSold,arrowsVisible,arrowsOnFirst,arrowsOnSlope,arrowsOnMaCross,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnMaCross,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,3,y); 
         slope[i]     = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",WprPeriod,WprPhase,WprDouble,Price,SmoothLength,SmoothPhase,SmoothDouble,AtrLength,overBought,overSold,arrowsVisible,arrowsOnFirst,arrowsOnSlope,arrowsOnMaCross,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnMaCross,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,6,y); 
         Buffer4Da[i] = EMPTY_VALUE;
         Buffer4Db[i] = EMPTY_VALUE; 
           
         //
         //
         //
         //
         //
               
         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++)
            {
               Buffer1[i+k] = Buffer1[i] + (Buffer1[i+n] - Buffer1[i]) * k/n;
               Buffer2[i+k] = Buffer2[i] + (Buffer2[i+n] - Buffer2[i]) * k/n;
               Buffer3[i+k] = Buffer3[i] + (Buffer3[i+n] - Buffer3[i]) * k/n;
               Buffer4[i+k] = Buffer4[i] + (Buffer4[i+n] - Buffer4[i]) * k/n;             
           }          
    }
    for (i=limit;i>=0;i--) if (MultiColor && slope[i] == -1) PlotPoint(i,Buffer4Da,Buffer4Db,Buffer4);  
return(0);
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

string sTfTable[] = {"M1","M5","M10","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,10,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);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double wrk[][40];

#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]);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   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 (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;
      }
}

//
//
//
//
//

void drawArrow(string nameAdd, double gapMul, int i,color theColor,int theCode,bool up)
{
   string name = arrowsIdentifier+":"+nameAdd+":"+Time[i];
   double gap  = iATR(NULL,0,20,i)*gapMul;   
   
      //
      //
      //
      //
      //
      
      int add = 0; if (!arrowsOnFirst) add = _Period*60-1;
      ObjectCreate(name,OBJ_ARROW,0,Time[i]+add,0);
         ObjectSet(name,OBJPROP_ARROWCODE,theCode);
         ObjectSet(name,OBJPROP_COLOR,theColor);
         if (up)
               ObjectSet(name,OBJPROP_PRICE1,High[i] + arrowsUpperGap * gap);
         else  ObjectSet(name,OBJPROP_PRICE1,Low[i]  - arrowsLowerGap * 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 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)," OnChart_WPRsmooth ",doWhat);
             if (alertsMessage) Alert(message);
             if (alertsNotify)  SendNotification(message);
             if (alertsEmail)   SendMail(StringConcatenate(Symbol()," OnChart_WPRsmooth "),message);
             if (alertsSound)   PlaySound(soundFile);
      }
}

  