//+------------------------------------------------------------------+
//|                                           Volatility quality.mq4 |
//|                                                                  |
//|                                                                  |
//| Volatility quality index originaly developed by                  |
//| Thomas Stridsman (August 2002 Active Trader Magazine)            |
//+------------------------------------------------------------------+
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"

#property indicator_separate_window
#property indicator_buffers 2
#property indicator_color1  DodgerBlue
#property indicator_color2  Orange
#property indicator_minimum 0
#property indicator_maximum 1
#property indicator_width1  4
#property indicator_width2  4

//
//
//
// 15/5/3/1
// 15/5/3/3 = better!

extern string TimeFrame            = "5";
extern int    PriceSmoothing       = 5;
extern int    PriceSmoothingMethod = 3;
extern double Filter               = 3;

extern bool   alertsOn             = 1;
extern bool   alertsOnCurrent      = 1;
extern bool   alertsMessage        = 1;
extern bool   alertsSound          = 1;
 bool   alertsEmail          = false;

//
//
//
//
//

double sumVqi[];
double sumVqida[];
double sumVqidb[];
double Vqi[];
double trend[];

//
//
//
//
//

string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(5);
      SetIndexBuffer(0,sumVqida); SetIndexStyle(0,DRAW_HISTOGRAM);
      SetIndexBuffer(1,sumVqidb); SetIndexStyle(1,DRAW_HISTOGRAM);
      SetIndexBuffer(2,sumVqi); 
      SetIndexBuffer(3,Vqi);   
      SetIndexBuffer(4,trend); 
      
     //
     //
     //
     //
     //
     
         PriceSmoothing    =  MathMax(PriceSmoothing,1);
         indicatorFileName = WindowExpertName();
         calculateValue    = TimeFrame=="calculateValue"; if (calculateValue) { return(0); }
         returnBars        = TimeFrame=="returnBars";     if (returnBars)     { return(0); }
         timeFrame         = stringToTimeFrame(TimeFrame);
      
      //
      //
      //
      //
      //
   
   IndicatorShortName(timeFrameToString(timeFrame)+" Volatility zero line");
   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) { sumVqida[0] = limit+1; return(0); }

   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame == Period())
   {
   
    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) sumVqida[i] = 1;  
         if (trend[i] ==-1) sumVqidb[i] = 1;  
   }
    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]);
         sumVqida[i] = EMPTY_VALUE;
         sumVqidb[i] = EMPTY_VALUE;
         trend[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",PriceSmoothing,PriceSmoothingMethod,Filter,4,y);
         
         if (trend[i] == 1) sumVqida[i] = 1;  
         if (trend[i] ==-1) sumVqidb[i] = 1; 
    }
    manageAlerts();
return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+  
//
//
//
//
//

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,"up");
         else  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)," VQ zero direction changed to ",doWhat);
             if (alertsMessage) Alert(message); 
             //Alert("["+Symbol()+"] [M"+Period()+"] #Brutal Insanity V2: (Going DOWN) // #PUT");
             if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"VQ zero "),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);
} 
   
//
//
//
//
//


