//+------------------------------------------------------------------+
//|                                                  OnChart WPR.mq4 |
//|                                                           mladen |
//| not for sale, rent, auction, nor lease                           |
//+------------------------------------------------------------------+
// https://forex-station.com/viewtopic.php?p=1295413478#p1295413478
// modified by banzai; 6/26/20
// thanks to jeanlouie codes and templates @ https://www.forexfactory.com/jeanlouie

#property copyright "mladen"
#property link      "www.forex-station.com"

#property indicator_chart_window
#property indicator_buffers 7
#property indicator_color1  clrSlateGray // middle line
#property indicator_width1  1
#property indicator_style1  STYLE_DOT

#property indicator_color2  clrHotPink //upper band
#property indicator_width2  2
#property indicator_color3  clrHotPink  //lower band
#property indicator_width3  1

#property indicator_color4  clrSpringGreen //upper band
#property indicator_width4  2
#property indicator_color5  clrSpringGreen //lower band
#property indicator_width5  1

#property indicator_color6  clrSeaGreen //uptrend line
#property indicator_width6  3
#property indicator_color7  clrMediumVioletRed //downtrend line
#property indicator_width7  3

extern string                TimeFrame         = "Current time frame";
extern double                WprPeriod         = 14;
extern double                WprPhase          = 0;
extern bool                  WprDouble         = false;
extern ENUM_APPLIED_PRICE    Price             =  0;
extern double                SmoothLength      = 50;
extern double                SmoothPhase       = 0; 
extern bool                  SmoothDouble      = false;
extern int                   AtrLength         = 120;
extern int                   overBought        = -20;
extern int                   overSold          = -80;
extern string                note9             = "-------------------------";
extern bool                  arrowsVisible     = true;
extern bool                  arrowsOnFirst     = true;
extern bool                  arrowsOnSlope     = true;
extern bool                  arrowsOnMaCross   = false;
extern string                arrowsIdentifier  = "WPRarrows";
extern double                arrowsUpperGap    = 2.5;
extern double                arrowsLowerGap    = 0.3;
extern color                 arrowsUpColor     = clrLimeGreen;
extern color                 arrowsDnColor     = clrRed;
extern int                   arrowsUpCode      = 241;
extern int                   arrowsDownCode    = 242;
extern int                   arrowSize         = 3;
extern string                note10            = "-------------------------";
extern bool                  alertsOn          = false;
extern bool                  alertsOnCurrent   = false;
extern bool                  alertsOnSlope     = false;
extern bool                  alertsOnMaCross   = false;
extern bool                  alertsMessage     = false;
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;

//template code start1
extern bool   btn_show       = true;                         //btn__show
extern string btn_pressed    = "WPR";                //btn__pressed text
extern string btn_unpressed  = "WPR";              //btn__unpressed text
extern int    btn_offset_x   = 204;                             //btn__x
extern int    btn_offset_y   = 20;                              //btn__y
extern int    btn_width      = 65;                          //btn__width
extern int    btn_height     = 20;                         //btn__height
extern int    btn_font_size  = 10;                      //btn__font size
extern color  btn_font_clr   = clrBlack;               //btn__font color
extern color  btn_bg_color   = clrGray;                  //btn__bg color
extern color  btn_border_clr = clrWhiteSmoke;        //btn__border color
//template code end1

extern string                TimeFrameNote1="input 0 for Current Timeframe, 1 for 1MIN, 5 for 5MIN";
extern string                TimeFrameNote2="15 for 15MIN, 30 for 30MIN, 60 for 1H";
extern string                TimeFrameNote3="240 for 4H, 1440 for D1, 10080 for W1, 43200 for MN1";

double MiddleLine[], UpperBand1[], LowerBand2[], Buffer4[], Buffer4Da[], Buffer4Db[], trend[], slope[], UpperBand2[], LowerBand1[];

string indicatorFileName;
bool   returnBars, calculateValue;
int    timeFrame, atrTimeFrame;

//template code start2
string aButtonName = "WPR_tog_btn";
//template code end2

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int OnInit()
{
   IndicatorBuffers(10);
   SetIndexBuffer(0,MiddleLine); SetIndexLabel (0, "Middle Line");

   SetIndexBuffer(1,UpperBand1); SetIndexLabel (1, "Upper Band 1");
   SetIndexBuffer(2,UpperBand2); SetIndexLabel (2, "Upper Band 2");
   SetIndexBuffer(3,LowerBand1); SetIndexLabel (3, "Lower Band 1");
   SetIndexBuffer(4,LowerBand2); SetIndexLabel (4, "Lower Band 2");

   SetIndexBuffer(5,Buffer4);    SetIndexLabel (5, "WPR ("+IntegerToString(WprPeriod)+")");
   SetIndexBuffer(6,Buffer4Da);
   SetIndexBuffer(7,Buffer4Db);
   SetIndexBuffer(8,slope);
   SetIndexBuffer(9,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)+"   %R");
   
