//------------------------------------------------------------------
#property copyright "mladen"
#property link      "www.forex-station.cm"
//------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 8
#property indicator_color1  clrLimeGreen
#property indicator_color2  clrPaleVioletRed
#property indicator_color3  clrLimeGreen
#property indicator_color4  clrPaleVioletRed
#property indicator_color5  clrLimeGreen
#property indicator_color6  clrPaleVioletRed
#property indicator_color7  clrLimeGreen
#property indicator_color8  clrPaleVioletRed
#property indicator_minimum 0
#property indicator_maximum 5

//
//
//
//
//

enum enMaTypes
{
   ma_sma,     // Simple moving average
   ma_ema,     // Exponential moving average
   ma_smma,    // Smoothed MA
   ma_lwma,    // Linear weighted MA
};

extern string         TimeFrame1            = "Current time frame";
extern string         TimeFrame2            = "next1";
extern string         TimeFrame3            = "next2";
extern string         TimeFrame4            = "next3";
extern int            PriceSmoothing        = 15;
extern enMaTypes      PriceSmoothingMethod  = ma_lwma;
input double          Filter                = 5.0;      
extern string         UniqueID              = "4 Time frame VQ zeroline";
extern int            LinesWidth            = 0;
extern color          LabelsColor           = clrDarkGray;
extern int            LabelsHorizontalShift = 5;
extern double         LabelsVerticalShift   = 1.5;
extern bool           alertsOn              = false;
extern int            alertsLevel           = 3;
extern bool           alertsMessage         = true;
extern bool           alertsSound           = false;
extern bool           alertsEmail           = false;
input bool            alertsNotify          = false;

//
//
//
//
//

double vq1u[];
double vq1d[];
double vq2u[];
double vq2d[];
double vq3u[];
double vq3d[];
double vq4u[];
double vq4d[];

int    timeFrames[4];
bool   returnBars;
bool   calculateValue;
string indicatorFileName;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   SetIndexBuffer(0,vq1u);
   SetIndexBuffer(1,vq1d);
   SetIndexBuffer(2,vq2u);
   SetIndexBuffer(3,vq2d);
   SetIndexBuffer(4,vq3u);
   SetIndexBuffer(5,vq3d);
   SetIndexBuffer(6,vq4u);
   SetIndexBuffer(7,vq4d);
      PriceSmoothing    = MathMax(PriceSmoothing,1);
      indicatorFileName = WindowExpertName();
      returnBars        = (TimeFrame1=="returnBars");     if (returnBars)     return(0);
      calculateValue    = (TimeFrame1=="calculateValue"); if (calculateValue) return(0);
      
      //
      //
      //
      //
      //
      
      for (int i=0; i<8; i++) 
      {
         SetIndexStyle(i,DRAW_ARROW,EMPTY,LinesWidth); SetIndexArrow(i,110); 
      }
      timeFrames[0] = stringToTimeFrame(TimeFrame1);
      timeFrames[1] = stringToTimeFrame(TimeFrame2);
      timeFrames[2] = stringToTimeFrame(TimeFrame3);
      timeFrames[3] = stringToTimeFrame(TimeFrame4);
      alertsLevel = MathMin(MathMax(alertsLevel,3),4);
      IndicatorShortName(UniqueID);
   return(0);
}
int deinit()
{
   for (int t=0; t<4; t++) ObjectDelete(UniqueID+t);
   return(0); 
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double trend[][2];
#define _up 0
#define _dn 1
int start()
{
   int i,r,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) { vq1u[0] = limit+1; return(0); }
         if (calculateValue) { calculateByIT(limit); return(0); }

         if (timeFrames[0] != Period()) limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrames[0],indicatorFileName,"returnBars",0,0)*timeFrames[0]/Period()));
         if (timeFrames[1] != Period()) limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrames[1],indicatorFileName,"returnBars",0,0)*timeFrames[1]/Period()));
         if (timeFrames[2] != Period()) limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrames[2],indicatorFileName,"returnBars",0,0)*timeFrames[2]/Period()));
         if (timeFrames[3] != Period()) limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrames[3],indicatorFileName,"returnBars",0,0)*timeFrames[3]/Period()));
         if (ArrayRange(trend,0)!=Bars) ArrayResize(trend,Bars);

         //
         //
         //
         //
         //
         
         bool initialized = false;
         if (!initialized)
         {
            initialized = true;
            int window = WindowFind(UniqueID);
            for (int t=0; t<4; t++)
            {
               string label = timeFrameToString(timeFrames[t]);
               ObjectCreate(UniqueID+t,OBJ_TEXT,window,0,0);
                  ObjectSet(UniqueID+t,OBJPROP_COLOR,LabelsColor);
                  ObjectSet(UniqueID+t,OBJPROP_PRICE1,t+LabelsVerticalShift);
                  ObjectSetText(UniqueID+t,label,8,"Arial");
            }               
         }
         for (t=0; t<4; t++) ObjectSet(UniqueID+t,OBJPROP_TIME1,Time[0]+Period()*LabelsHorizontalShift*60);

   //
   //
   //
   //
   //
    
   for(i = limit, r=Bars-i-1; i >= 0; i--,r++)
   {
      trend[r][_up] = 0;
      trend[r][_dn] = 0;
      for (int k=0; k<4; k++)
      {
         int y = iBarShift(NULL,timeFrames[k],Time[i]);
            double spanA = iCustom(NULL,timeFrames[k],indicatorFileName,"calculateValue","","","",PriceSmoothing,PriceSmoothingMethod,Filter,0,y);
            bool   isUp  = (spanA>0);
            switch (k)
            {
               case 0 : if (isUp) { vq1u[i] = k+1; vq1d[i] = EMPTY_VALUE;}  else { vq1d[i] = k+1; vq1u[i] = EMPTY_VALUE; } break;
               case 1 : if (isUp) { vq2u[i] = k+1; vq2d[i] = EMPTY_VALUE;}  else { vq2d[i] = k+1; vq2u[i] = EMPTY_VALUE; } break;
               case 2 : if (isUp) { vq3u[i] = k+1; vq3d[i] = EMPTY_VALUE;}  else { vq3d[i] = k+1; vq3u[i] = EMPTY_VALUE; } break;
               case 3 : if (isUp) { vq4u[i] = k+1; vq4d[i] = EMPTY_VALUE;}  else { vq4d[i] = k+1; vq4u[i] = EMPTY_VALUE; } break;
            }
            if (isUp)
                  trend[r][_up] += 1;
            else  trend[r][_dn] += 1;
      }
   }
   manageAlerts();
   return(0);
}


