//+------------------------------------------------------------------+
//|                                       ForexTSD_Calendar_v1.4.mq4 |
//|                                  Copyright © 2007, Forex-TSD.com |
//|                         Written by IgorAD,igorad2003@yahoo.co.uk |   
//|            http://finance.groups.yahoo.com/group/TrendLaboratory |                                      
//+------------------------------------------------------------------+
#property copyright "Copyright © 2007, Forex-TSD.com "
#property link      "http://www.forex-tsd.com/"

#include <WebGet.mqh>

#property indicator_chart_window

extern string     CalendarName     = "ForexTSD";
extern int        CalendarID       =       4; // Calendar's ID on calendar.forex-tsd.com  
extern bool       UseStartDate     =    true; //false; 
extern datetime   StartDate        = D'2011.02.21';      
extern bool       AlertMode        =    true; //false;
extern int        AlertTimeGap     =      15; // Time Gap between News Time and Alert Time in min 
extern bool       DisplayLine      =    true; // Display Line Option (Visualization mode) 
extern bool       DisplayText      =    true; // Display Text Option (Visualization mode)

extern string     cFilter          = " Currency Filter ";
extern bool       USD              =    true;
extern bool       EUR              =    true;
extern bool       GBP              =    true;
extern bool       JPY              =    true;
extern bool       AUD              =    true;
extern bool       CAD              =    true;
extern bool       CHF              =    true;
extern bool       NZD              =    true;

extern string     rFilter          = " Rating Filter ";
extern int        MaxRating        =       3;
extern int        MinRating        =       1;  

string   sDate[1000];          // Date
string   sTime[1000];          // Time
string   sCurrency[1000];      // Currency
string   sDescription[1000];   // Description
string   sRating[1000];        // Rating
string   sActual[1000];        // Actual value
string   sForecast[1000];      // Forecast value
string   sPrevious[1000];      // Previous value
string   sImpact[1000];
datetime dt[1000];    
int      NewsNum;
bool     fTime;
datetime prevTime, nTime, OpenTime;
int      TimeZone;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
//---- indicators
   fTime = true;
//----
   return(0);
  }
//-----
void ReadnPlotCalendar(string fName)
{    
   int i,handle;
   bool rates=false;
     
   handle=FileOpen(fName,FILE_CSV|FILE_READ,';');
      if(handle<1)
      {
      Print("File not found ", GetLastError());
      return(false);
      }
   i=0;
   while(!FileIsEnding(handle))
   {
   sDate[i]=FileReadString(handle);          
   sTime[i]=FileReadString(handle);         
   sCurrency[i]=FileReadString(handle);      
   sDescription[i]=FileReadString(handle);   
   sRating[i]=FileReadString(handle);        
   sActual[i]=FileReadString(handle);       
   sForecast[i]=FileReadString(handle);      
   sPrevious[i]=FileReadString(handle);                
   
   int rating = StrToInteger(sRating[i]);
   //Print("i=   ",i,  ",  rating=   ", rating);
   
   rates = rating <= MaxRating && rating >= MinRating;
      
   if(!rates) continue;  
   
   if ((sCurrency[i] == "USD") && (!USD)) continue;            
   if ((sCurrency[i] == "EUR") && (!EUR)) continue;            
   if ((sCurrency[i] == "GBP") && (!GBP)) continue;                      
   if ((sCurrency[i] == "JPY") && (!JPY)) continue;
   if ((sCurrency[i] == "AUD") && (!AUD)) continue;
   if ((sCurrency[i] == "CAD") && (!CAD)) continue;                     
   if ((sCurrency[i] == "CHF") && (!CHF)) continue;  
   if ((sCurrency[i] == "NZD") && (!NZD)) continue;   
      
   dt[i] = StrToTime(sDate[i]+" "+sTime[i])+TimeZone*3600;
   if(rating == 3) sImpact[i] = "High";
   if(rating == 2) sImpact[i] = "Medium";
   if(rating == 1) sImpact[i] = "Low";
   //Print("i=   ",i,  ",  sImpact[i]   ", sImpact[i]);
   
   string info = i+"_"+TimeToStr(dt[i])+" "+sCurrency[i]+" "+" "+sDescription[i]+" "+sImpact[i]+"  ";
   
   
   color c=Yellow ;
   
   if (sCurrency[i] == "USD") c = Blue;  
   if (sCurrency[i] == "EUR") c = Pink; 
   if (sCurrency[i] == "GBP") c = Red;
   if (sCurrency[i] == "JPY") c = Orange;            
   if (sCurrency[i] == "AUD") c = Green;       
   if (sCurrency[i] == "CAD") c = Gray;
   if (sCurrency[i] == "CHF") c = Green;
   if (sCurrency[i] == "NZD") c = Lime;  
      
      if (DisplayText)
      {
      ObjectCreate("TSDT"+i, OBJ_TEXT, 0, dt[i], Close[0]);
      ObjectSet("TSDT"+i, OBJPROP_COLOR, c);          
      ObjectSetText("TSDT"+i,sCurrency[i] + " " + sDescription[i] + " ",8);          
      ObjectSet("TSDT"+i, OBJPROP_ANGLE, 90);          
      }
          
      if (DisplayLine)
      {         
      ObjectCreate("TSDL"+i, OBJ_VLINE, 0, dt[i], Close[0]);
      ObjectSet("TSDL"+i, OBJPROP_COLOR, c);                    
      ObjectSet("TSDL"+i, OBJPROP_STYLE, STYLE_DOT);                    
      ObjectSet("TSDL"+i, OBJPROP_BACK, true);          
      ObjectSetText("TSDL"+i,sDescription[i] + " · ",8);          
      }
      
   i++;
   }
   NewsNum = i;
   
return(0);
}

