//+------------------------------------------------------------------+
//|                                           Volatility quality.mq4 |
//|                                                                  |
//|                                                                  |
//| Volatility quality index originaly developed by                  |
//| Thomas Stridsman (August 2002 Active Trader Magazine)            |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "www.forex-station.com"

#property indicator_separate_window
#property indicator_buffers    3
#property indicator_color1     LimeGreen
#property indicator_color2     Red
#property indicator_color3     Red
#property indicator_width1     2
#property indicator_width2     2
#property indicator_width3     2
#property indicator_level1     0
#property indicator_levelcolor DarkGray

//
//
//
//
//

extern string         TimeFrame            = "Current time frame";
extern int            PriceSmoothing       = 15;
extern ENUM_MA_METHOD PriceSmoothingMethod = MODE_LWMA;
extern double         Filter               = 5;
extern bool           alertsOn             = false;
extern bool           alertsOnCurrent      = true;
extern bool           alertsMessage        = true;
extern bool           alertsPushNotif      = false;
extern bool           alertsSound          = false;
extern bool           alertsEmail          = false;
extern string         soundFile            = "alert2.wav";

//
//
//
//
//

double sumVqi[];
double sumVqida[];
double sumVqidb[];
double Vqi[];
double trend[];

string indicatorFileName;
bool   returnBars;
int    timeFrame;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(5);
      SetIndexBuffer(0,sumVqi); 
      SetIndexBuffer(1,sumVqida); 
      SetIndexBuffer(2,sumVqidb); 
      SetIndexBuffer(3,Vqi);   
      SetIndexBuffer(4,trend); 
      
      //
      //
      //
      //
      //
         
      PriceSmoothing    = MathMax(PriceSmoothing,1);
      timeFrame         = stringToTimeFrame(TimeFrame);
      indicatorFileName = WindowExpertName();
      returnBars        = TimeFrame=="returnBars"; 
      
      //
      //
      //
      //
      //
      
      IndicatorShortName(timeFrameToString(timeFrame)+" Volatility quality");
      return(0);
}
int deinit() { return(0); }

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
   int i,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
         limit = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { sumVqi[0] = MathMin(limit+1,Bars-1); return(0); }

   //
   //
   //
   //
   //

   if (timeFrame == Period())
   {     
     if (trend[limit] == -1) CleanPoint(limit,sumVqida,sumVqidb);
     for(i=limit; i>=0; i--)
     {
        if (i==(Bars-1)) { Vqi[i] = 0; sumVqi[i] = 0; continue; }

        double cHigh  = iMA(NULL,0,PriceSmoothing,0,PriceSmoothingMethod,PRICE_HIGH ,i);
        double cLow   = iMA(NULL,0,PriceSmoothing,0,PriceSmoothingMethod,PRICE_LOW  ,i);
        double cOpen  = iMA(NULL,0,PriceSmoothing,0,PriceSmoothingMethod,PRICE_OPEN ,i);
        double cClose = iMA(NULL,0,PriceSmoothing,0,PriceSmoothingMethod,PRICE_CLOSE,i);
        double pClose = iMA(NULL,0,PriceSmoothing,0,PriceSmoothingMethod,PRICE_CLOSE,i+1);

        double trueRange = MathMax(cHigh,pClose)-MathMin(cLow,pClose);
        double     range = cHigh-cLow;
      
        if (range != 0 && trueRange!=0)
           double vqi = ((cClose-pClose)/trueRange + (cClose-cOpen)/range)*0.5;
        else      vqi = Vqi[i+1];

        //
        //
        //
        //
        //
         
        Vqi[i]      = MathAbs(vqi)*(cClose-pClose+cClose-cOpen)*0.5;
        sumVqi[i]   = Vqi[i];
        sumVqida[i] = EMPTY_VALUE;
        sumVqidb[i] = EMPTY_VALUE;
           if (Filter > 0) if (MathAbs(sumVqi[i]-sumVqi[i+1]) < Filter*Point) sumVqi[i] = sumVqi[i+1];
      
         //
         //
         //
         //
         //
      
         trend[i] = trend[i+1];
            if (sumVqi[i] > 0) trend[i] =  1;
            if (sumVqi[i] < 0) trend[i] = -1;
            if (trend[i] == -1) PlotPoint(i,sumVqida,sumVqidb,sumVqi);
      }
      manageAlerts();
      return(0);
   }      

   //
   //
   //
   //
   //

   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   if (trend[limit] == -1) CleanPoint(limit,sumVqida,sumVqidb);
   for (i=limit; i>=0; i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         trend[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",PriceSmoothing,PriceSmoothingMethod,Filter,alertsOn,alertsOnCurrent,alertsMessage,alertsPushNotif,alertsSound,alertsEmail,soundFile,4,y);
         sumVqi[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",PriceSmoothing,PriceSmoothingMethod,Filter,alertsOn,alertsOnCurrent,alertsMessage,alertsPushNotif,alertsSound,alertsEmail,soundFile,0,y);
         sumVqida[i] = EMPTY_VALUE;
         sumVqidb[i] = EMPTY_VALUE;
         if (trend[i]==-1) PlotPoint(i,sumVqida,sumVqidb,sumVqi);
   }
   return(0);
}

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   if (i>=Bars-3) return;
   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 (i>=Bars-2) return;
   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; }
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

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)
{
   StringToUpper(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("");
}


//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; 
      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()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," - ",timeFrameToString(timeFrame)+" VQ trend changed to ",doWhat);
          if (alertsMessage)   Alert(message);
          if (alertsEmail)     SendMail(StringConcatenate(Symbol()," VQ "),message);
          if (alertsPushNotif) SendNotification(StringConcatenate(Symbol(), " VQ "+" "+message)); 
          if (alertsSound)     PlaySound(soundFile);
   }
}