//+------------------------------------------------------------------+
//|   TVI_2color.mq4
//+------------------------------------------------------------------+
#property indicator_separate_window
#include <stdlib.mqh>
#property indicator_buffers 2
#property indicator_color1 Green
#property indicator_color2 Red
#property indicator_level1 0.00
#property indicator_levelcolor Black

extern int r=8;
extern int s=8;
extern int u=5;
extern bool SendAlert = true;
extern int CountBars=300;

double ev=EMPTY_VALUE;
bool AlertDone = false;
 
double Up[];
double Dn[];

double TVI[];
double Trend[];

int init()
{
   IndicatorBuffers(2);
   
   SetIndexStyle(0,DRAW_LINE,0,2);
   SetIndexBuffer(0,Up);
   SetIndexLabel(0,"Up");

   SetIndexStyle(1,DRAW_LINE,0,2);
   SetIndexBuffer(1,Dn);
   SetIndexLabel(1,"Dn");

   ArraySetAsSeries(TVI,true);
   ArraySetAsSeries(Trend,true);

   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
   if(CountBars>Bars-1) int limit = Bars-1; else limit =CountBars;
   //int limit = Bars-counted_bars;
   
   for (int i=limit;i>=0;i--)
   {
      ArrayResize(TVI,Bars);   
      ArrayResize(Trend,Bars);   

      Trend[i] = Trend[i+1];
      
      TVI[i] = iCustom(NULL,0,"TVI",r,s,u,0,i);
      
      if (TVI[i] > TVI[i+1])
      {Trend[i] = 1;}
      else
      if (TVI[i] < TVI[i+1])
      {Trend[i] = -1;}
      
      if (Trend[i] > 0)
      {
         Up[i] = TVI[i];
         
         if (Trend[i+1] < 0)
         {
            Up[i+1] = TVI[i+1];
         }
         Dn[i] = ev;   
      }
      else
      if (Trend[i] < 0)
      {
         Dn[i] = TVI[i];
         
         if (Trend[i+1] > 0)
         {
            Dn[i+1] = TVI[i+1];
         }
         Up[i] = ev;   
      }
      DoAlerts(i);
   }
}

void DoAlerts(int i)
{
   if (SendAlert && i == 0)
   {
      if (Trend[i+1] != Trend[i+2])
      {
         if (AlertDone == false)
         {
            AlertDone = true;      
            if (Trend[i+1] > 0)
            {
               Alert("TVI Up"," on ",Symbol(), " TF " + Period());
            }               
            else
            {
               Alert("TVI Down"," on ",Symbol(), " TF "+Period());
            } 
            SendMail("MA cross Alert", "alert");            
            PlaySound("Alert.wav");
         }   
      }
      else
      {AlertDone = false;}
   }
}
//+------------------------------------------------------------------+