//+------------------------------------------------------------------+
//|                                           Volatility quality.mq4 |
//|                                                                  |
//|                                                                  |
//| Volatility quality index originaly developed by                  |
//| Thomas Stridsman (August 2002 Active Trader Magazine)            |
//|                                                                  |
//| Price pre-smoothing and filter added by raff1410                 |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers 2
#property indicator_color1  DeepSkyBlue
#property indicator_color2  Silver
#property indicator_minimum 0
#property indicator_maximum 1
#property indicator_width1  3
#property indicator_width2  3
#property strict

//
//
//
//
//
extern ENUM_TIMEFRAMES TimeFrame = PERIOD_CURRENT;  // Time frame to use 
extern int    PreSmooth          = 5;               // Pre smoothing period
extern double PreSmoothPhase     = 0;               // Pre smoothing phase
extern bool   PreSmoothDouble    = false;           // Pre smoothing should be double smoothing
extern int    JMA1Period         = 14;              // First jma period
extern double JMA1Phase          = 0;               // First jma phase
extern bool   JMA1Double         = false;           // First jma should be double
extern int    JMA2Period         = 100;             // Second jma period
extern double JMA2Phase          = 0;               // Second jma phase
extern bool   JMA2Double         = false;           // Second jma should be double
extern int    Filter             = 0;               // Filter length
extern bool   alertsOn           = false;           // Turn alerts on
extern bool   alertsOnCurrent    = true;            // Alert on current (still opened) bar
extern bool   alertsMessage      = true;            // Alerts should show popup message
extern bool   alertsSound        = false;           // Alerts should play a sound
extern bool   alertsEmail        = false;           // alerts should send email
extern bool   alertsPush         = false;           // alerts should send push notification

//
//
//
//
//

double sumVqi[];
double sumVqida[];
double sumVqidb[];
double sumVqi1[];
double sumVqi2[];
double Vqi[];
double trend[];

string indicatorFileName;
bool   returnBars;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(7);
      SetIndexBuffer(0,sumVqida); SetIndexStyle(0,DRAW_HISTOGRAM);
      SetIndexBuffer(1,sumVqidb); SetIndexStyle(1,DRAW_HISTOGRAM);
      SetIndexBuffer(2,sumVqi1); 
      SetIndexBuffer(3,sumVqi2); 
      SetIndexBuffer(4,sumVqi); 
      SetIndexBuffer(5,Vqi); 
      SetIndexBuffer(6,trend);
      
      //
      //
      //
      //
      //
      
      indicatorFileName = WindowExpertName();
      returnBars        = TimeFrame==-99;
      TimeFrame         = MathMax(TimeFrame,_Period);
      
      //
      //
      //
      //
      //
         
    IndicatorShortName(timeFrameToString(TimeFrame)+" VQ on jurik ");
return(0);
}
int deinit() { 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)  { sumVqi1[0] = limit+1; return(0); }     
   
   //
   //
   //
   //
   //
         
   if (TimeFrame==Period())
   {      
    for(int i=limit; i>=0; i--)
    {
      if (i==(Bars-1))
      {
         Vqi[i]    = 0;
         sumVqi[i] = 0;
         continue;
      }
      
      //
      //
      //
      //
      //
      
         double cHigh  = iDSmooth(iMA(NULL,0,1,0,MODE_SMA,PRICE_HIGH,i),   PreSmooth,PreSmoothPhase,PreSmoothDouble,i,   0);
         double cLow   = iDSmooth(iMA(NULL,0,1,0,MODE_SMA,PRICE_LOW,i),    PreSmooth,PreSmoothPhase,PreSmoothDouble,i,  20);
         double cOpen  = iDSmooth(iMA(NULL,0,1,0,MODE_SMA,PRICE_OPEN,i),   PreSmooth,PreSmoothPhase,PreSmoothDouble,i,  40);
         double cClose = iDSmooth(iMA(NULL,0,1,0,MODE_SMA,PRICE_CLOSE,i),  PreSmooth,PreSmoothPhase,PreSmoothDouble,i,  60);
         double pClose = iDSmooth(iMA(NULL,0,1,0,MODE_SMA,PRICE_CLOSE,i+1),PreSmooth,PreSmoothPhase,PreSmoothDouble,i+1,80);
         
         
         double trueRange = MathMax(cHigh,pClose)-MathMin(cLow,pClose);
         double     range = cHigh-cLow;
         double       vqi = i<(Bars-1) ? 0 : Vqi[i+1];
      
            if (range != 0 && trueRange!=0) vqi = ((cClose-pClose)/trueRange + (cClose-cOpen)/range)*0.5;

         //
         //
         //
         //
         //
         
         Vqi[i]      = MathAbs(vqi)*(cClose-pClose+cClose-cOpen)*0.5;
         sumVqi[i]   = sumVqi[i+1]+Vqi[i];
            if (Filter > 0) if (MathAbs(sumVqi[i]-sumVqi[i+1]) < Filter*Point) sumVqi[i] = sumVqi[i+1];
      }
      for(int i=limit; i>=0; i--)
      {
         if (JMA1Period > 1) sumVqi1[i] = iDSmooth(sumVqi[i],JMA1Period,JMA1Phase,JMA1Double,i,100);
         if (JMA2Period > 1) sumVqi2[i] = iDSmooth(sumVqi[i],JMA2Period,JMA2Phase,JMA2Double,i,120);
         
         //
         //
         //
         //
         //
         
         sumVqida[i] = EMPTY_VALUE;
         sumVqidb[i] = EMPTY_VALUE;
         if (i<(Bars-1))
         {
            trend[i] = trend[i+1];
               if (sumVqi[i] > sumVqi2[i]) trend[i] =  1;
               if (sumVqi[i] < sumVqi2[i]) trend[i] = -1;
               if (trend[i] == 1) sumVqida[i] = 1;  
               if (trend[i] ==-1) sumVqidb[i] = 1; 
         }      
      }  
      manageAlerts();
      return(0);
   }
   
   //
   //
   //
   //
   //
  
   limit = (int)MathMax(limit,MathMin(Bars-1,iCustom(NULL,TimeFrame,indicatorFileName,-99,0,0)*TimeFrame/Period()));
   for (int i=limit;i>=0;i--)
   {
      int y = iBarShift(NULL,TimeFrame,Time[i]);
         sumVqida[i] = EMPTY_VALUE;
         sumVqidb[i] = EMPTY_VALUE;  
         trend[i]    = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,PreSmooth,PreSmoothPhase,PreSmoothDouble,JMA1Period,JMA1Phase,JMA1Double,JMA2Period,JMA2Phase,JMA2Double,Filter,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,alertsPush,6,y);     
         if (trend[i] == 1) sumVqida[i] = 1;  
         if (trend[i] ==-1) sumVqidb[i] = 1; 
   }
return(0);   
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double wrk[][140];

#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<2) { int k; for(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]);
            double dVolty = 0;   
            if (wrk[r][avolty+s] > 0)
               dVolty = wrk[r][volty+s]/wrk[r][avolty+s];
	               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 manageAlerts()
{
   if (alertsOn)
   {
      int whichBar = 1; if (alertsOnCurrent) whichBar = 0;
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar] ==  1) doAlert(whichBar,"up");
         if (trend[whichBar] == -1) doAlert(whichBar,"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()," ",timeFrameToString(_Period)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," VQ nrp changed direction to ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," VQ nrp "),message);
          if (alertsPush)    SendNotification(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};

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}