//+------------------------------------------------------------------+
//|                                  QuoteToExcel_MultiPair v2.0.mq4 |
//|                                     'gilani' at forexfactory.com |
//+------------------------------------------------------------------+
// Change Log
// 24-02-08 v1.1 - fixed the H1 chart running for requirement for H1 data generation. 
//          Now a chat can be running on any timeframe, H1 wil be generated by default
// 26-02-08 v2.0 added D1 history files 


#property copyright "gilani"
#property link ""

#include <stdlib.mqh>

string pairs[]  = {"EURJPY", "EURUSD", "GBPUSD", "USDJPY", "USDCHF"};

string months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
string name; 
//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
int totalPairs;

int init() {
   name = "QuoteToExcel_MultiPair v2.0";
   totalPairs = ArraySize (pairs);   
   return (0);

}

int start() {
   
   if (IsConnected() == false) {
      Alert ("You must be connected to the server first!");
      return (0);
   }

   for (int x=0; x<totalPairs; x++) { //asking for updates for H1 & D1 so that the reqest is sent in parallel.
      iBars(pairs[x], PERIOD_D1);
      iBars(pairs[x], PERIOD_H4);
      iBars(pairs[x], PERIOD_W1);
      iBars(pairs[x], PERIOD_MN1);
   }
   process(PERIOD_H4);  
   process(PERIOD_D1);
   process(PERIOD_W1);
   process(PERIOD_MN1);
}


int process (int period) {
   
   int err = 0;
   bool isError = false;
   string pairNames = "";
      
   err = checkHistoryAvailability (period);
   if (err != 0) {
      Alert ("Error "+err+" - Unabe to update local history files!. Please rerun the script later");   
      return (0);
   }
   
   
   for (int x=0; x<totalPairs; x++) {
      pairNames = pairNames + pairs[x] + ",";   
      err = generateFile (pairs[x], period);
      if (err != 0) {
         Alert("Symbol(",pairs[x],") Error(",err,"): ",ErrorDescription(err));
         isError = true;
      }
   }

   string msg = periodDesc(period)+" for "+totalPairs+" pairs - "+StringSubstr(pairNames,0, StringLen(pairNames)-1);
   
   if (isError == false) {
      Alert(name+" - Successfully exported history data on "+msg);
   } else {
      Alert(name+" - Export unsuccessful on "+msg+"! Please check the errors.");
   }
   
   return (0);
}
  
int generateFile (string symbol, int period) {
   double O,H,L,C, T;   
   int availableBars = iBars(symbol, period);
      
   int totalBars = maxBarsToRead(period);
   if (availableBars < totalBars) totalBars = availableBars;

   int handle=FileOpen("Exported"+symbol+periodDesc(period)+".csv", FILE_CSV|FILE_WRITE, ',');
  
   FileWrite(handle, symbol+" "+periodDesc(period)+" (Export generated by "+name+")");
   FileWrite(handle, "DATE","HOUR","OPEN","HIGH","LOW","CLOSE");

   for (int i=0; i<totalBars; i++) {
      if(handle>0) {
         O = iOpen (symbol, period, i);
         H = iHigh (symbol, period, i);      
         L = iLow  (symbol, period, i);      
         C = iClose(symbol, period, i);               
         T = iTime (symbol, period, i);

         string date = TimeDay(T)+" "+months[TimeMonth(T)-1]+" "+TimeYear(T); //format - 21 Feburary 2008         
         string time = TimeToStr(T, TIME_MINUTES);
         
         FileWrite(handle, date, time, O, H, L, C);

      }
   } 
   
   FileClose(handle);
   return(GetLastError());
}
  
string periodDesc(int period) {
   switch (period) {
      case PERIOD_H4:  return ("H4");
      case PERIOD_D1:  return ("D1");
      case PERIOD_W1:  return ("W1");
      case PERIOD_MN1:  return ("MN1");
   }
   return ("");
}

int checkHistoryAvailability(int period) {
   int bars;
   int err;
   int pause = 5;
   
   int maxBars = maxBarsToRead(period);
   
   for (int i=0;i <10; i++) {
      bars = maxBars;
      for (int x=0; x<totalPairs; x++) {
         int getBars = iBars(pairs[x], period);
         if (getBars < maxBars) bars = getBars;
      }
      err = GetLastError();
      if (err != 0 || bars < maxBars) {
         Alert ("Local history files are being updated from the server. Attempting again in "+pause+" seconds... ");
         Sleep (pause*1000);
         pause += 2;
      } else {
         break;
      }
   }
   return (err);
}   



int maxBarsToRead (int period) {
   switch (period) {
      case PERIOD_H4:  return (5);
      case PERIOD_D1:  return (5);
      case PERIOD_W1:  return (5);
      case PERIOD_MN1:  return (5);
   }
      
  return (0);
}