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

//
//
//
//
//

extern ENUM_TIMEFRAMES TimeFrame      = PERIOD_CURRENT;
extern ENUM_APPLIED_PRICE Price       = PRICE_CLOSE;
extern int             FastEma        = 13;
extern int             SlowEma        = 34;
extern int             SignalMA       = 8;
extern ENUM_MA_METHOD  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   alertsPush             = false;
extern bool   ShowText               = true;
extern string TextDir                = "advanced forecaster Text";
extern int    textCorner             = 1;
extern int    textXPosition          = 10;
extern int    textYPosition          = 10;
extern color  upTextColor            = Blue;
extern color  dnTextColor            = Red;
extern int    upFontSize             = 12;
extern int    dnFontSize             = 12;   
extern bool   verticalLinesVisible   = false;
extern bool   linesOnFirst           = true;
extern string verticalLinesID        = "advanced forecaster Lines";
extern color  verticalLinesUpColor   = DeepSkyBlue;
extern color  verticalLinesDnColor   = PaleVioletRed;
extern int    verticalLinesStyle     = STYLE_DOT;
extern int    verticalLinesWidth     = 0;
extern bool   Interpolate            = true;

extern bool   drawArrows             = false;//true; 
extern bool   ArrowsOnFirstBar       = false;//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 init() 
{
   IndicatorBuffers(10);   
   SetIndexBuffer(0,sum);
   SetIndexBuffer(1,sumua);
   SetIndexBuffer(2,sumub);
   SetIndexBuffer(3,sumda);
   SetIndexBuffer(4,sumdb);
   SetIndexBuffer(5,dotu);  if (drawArrows) { SetIndexStyle(5,DRAW_ARROW); SetIndexArrow(5,234); } else SetIndexStyle(5,DRAW_NONE);
   SetIndexBuffer(6,dotd);  if (drawArrows) { SetIndexStyle(6,DRAW_ARROW); SetIndexArrow(6,233); } else SetIndexStyle(6,DRAW_NONE);
   SetIndexBuffer(7,temp1);
   SetIndexBuffer(8,temp2);
   SetIndexBuffer(9,state);
      indicatorFileName = WindowExpertName();
      returnBars        = (TimeFrame==-99);
      TimeFrame         = MathMax(TimeFrame,_Period);
   IndicatorShortName(timeFrameToString(TimeFrame)+" Advanced_forecater");
   return (0);
}
int deinit() 
{  
   ObjectDelete(TextDir);
   deleteLines();
return(0); 
}

//
//
//
//
//

