
#include <Files/FileTxt.mqh>

// run as an indicator; to run as an expert comment out the next line and copy the source file to the experts dir
#property indicator_chart_window

input string _s1 = "Time filter for recording";
input int start_hour = 9;
input int start_minute = 0;
input int end_hour = 10;
input int end_minute = 0;

char delim = '\t';
string startup_date = "";

CFileTxt* file;
string fileName="";
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
//---- indicators
   file=new CFileTxt();
   
//----
   return(0);
  }

//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   file.Close();
   
   delete file;
         
   Comment (" ");
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
  {
   //int    counted_bars=IndicatorCounted();
//----   
   datetime current_dt = TimeCurrent ();
   string current_date = TimeToStr (current_dt, TIME_DATE);
   
   if (current_date != startup_date)
   {                     
      fileName = current_date + "-" + Symbol() + "_tick.csv";
      
      file.Open(fileName,FILE_READ|FILE_WRITE|FILE_SHARE_WRITE|FILE_SHARE_READ|FILE_CSV,delim);
      if (file.Size()>0)
      {
         file.Seek(0,ENUM_FILE_POSITION::SEEK_END);
      }
      startup_date = current_date;
   }
   
   string current_time = TimeToStr (current_dt, TIME_SECONDS);
   int current_hour = TimeHour (current_dt);
   int current_minute = TimeMinute (current_dt);
   
   int current_hm = current_hour * 60 + current_minute;
   if (current_hm < start_hour * 60 + start_minute ||
       current_hm > end_hour * 60 + end_minute)
   {
      Comment ("TickDataCollector NOT recording");
      return 0;
   }

   Comment ("TickDataCollector recording");
   
   string line = StringFormat("%s",current_date) + ";";   
   line = line + CharToStr(delim) + StringFormat("%s",current_time) + ";";
   line = line + CharToStr(delim) + StringFormat("%f",NormalizeDouble(Ask,Digits)) + ";";
   line = line + CharToStr(delim) + StringFormat("%f",NormalizeDouble(Bid,Digits));
      
   file.WriteString(line + "\r\n");
   file.Flush();   
   
//----
   return(0);
  }
//+------------------------------------------------------------------+