//----
void ObjDel()
{
   int _GetLastError;
   if(DisplayLine && DisplayText) int obtotal = 0.5*ObjectsTotal(); else obtotal = ObjectsTotal();
   for ( int i = 0; i < obtotal; i ++ )
   {
      if (DisplayLine)
      if ( !ObjectDelete( StringConcatenate( "TSDL", i ) ) )
      {
      _GetLastError = GetLastError();
      //Print( "ObjectDelete( \"", StringConcatenate( "TSDL", i ),"\" ) - Error #", _GetLastError );
      }
      
      if (DisplayText)
      if( !ObjectDelete( StringConcatenate( "TSDT", i ) ) )
      {
      _GetLastError = GetLastError();
      //Print( "ObjectDelete( \"", StringConcatenate( "TSDT", i ),"\" ) - Error #", _GetLastError );
      }
   }
}

string ForexTSD_Calendar()
{
   if(!UseStartDate)
   datetime StartWeek = iTime(NULL,PERIOD_W1,0);
   else 
   StartWeek = StartDate;
   
   string StartYear  = TimeYear (StartWeek);
   if (TimeMonth(StartWeek)>9) string StartMonth = TimeMonth(StartWeek);
   else StartMonth = "0" + TimeMonth(StartWeek);
   if (TimeDay(StartWeek)>9) string StartDay   = TimeDay(StartWeek);
   else StartDay = "0" + TimeDay(StartWeek);
   
   string StartTime = StartYear + StartMonth + StartDay;  
      
   string WebAdress = "http://calendar.forex-tsd.com/calendar.php?csv=1&date="+StartTime+"&calendar[]="+CalendarID;
   string result = forextsd_com_webget(WebAdress);
      
   if(result != "") 
   {
   string CalName = "ForexTSD_"+StartYear+"-"+StartMonth+"-"+StartDay+".csv";
   
   Print(CalName," is OK");
   
   int handle=FileOpen(CalName,FILE_CSV|FILE_WRITE,';');
         
      if(handle>0)
      {
      FileWrite(handle, result);
      FileClose(handle);
      }
   }
   else CalName = "";
  
   return(CalName);   
}

void ChartComment()
{
   string sComment   = "";
   string sp         = "---------------------------------------------------\n";
   string NL         = "\n";
   
   for (int i=0; i<=NewsNum-1; i++)
   { 
      if(TimeCurrent()> dt[i-1] && TimeCurrent() <= dt[i])
      {
      OpenTime = dt[i];
      string upcomNews = sCurrency[i]+" "+sDescription[i]+"  Impact= " + sImpact[i]; 
      string upcomTime = TimeToStr(dt[i]);  
         
         if (i-1 >= 0)
         {
         string prevNews = sCurrency[i-1]+" "+sDescription[i-1]+"  Impact= " + sImpact[i-1]; 
         string prevTime = TimeToStr(dt[i-1]);
         }
      }
      
      if(OpenTime > 0 && OpenTime < dt[i])
      {
      string nextNews = sCurrency[i]+" "+sDescription[i]+"  Impact= " + sImpact[i];
      string nextTime = TimeToStr(dt[i]);
      break;
      }
   }
      
   sComment = sp;
   sComment = sComment+"ForexTSD Calendar:"+NL;
   
   if(TimeZone >= 0)
   sComment = sComment+"Broker\'s Time Zone : GMT + " + TimeZone + NL;
   else
   sComment = sComment+"Broker\'s Time Zone : GMT - " + MathAbs(TimeZone) + NL;
   
   sComment = sComment+"NEWS :" + NL;
   sComment = sComment+"Previous  = " + prevTime  +" "+prevNews  + NL;
   sComment = sComment+"Upcoming = " + upcomTime +" "+upcomNews + NL;
   sComment = sComment+"Next         = " + nextTime +" "+nextNews + NL;
   sComment = sComment+sp;
  
   Comment(sComment);
}      

bool TimeToAlert()
{
   bool result = false;
   for (int i=0; i<=NewsNum; i++)
   { 
   datetime AlertTime = dt[i] - AlertTimeGap*60;
   
      if((TimeCurrent()>= AlertTime && TimeCurrent() <= AlertTime + 60))
      {result=true; break;}
   }
   return(result);
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   ObjDel();
 
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
  {
   
   datetime cTime = iTime(NULL,PERIOD_W1,0);
   
   if (fTime || (TimeCurrent() > cTime && cTime > prevTime))
   {
   string gmt = forextsd_com_webget("http://calendar.forex-tsd.com/gmt.php");
   if(gmt!="") datetime gmtime = StrToTime(gmt);
   else return(0);
   
   int tz = NormalizeDouble((TimeCurrent() - gmtime)/3600.0,0);
   if ( tz < 24) TimeZone = tz;
   
      
   string cName = ForexTSD_Calendar();  
      
      if(cName != "")
      {   
      ReadnPlotCalendar(cName);
      fTime = false;
      prevTime = cTime;
      }
      else 
      {
      //Print("Attention! Wrong Calendar:",cName); 
      return(0);
      }
   //Print("OK Calendar");
   }
   
   if(AlertMode && TimeToAlert() && TimeCurrent() > nTime) 
   {
   Alert("Upcoming News! Be ready!"); 
   nTime = TimeCurrent() + AlertTimeGap*60;
   }
   ChartComment();   

//----

   return(0);
  }
//+------------------------------------------------------------------+