//+------------------------------------------------------------------+
//|   TVI_Candles.mq4
//+------------------------------------------------------------------+
#property indicator_chart_window
#include <stdlib.mqh>
#property indicator_buffers 3

extern color UpColor = Green;
extern color DnColor = Red;
extern int CandleWidth = 5;
extern int r = 8;
extern int s = 8;
extern int u = 5;
extern bool SendAlert = false;
extern bool SendEmail = false;

double MyPoint,TVI1,TVI2,ev=EMPTY_VALUE;
bool AlertDone = false;

double Up[];
double Dn[];
double Trend[];

int init()
{
   SetIndexStyle(0,DRAW_HISTOGRAM,0,CandleWidth,UpColor);
   SetIndexBuffer(0,Up);

   SetIndexStyle(1,DRAW_HISTOGRAM,0,CandleWidth,DnColor);
   SetIndexBuffer(1,Dn);

   SetIndexStyle(2,DRAW_NONE);
   SetIndexBuffer(2,Trend);

   return(0);
}

int deinit()
{
   return(0);
}

int start()
{
   int counted_bars=IndicatorCounted();
   if(counted_bars<0) return(-1); //---- check for possible errors
   if(counted_bars>0) counted_bars--; //---- last counted bar will be recounted
   int limit = Bars-counted_bars;

   for(int i=limit;i>=0;i--)
   {
      Up[i] = ev;
      Dn[i] = ev;

      TVI1 = iCustom(NULL,0,"TVI",r,s,u,0,i);
      TVI2 = iCustom(NULL,0,"TVI",r,s,u,0,i+1);

      if (TVI1 > TVI2)
      {Trend[i] = 1;}

      if (TVI1 < TVI2)
      {Trend[i] = -1;}

      if (Trend[i] == 1 && Close[i] > Open[i])
      {
         Up[i] = MathMax(Open[i],Close[i]);
         Dn[i] = MathMin(Open[i],Close[i]);
      }

      if (Trend[i] == -1 && Close[i] < Open[i])
      {
         Dn[i] = MathMax(Open[i],Close[i]);
         Up[i] = MathMin(Open[i],Close[i]);
      }
      DoAlerts(i);
   }

   return(0);
}

void DoAlerts(int i)
{
   if (SendAlert && i == 0)
   {
      if (AlertDone == false)
      {
         if (Trend[i] > Trend[i+1])
         {
            AlertDone = true;      
            Alert("TVI Up ",Symbol());
            PlaySound("Alert.wav");
            if (SendEmail)
            {SendMail("TVI Up ",Symbol());}
         }
         else
         if (Trend[i] < Trend[i+1])
         {
            AlertDone = true;      
            Alert("TVI Down ",Symbol());
            PlaySound("Alert.wav");
            if (SendEmail)
            {SendMail("TVI Down ",Symbol());}
         }
         else
         {AlertDone = false;}
      }
   }
}