//template code start3  
   if(btn_show){CreateButton();}
   if(!btn_show){ObjectDelete(0,aButtonName);}
//template code end3

   return(0);
}
//+------------------------------------------------------------------+
int deinit()
{
   deleteArrows();

   //template code start4
   ObjectDelete(0,aButtonName);
   //template code end4

return(0);
}
//+------------------------------------------------------------------+
int start()
{
string lookFor;
   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) { MiddleLine[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); 
               
            MiddleLine[i] = maValue;
            UpperBand1[i] = maValue+(avgRange*(overBought+50)/100);
            LowerBand2[i] = maValue-(avgRange*(-50-overSold)/100);
            UpperBand2[i] = maValue+(avgRange*(overBought+45)/100);
            LowerBand1[i] = maValue-(avgRange*(-45-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]>MiddleLine[i])   trend[i] =  1;
            if (Buffer4[i]<MiddleLine[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]);
              lookFor = arrowsIdentifier+":"+Time[i]; ObjectDelete(lookFor);
              if (arrowsOnSlope && slope[i] != slope[i+1])
              {
                if (slope[i] == 1) drawArrow("1up",0.5,i,arrowsUpColor,arrowsUpCode,false);
                if (slope[i] ==-1) drawArrow("1down",0.5,i+1,arrowsDnColor,arrowsDownCode,true);
              }
              if (arrowsOnMaCross && trend[i] != trend[i+1])
              {
                if (trend[i] == 1) drawArrow("2up",1,i,arrowsUpColor,arrowsUpCode,false);
                if (trend[i] ==-1) drawArrow("2down",1,i+1,arrowsDnColor,arrowsDownCode,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]);

         MiddleLine[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",WprPeriod,WprPhase,WprDouble,Price,SmoothLength,SmoothPhase,SmoothDouble,AtrLength,overBought,overSold,note9,arrowsVisible,arrowsOnFirst,arrowsOnSlope,arrowsOnMaCross,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDownCode,arrowSize,note10,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnMaCross,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,Interpolate,MultiColor,btn_show,btn_pressed,btn_unpressed,btn_offset_x,btn_offset_y,btn_width,btn_height,btn_font_size,btn_font_clr,btn_bg_color,btn_border_clr,0,y);
         UpperBand1[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",WprPeriod,WprPhase,WprDouble,Price,SmoothLength,SmoothPhase,SmoothDouble,AtrLength,overBought,overSold,note9,arrowsVisible,arrowsOnFirst,arrowsOnSlope,arrowsOnMaCross,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDownCode,arrowSize,note10,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnMaCross,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,Interpolate,MultiColor,btn_show,btn_pressed,btn_unpressed,btn_offset_x,btn_offset_y,btn_width,btn_height,btn_font_size,btn_font_clr,btn_bg_color,btn_border_clr,1,y);
         UpperBand2[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",WprPeriod,WprPhase,WprDouble,Price,SmoothLength,SmoothPhase,SmoothDouble,AtrLength,overBought,overSold,note9,arrowsVisible,arrowsOnFirst,arrowsOnSlope,arrowsOnMaCross,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDownCode,arrowSize,note10,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnMaCross,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,Interpolate,MultiColor,btn_show,btn_pressed,btn_unpressed,btn_offset_x,btn_offset_y,btn_width,btn_height,btn_font_size,btn_font_clr,btn_bg_color,btn_border_clr,2,y);
         LowerBand1[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",WprPeriod,WprPhase,WprDouble,Price,SmoothLength,SmoothPhase,SmoothDouble,AtrLength,overBought,overSold,note9,arrowsVisible,arrowsOnFirst,arrowsOnSlope,arrowsOnMaCross,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDownCode,arrowSize,note10,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnMaCross,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,Interpolate,MultiColor,btn_show,btn_pressed,btn_unpressed,btn_offset_x,btn_offset_y,btn_width,btn_height,btn_font_size,btn_font_clr,btn_bg_color,btn_border_clr,3,y);
         LowerBand2[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",WprPeriod,WprPhase,WprDouble,Price,SmoothLength,SmoothPhase,SmoothDouble,AtrLength,overBought,overSold,note9,arrowsVisible,arrowsOnFirst,arrowsOnSlope,arrowsOnMaCross,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDownCode,arrowSize,note10,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnMaCross,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,Interpolate,MultiColor,btn_show,btn_pressed,btn_unpressed,btn_offset_x,btn_offset_y,btn_width,btn_height,btn_font_size,btn_font_clr,btn_bg_color,btn_border_clr,4,y);
         Buffer4[i]       = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",WprPeriod,WprPhase,WprDouble,Price,SmoothLength,SmoothPhase,SmoothDouble,AtrLength,overBought,overSold,note9,arrowsVisible,arrowsOnFirst,arrowsOnSlope,arrowsOnMaCross,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDownCode,arrowSize,note10,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnMaCross,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,Interpolate,MultiColor,btn_show,btn_pressed,btn_unpressed,btn_offset_x,btn_offset_y,btn_width,btn_height,btn_font_size,btn_font_clr,btn_bg_color,btn_border_clr,5,y); 
         slope[i]         = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",WprPeriod,WprPhase,WprDouble,Price,SmoothLength,SmoothPhase,SmoothDouble,AtrLength,overBought,overSold,note9,arrowsVisible,arrowsOnFirst,arrowsOnSlope,arrowsOnMaCross,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDownCode,arrowSize,note10,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnMaCross,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,Interpolate,MultiColor,btn_show,btn_pressed,btn_unpressed,btn_offset_x,btn_offset_y,btn_width,btn_height,btn_font_size,btn_font_clr,btn_bg_color,btn_border_clr,8,y); 
         trend[i]         = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",WprPeriod,WprPhase,WprDouble,Price,SmoothLength,SmoothPhase,SmoothDouble,AtrLength,overBought,overSold,note9,arrowsVisible,arrowsOnFirst,arrowsOnSlope,arrowsOnMaCross,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDownCode,arrowSize,note10,alertsOn,alertsOnCurrent,alertsOnSlope,alertsOnMaCross,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,Interpolate,MultiColor,btn_show,btn_pressed,btn_unpressed,btn_offset_x,btn_offset_y,btn_width,btn_height,btn_font_size,btn_font_clr,btn_bg_color,btn_border_clr,9,y); 
         Buffer4Da[i]     = EMPTY_VALUE; //make mtf lines smoother
         Buffer4Db[i]     = EMPTY_VALUE; //make mtf lines smoother
           
            if (arrowsVisible)
            {
              ObjectDelete(arrowsIdentifier+":1up:"+Time[i]);
              ObjectDelete(arrowsIdentifier+":1down:"+Time[i]);
              ObjectDelete(arrowsIdentifier+":2up:"+Time[i]);
              ObjectDelete(arrowsIdentifier+":2down:"+Time[i]);
              lookFor = arrowsIdentifier+":"+Time[i]; ObjectDelete(lookFor);
              if (arrowsOnSlope && slope[i] != slope[i+1])
              {
                if (slope[i] == 1) drawArrow("1up",0.5,i,arrowsUpColor,arrowsUpCode,false);
                if (slope[i] ==-1) drawArrow("1down",0.5,i+1,arrowsDnColor,arrowsDownCode,true);
              }
              if (arrowsOnMaCross && trend[i] != trend[i+1])
              {
                if (trend[i] == 1) drawArrow("2up",1,i,arrowsUpColor,arrowsUpCode,false);
                if (trend[i] ==-1) drawArrow("2down",1,i+1,arrowsDnColor,arrowsDownCode,true);
              }
            }
//
//
//               
         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++)
            {
               MiddleLine[i+k] = MiddleLine[i] + (MiddleLine[i+n] - MiddleLine[i]) * k/n;
               UpperBand1[i+k] = UpperBand1[i] + (UpperBand1[i+n] - UpperBand1[i]) * k/n;
               UpperBand2[i+k] = UpperBand2[i] + (UpperBand2[i+n] - UpperBand2[i]) * k/n;
               LowerBand1[i+k] = LowerBand1[i] + (LowerBand1[i+n] - LowerBand1[i]) * k/n;
               LowerBand2[i+k] = LowerBand2[i] + (LowerBand2[i+n] - LowerBand2[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);
         ObjectSet   (name,OBJPROP_WIDTH,arrowSize);

         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 MakeArrows_clrNONE()
{
   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) 
            ObjectSet    (objectName,OBJPROP_COLOR,clrNONE);
   }
}
//+------------------------------------------------------------------+
void RestoreArrowColors()
{
   string lookFor1up, lookFor2up, lookFor1down, lookFor2down, objectName;
   int i, lookForLength1, lookForLength2, lookForLength3, lookForLength4;
   
   lookFor1up     = arrowsIdentifier+":1up";
   lookFor2up     = arrowsIdentifier+":2up";
   lookForLength1 = StringLen(lookFor1up);
   lookForLength2 = StringLen(lookFor2up);

   lookFor1down   = arrowsIdentifier+":1down";
   lookFor2down   = arrowsIdentifier+":2down";
   lookForLength3 = StringLen(lookFor1down);
   lookForLength4 = StringLen(lookFor2down);

   for (i=ObjectsTotal()-1; i>=0; i--)
   {
      objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength1) == lookFor1up)
            ObjectSet    (objectName,OBJPROP_COLOR,arrowsUpColor);
         if (StringSubstr(objectName,0,lookForLength2) == lookFor2up)
            ObjectSet    (objectName,OBJPROP_COLOR,arrowsUpColor);
         
         if (StringSubstr(objectName,0,lookForLength3) == lookFor1down)
            ObjectSet    (objectName,OBJPROP_COLOR,arrowsDnColor);
         if (StringSubstr(objectName,0,lookForLength4) == lookFor2down)
            ObjectSet    (objectName,OBJPROP_COLOR,arrowsDnColor);
   }
}
//+------------------------------------------------------------------+
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);
      }
}
//+------------------------------------------------------------------+
//template start codes5
void CreateButton()
{
   ButtonCreate(NULL,aButtonName,0,btn_offset_x,btn_offset_y,btn_width,btn_height,CORNER_LEFT_UPPER,btn_unpressed,"Arial",btn_font_size,btn_font_clr,btn_bg_color,btn_border_clr,false,true,false,false,0);
}
//+------------------------------------------------------------------+
void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
{
   if (id == CHARTEVENT_OBJECT_CLICK && sparam==aButtonName) 
   { 
      if(ObjectGetInteger (0,aButtonName,OBJPROP_STATE)){
         ObjectSetString  (0,aButtonName,OBJPROP_TEXT,btn_pressed);
         SetIndexStyle(0,DRAW_LINE,EMPTY,indicator_width1,clrNONE);
         SetIndexStyle(1,DRAW_LINE,EMPTY,indicator_width2,clrNONE);
         SetIndexStyle(2,DRAW_LINE,EMPTY,indicator_width3,clrNONE);
         SetIndexStyle(3,DRAW_LINE,EMPTY,indicator_width4,clrNONE);
         SetIndexStyle(4,DRAW_LINE,EMPTY,indicator_width5,clrNONE);
         SetIndexStyle(5,DRAW_LINE,EMPTY,indicator_width6,clrNONE);
         SetIndexStyle(6,DRAW_LINE,EMPTY,indicator_width7,clrNONE);
         MakeArrows_clrNONE();
         }

      if(!ObjectGetInteger(0,aButtonName,OBJPROP_STATE)){
         ObjectSetString  (0,aButtonName,OBJPROP_TEXT,btn_unpressed);
         SetIndexStyle(0,DRAW_LINE,EMPTY,indicator_width1,indicator_color1);
         SetIndexStyle(1,DRAW_LINE,EMPTY,indicator_width2,indicator_color2);
         SetIndexStyle(2,DRAW_LINE,EMPTY,indicator_width3,indicator_color3);
         SetIndexStyle(3,DRAW_LINE,EMPTY,indicator_width4,indicator_color4);
         SetIndexStyle(4,DRAW_LINE,EMPTY,indicator_width5,indicator_color5);
         SetIndexStyle(5,DRAW_LINE,EMPTY,indicator_width6,indicator_color6);
         SetIndexStyle(6,DRAW_LINE,EMPTY,indicator_width7,indicator_color7);
         RestoreArrowColors();
         }
   }
}
//+------------------------------------------------------------------+
bool ButtonCreate(const long              chart_ID=0,               // chart's ID
                  const string            name="Button",            // button name
                  const int               sub_window=0,             // subwindow index
                  const int               x=0,                      // X coordinate
                  const int               y=0,                      // Y coordinate
                  const int               width=50,                 // button width
                  const int               height=18,                // button height
                  const ENUM_BASE_CORNER  corner=CORNER_LEFT_UPPER, // chart corner for anchoring
                  const string            text="Button",            // text
                  const string            font="Arial",             // font
                  const int               font_size=10,             // font size
                  const color             clr=clrBlack,             // text color
                  const color             back_clr=C'236,233,216',  // background color
                  const color             border_clr=clrNONE,       // border color
                  const bool              state=false,              // pressed/released
                  const bool              back=false,               // in the background
                  const bool              selectable=true,      //object can be selected        
                  const bool              selection=false,          // highlight to move
                  const bool              hidden=false,              // hidden in the object list
                  const long              z_order=0)                // priority for mouse click
  {
   ResetLastError();
   ObjectCreate    (chart_ID,name,OBJ_BUTTON,          sub_window,0,0);
   ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,   x);
   ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,   y);
   ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,       width);
   ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,      corner);
   ObjectSetString (chart_ID,name,OBJPROP_TEXT,        text);
   ObjectSetString (chart_ID,name,OBJPROP_FONT,        font);
   ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,    font_size);
   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,       clr);
   ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,     back_clr);
   ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_COLOR,border_clr);
   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,        back);
   ObjectSetInteger(chart_ID,name,OBJPROP_STATE,       state);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,  selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,    selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,      hidden);
   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,      z_order);
   return(true);
  }
//+------------------------------------------------------------------+
//template end codes5