int start() 
{
   int countedBars = IndicatorCounted();
      if(countedBars<0) return(-1);
      if(countedBars>0) countedBars--;
         int i,limit = MathMin(Bars-countedBars,Bars-1);
            if (returnBars) { sum[0] = limit+1; return(0); }
            if (TimeFrame!=Period())
            {
                     int shift = -1; if (ArrowsOnFirstBar) shift=1;
                     limit = MathMax(limit,MathMin(Bars,iCustom(NULL,TimeFrame,indicatorFileName,-99,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]);
                           int x = iBarShift(NULL,TimeFrame,Time[i+shift]);
                           sum[i]   = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,Price,FastEma,SlowEma,SignalMA,SignalMAMode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,ShowText,TextDir,textCorner,textXPosition,textYPosition,upTextColor,dnTextColor,upFontSize,dnFontSize,verticalLinesVisible,linesOnFirst,verticalLinesID,verticalLinesUpColor,verticalLinesDnColor,verticalLinesStyle,verticalLinesWidth,0,y);
                           state[i] = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,Price,FastEma,SlowEma,SignalMA,SignalMAMode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,ShowText,TextDir,textCorner,textXPosition,textYPosition,upTextColor,dnTextColor,upFontSize,dnFontSize,verticalLinesVisible,linesOnFirst,verticalLinesID,verticalLinesUpColor,verticalLinesDnColor,verticalLinesStyle,verticalLinesWidth,9,y);
                           sumua[i] = EMPTY_VALUE;
                           sumub[i] = EMPTY_VALUE;
                           sumda[i] = EMPTY_VALUE;
                           sumdb[i] = EMPTY_VALUE;
                        if(x!=y)
                        {
                           dotu[i]  = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,Price,FastEma,SlowEma,SignalMA,SignalMAMode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,ShowText,TextDir,textCorner,textXPosition,textYPosition,upTextColor,dnTextColor,upFontSize,dnFontSize,verticalLinesVisible,linesOnFirst,verticalLinesID,verticalLinesUpColor,verticalLinesDnColor,verticalLinesStyle,verticalLinesWidth,5,y);
                           dotd[i]  = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,Price,FastEma,SlowEma,SignalMA,SignalMAMode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,ShowText,TextDir,textCorner,textXPosition,textYPosition,upTextColor,dnTextColor,upFontSize,dnFontSize,verticalLinesVisible,linesOnFirst,verticalLinesID,verticalLinesUpColor,verticalLinesDnColor,verticalLinesStyle,verticalLinesWidth,6,y);
                        }
                        else
                        {
                           dotu[i]  = EMPTY_VALUE;
                           dotd[i]  = EMPTY_VALUE;
                        }
                        
                           //
                           //
                           //
                           //
                           //
                        
                           if (!Interpolate || (i>0 && y==iBarShift(NULL,TimeFrame,Time[i-1]))) continue;
                           
                           //
                           //
                           //
                           //
                           //
                           
                           datetime time = iTime(NULL,TimeFrame,y);
                              for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
                              for(int 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);
            }

   //
   //
   //
   //
   //

   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 (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,i)-iMA(NULL,0,SlowEma,0,MODE_EMA,Price,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;
      dotu[i]  = EMPTY_VALUE;
      dotd[i]  = EMPTY_VALUE;
      sum[i]   = (Multiply_Factor_1 * iMA(NULL,0,FastEma,0,MODE_EMA,Price,i)+iMA(NULL,0,SlowEma,0,MODE_EMA,Price,i) - 
                                      iMA(NULL,0,FastEma,0,MODE_EMA,Price,i)-Multiply_Factor_2*iMA(NULL,0,SlowEma,0,MODE_EMA,Price,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;   
         }
         
         //
         //
         //
         //
         //
         
         if (verticalLinesVisible)
         {
           deleteLine(Time[i]);
           if (state[i]!= state[i+1])
           {
                if (state[i] == 1) drawLine(i,verticalLinesDnColor);
                if (state[i] ==-1) drawLine(i,verticalLinesUpColor);
           }
         }      
   }
   if (state[0] ==  1) Commenter(-1);
   if (state[0] == -1) Commenter( 1);
   manageAlerts();
   return (0);
}

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

string sTfTable[] = {"M1","M5","M10","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,10,15,30,60,240,1440,10080,43200};

string timeFrameToString(int tf) {
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}

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

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 (alertsPush)    SendNotification(message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//
//
//
//
//

void drawLine(int i,color theColor)
{
      string name = verticalLinesID+":"+Time[i];
   
      //
      //
      //
      //
      //
      
      int add = 0; if (!linesOnFirst) add = _Period*60-1;
      ObjectCreate(name,OBJ_VLINE,0,Time[i]+add,0);
         ObjectSet(name,OBJPROP_COLOR,theColor);
         ObjectSet(name,OBJPROP_STYLE,verticalLinesStyle);
         ObjectSet(name,OBJPROP_WIDTH,verticalLinesWidth);
         ObjectSet(name,OBJPROP_BACK,true);
}

//
//
//
//
//

void deleteLines()
{
   string lookFor       = verticalLinesID+":";
   int    lookForLength = StringLen(lookFor);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
}

//
//
//
//
//

void deleteLine(datetime time)
{
   string lookFor = verticalLinesID+":"+time; ObjectDelete(lookFor);
}

//
//
//
//
//

void Commenter(int Dir) 
{
    if (ShowText)
    {
      ObjectCreate(TextDir,OBJ_LABEL,0,0,0);
         ObjectSet(TextDir,OBJPROP_CORNER,textCorner);
         ObjectSet(TextDir,OBJPROP_XDISTANCE,textXPosition);
         ObjectSet(TextDir,OBJPROP_YDISTANCE,textYPosition);
         if (Dir == 1) ObjectSetText(TextDir, "Buy signal", upFontSize,"Arial Black",upTextColor);
         if (Dir ==-1) ObjectSetText(TextDir, "Sell signal",dnFontSize,"Arial Black",dnTextColor);
    }
   
return; 
}