//+------------------------------------------------------------------+
//|                                               Advanced forecater |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 7
#property indicator_color1 Black//DarkGray
#property indicator_color2 Red//Orange
#property indicator_color3 Red//Orange
#property indicator_color4 Blue//LimeGreen
#property indicator_color5 Blue//LimeGreen
#property indicator_color6 Red//Orange
#property indicator_color7 Blue//Orange
#property indicator_width1 3
#property indicator_width2 3
#property indicator_width3 3
#property indicator_width4 3
#property indicator_width5 3
#property indicator_width6 2
#property indicator_width7 2

//
//
//
//
//

extern string TimeFrame    = "Current time frame";
extern int    FastEma      = 13;
extern int    SlowEma      = 34;
extern int    SignalMA     = 8;
extern int    SignalMAMode = MODE_EMA;
extern bool   alertsOn        = true;
extern bool   alertsOnCurrent = false;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = false;
extern bool   alertsEmail     = false;
extern bool   Interpolate     = true;

double temp1[];
double temp2[];
double sum[];
double sumua[];
double sumub[];
double sumda[];
double sumdb[];
double dotu[];
double dotd[];
double state[];

string indicatorFileName;
bool   returnBars;
int    timeFrame;

//------------------------------------------------------------------
//
//------------------------------------------------------------------

int init() 
{
   IndicatorBuffers(10);   
   SetIndexBuffer(0,sum);
   SetIndexBuffer(1,sumua);
   SetIndexBuffer(2,sumub);
   SetIndexBuffer(3,sumda);
   SetIndexBuffer(4,sumdb);
   SetIndexBuffer(5,dotu);  SetIndexStyle(5,DRAW_ARROW); SetIndexArrow(5,159);
   SetIndexBuffer(6,dotd);  SetIndexStyle(6,DRAW_ARROW); SetIndexArrow(6,159);
   SetIndexBuffer(7,temp1);
   SetIndexBuffer(8,temp2);
   SetIndexBuffer(9,state);
      timeFrame         = stringToTimeFrame(TimeFrame);
      indicatorFileName = WindowExpertName();
      returnBars        = (TimeFrame=="returnBars"); if (returnBars) return(0);
   IndicatorShortName(timeFrameToString(timeFrame)+" Advanced_forecater");
   return (0);
}

//
//
//
//
//

int start() 
{
   int countedBars = IndicatorCounted();
      if(countedBars<0) return(-1);
      if(countedBars>0) countedBars--;
         int i,limit = MathMin(Bars-countedBars,Bars-1);
            double Multiply_Factor_1 = 2.0 / (FastEma + 1.0);
            double Multiply_Factor_2 = 2.0 / (SlowEma + 1.0);
            double Multiply_Factor_3 = Multiply_Factor_1 - Multiply_Factor_2;
                  if (MathAbs(Multiply_Factor_3) == 0.0) return(0);
                  if (timeFrame!=Period())
                  {
                     limit = MathMax(limit,MathMin(Bars,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
                     if (state[limit]== 1) CleanPoint(limit,sumua,sumub);
                     if (state[limit]==-1) CleanPoint(limit,sumda,sumdb);
                        for(i=limit; i>=0; i--)
                        {
                           int y = iBarShift(NULL,timeFrame,Time[i]);
                           sum[i]   = iCustom(NULL,timeFrame,indicatorFileName,"",FastEma,SlowEma,SignalMA,SignalMAMode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,0,y);
                           state[i] = iCustom(NULL,timeFrame,indicatorFileName,"",FastEma,SlowEma,SignalMA,SignalMAMode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,9,y);
                           sumua[i] = EMPTY_VALUE;
                           sumub[i] = EMPTY_VALUE;
                           sumda[i] = EMPTY_VALUE;
                           sumdb[i] = EMPTY_VALUE;
                           dotd[i]  = EMPTY_VALUE;
                           dotu[i]  = EMPTY_VALUE;
                              if (state[i]!=state[i+1])
                              {
                                 if (state[i]== 1) dotu[i] = sum[i]+iATR(NULL,0,20,i)/2;
                                 if (state[i]==-1) dotd[i] = sum[i]-iATR(NULL,0,20,i)/2;
                              }
                           if (!Interpolate || (i>0 && y==iBarShift(NULL,timeFrame,Time[i-1]))) continue;
                           int n,l;
                           datetime time = iTime(NULL,timeFrame,y);
                              for(n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
                              for(l = 1; l < n && (i+l<Bars) && (i+n)<Bars; l++)
                                 sum[i+l] = sum[i] + (sum[i+n]-sum[i])*l/n;

                        }                           
                        for(i=limit; i>=0; i--)
                        {
                              if (state[i]== 1) PlotPoint(i,sumua,sumub,sum);
                              if (state[i]==-1) PlotPoint(i,sumda,sumdb,sum);
                        }                              
                        return(0);
                  }

   //
   //
   //
   //
   //
 
   if (state[limit]== 1) CleanPoint(limit,sumua,sumub);
   if (state[limit]==-1) CleanPoint(limit,sumda,sumdb);
   for(i=limit; i>=0; i--) temp1[i] = iMA(NULL,0,FastEma,0,MODE_EMA, PRICE_CLOSE,i)-iMA(NULL,0,SlowEma,0,MODE_EMA,PRICE_CLOSE,i);
   for(i=limit; i>=0; i--) temp2[i] = iMAOnArray(temp1,0,SignalMA,0,SignalMAMode,i);
   for(i=limit; i>=0; i--)
   {
      sumua[i] = EMPTY_VALUE;
      sumub[i] = EMPTY_VALUE;
      sumda[i] = EMPTY_VALUE;
      sumdb[i] = EMPTY_VALUE;
      dotd[i]  = EMPTY_VALUE;
      dotu[i]  = EMPTY_VALUE;
      sum[i] = (Multiply_Factor_1 * iMA(NULL,0,FastEma,0,MODE_EMA,PRICE_CLOSE,i)+                  iMA(NULL,0,SlowEma,0,MODE_EMA,PRICE_CLOSE,i) - 
                                    iMA(NULL,0,FastEma,0,MODE_EMA,PRICE_CLOSE,i)-Multiply_Factor_2*iMA(NULL,0,SlowEma,0,MODE_EMA,PRICE_CLOSE,i) + temp2[i]) / Multiply_Factor_3;
      state[i] = 0;
      if (sum[i]>High[i]) state[i] =  1;
      if (sum[i]<Low[i])  state[i] = -1;
      if (state[i]== 1) PlotPoint(i,sumua,sumub,sum);
      if (state[i]==-1) PlotPoint(i,sumda,sumdb,sum);
      if (state[i]!=state[i+1])
      {
         if (state[i]== 1) dotu[i] = sum[i]+iATR(NULL,0,20,i)/2;
         if (state[i]==-1) dotd[i] = sum[i]-iATR(NULL,0,20,i)/2;
      }
   }
   manageAlerts();
   return (0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//

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 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);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   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 (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;
      }
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1;
      if (state[whichBar]!=state[whichBar+1])
      {
         if (state[whichBar] ==  1) doAlert(whichBar,"down");
         if (state[whichBar] == -1) doAlert(whichBar,"up");
      }         
   }
}

//
//
//
//
//

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()," "+timeFrameToString(Period())+" at ",TimeToStr(TimeLocal(),TIME_SECONDS)," Advanced forecaster trend changeed to ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," Advanced forecaster "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}