//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void calculateByIT(int limit)
{
    
    for (int i=limit; i>=0; i--) 
    {
      if (i==(Bars-1)) { vq3u[i] = 0; vq4u[i] = 0; continue; }
      
      //
      //
      //
      //
      //
  
         double cHigh  =              iCustomMa(PriceSmoothingMethod,High[i]   ,PriceSmoothing,i  ,Bars,0);
         double cLow   =              iCustomMa(PriceSmoothingMethod,Low[i]    ,PriceSmoothing,i  ,Bars,1);
         double cOpen  =              iCustomMa(PriceSmoothingMethod,Open[i]   ,PriceSmoothing,i  ,Bars,2);
         double cClose =              iCustomMa(PriceSmoothingMethod,Close[i]  ,PriceSmoothing,i  ,Bars,3);
         double pClose = (i<Bars-1) ? iCustomMa(PriceSmoothingMethod,Close[i+1],PriceSmoothing,i+1,Bars,4) : cClose;
         
         double trueRange = fmax(cHigh,pClose)-fmin(cLow,pClose);
         double range     = cHigh-cLow;
         double vqi       = (range != 0 && trueRange!=0) ? ((cClose-pClose)/trueRange + (cClose-cOpen)/range)*0.5 : (i<Bars-1) ? vq2u[i+1] : 0;

      //
      //
      //
      //
      //
      
      vq2u[i] = fabs(vqi)*(cClose-pClose+cClose-cOpen)*0.5;
      vq1u[i] = vq2u[i];
      if (Filter > 0 && i<Bars-1) if (fabs(vq1u[i]-vq1u[i+1]) < Filter*_Point) vq1u[i] = vq1u[i+1];
      vq4u[i] = (i<Bars-1) ? (vq1u[i]>0) ? 1 : (vq1u[i]<0) ? -1 : vq4u[i+1] : 0;  
   }
}

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

string getAverageName(int method)
{
      switch(method)
      {
         case ma_ema:    return("EMA");
         case ma_lwma:   return("LWMA");
         case ma_sma:    return("SMA");
         case ma_smma:   return("SMMA");
      }
return("");      
}

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

#define _maInstances 5
#define _maWorkBufferx1 1*_maInstances
#define _maWorkBufferx2 2*_maInstances
#define _maWorkBufferx3 3*_maInstances

double iCustomMa(int mode, double price, double length, int r, int bars, int instanceNo=0)
{
   r = bars-r-1;
   switch (mode)
   {
      case ma_sma   : return(iSma(price,(int)ceil(length),r,bars,instanceNo));
      case ma_ema   : return(iEma(price,length,r,bars,instanceNo));
      case ma_smma  : return(iSmma(price,(int)ceil(length),r,bars,instanceNo));
      case ma_lwma  : return(iLwma(price,(int)ceil(length),r,bars,instanceNo));
      default       : return(price);
   }
}

//
//
//
//
//

double workSma[][_maWorkBufferx1];
double iSma(double price, int period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workSma,0)!= _bars) ArrayResize(workSma,_bars);

   workSma[r][instanceNo+0] = price;
   double avg = price; int k=1;  for(; k<period && (r-k)>=0; k++) avg += workSma[r-k][instanceNo+0];  
   return(avg/(double)k);
}

//
//
//
//
//

double workEma[][_maWorkBufferx1];
double iEma(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workEma,0)!= _bars) ArrayResize(workEma,_bars);

   workEma[r][instanceNo] = price;
   if (r>0 && period>1)
          workEma[r][instanceNo] = workEma[r-1][instanceNo]+(2.0/(1.0+period))*(price-workEma[r-1][instanceNo]);
   return(workEma[r][instanceNo]);
}

//
//
//
//
//

double workSmma[][_maWorkBufferx1];
double iSmma(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workSmma,0)!= _bars) ArrayResize(workSmma,_bars);

   workSmma[r][instanceNo] = price;
   if (r>1 && period>1)
          workSmma[r][instanceNo] = workSmma[r-1][instanceNo]+(price-workSmma[r-1][instanceNo])/period;
   return(workSmma[r][instanceNo]);
}

//
//
//
//
//

double workLwma[][_maWorkBufferx1];
double iLwma(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workLwma,0)!= _bars) ArrayResize(workLwma,_bars);
   
   workLwma[r][instanceNo] = price; if (period<=1) return(price);
      double sumw = period;
      double sum  = period*price;

      for(int k=1; k<period && (r-k)>=0; k++)
      {
         double weight = period-k;
                sumw  += weight;
                sum   += weight*workLwma[r-k][instanceNo];  
      }             
      return(sum/sumw);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      int whichBar = Bars-1; 
      static datetime time1 = 0;
      static string   mess1 = "";
      if (trend[whichBar][_up]>=alertsLevel || trend[whichBar][_dn]>=alertsLevel)
      {
         if (trend[whichBar][_up] >= alertsLevel && trend[whichBar-1][_up]<alertsLevel) doAlert(time1,mess1,whichBar,"up",trend[whichBar][_up]);
         if (trend[whichBar][_dn] >= alertsLevel && trend[whichBar-1][_dn]<alertsLevel) doAlert(time1,mess1,whichBar,"down",trend[whichBar][_dn]);
      }              
    }         
}

//
//
//
//
//

void doAlert(datetime& previousTime, string& previousAlert, int forBar, string doWhat, int howMany)
{
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[forBar]) {
       previousAlert  = doWhat;
       previousTime   = Time[forBar];

       //
       //
       //
       //
       //

       message =  _Symbol+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" "+howMany+" time frames of VQ zeroline are aligned "+doWhat;
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(_Symbol+" 4 time frame VQ zeroline",message);
          if (alertsNotify)  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};

//
//
//
//
//

int toInt(double value) { return(value); }
int stringToTimeFrame(string tfs)
{
   tfs = stringUpperCase(tfs);
   int max = ArraySize(iTfTable)-1, add=0;
   int nxt = (StringFind(tfs,"NEXT1")>-1); if (nxt>0) { tfs = ""+Period(); add=1; }
       nxt = (StringFind(tfs,"NEXT2")>-1); if (nxt>0) { tfs = ""+Period(); add=2; }
       nxt = (StringFind(tfs,"NEXT3")>-1); if (nxt>0) { tfs = ""+Period(); add=3; }

      //
      //
      //
      //
      //
         
      for (int i=max; i>=0; i--)
         if (tfs==sTfTable[i] || tfs==""+iTfTable[i]) return(MathMax(iTfTable[toInt(MathMin(max,i+add))],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);
}