//extern bool o_Script =  false;
//extern bool tot_Forex = false;
//extern int tot_Charts = 4;
#include <Charts_Volatility_Chk_VPS.mqh>
//extern string Ftp_Ids = "2-4";
extern int tim_Charts = 20;
extern string Vol_Rept = "";  // EURUSD, USDJPY, GBPNZD

string Symbs, Symb2s, str=Vol_Rept;          bool t_mod=false;
int tot_Charts=4, i_=0, totCharts=tot_Charts, im;        datetime t_tim;

int OnInit() { EventSetTimer(tim_Charts * 60);           StringReplace(str, ", ", "|");      return(INIT_SUCCEEDED); }

void OnTick() { if (! (TimeCurrent() % (tim_Charts * 60)) || (FileIsExist("Chart_Symbol_Set (5).txt", FILE_COMMON) &&
   FileGetInteger("Chart_Symbol_Set (5).txt", FILE_MODIFY_DATE, FILE_COMMON) > t_tim)) {
      t_mod = true;        Symbs = "";       Symb2s = "";      if (i_ == im) { i_ = 0;       totCharts = tot_Charts; } }

  if (t_mod || (! OrdersTotal() && TimeCurrent() - t_tim > 120)) {
   string sep="|", temp, tmp, line_read[], headers, URL;       ushort u_sep=StringGetCharacter(sep, 0);
   char post[], result[];           int res, timeout=5000;

   int fl=4;      string Symb, Symb_;     if (Symbs == "") { Symbs = (str != ""? str + "|": "");
      while(FileIsExist("Charts_Volatility_Check-b"+IntegerToString(fl)+".txt", FILE_COMMON)) {
         CSV_FILE_READ("Charts_Volatility_Check-b"+IntegerToString(fl)+".txt");
         for (int i=0; i < ArraySize(line_read_); i ++) if (line_read_[i] != "" && line_read_[i] != NULL &&
            Symb != line_read_[i]) { Symbs += line_read_[i] + "|";         Symb = line_read_[i]; }
         fl += 4; }

      CSV_FILE_READ("Charts_Volatility_Check-c.txt");
      for (i = 0; i < ArraySize(line_read_); i ++) if (line_read_[i] != "" && line_read_[i] != NULL &&
         Symb != line_read_[i]) { Symbs += line_read_[i] + "|";         Symb = line_read_[i]; }
Alert("*** (1) " + Symbs + " ***");

      if (Symbs != "") { int cpt=0;       copy_file("Charts_Volatility_Check.txt", Symbs, false, false);       Sleep(200);
         while(! SendFTP("Charts_Volatility_Check.txt", NULL) && cpt < 7) { Sleep(200);         cpt ++; }      // www/logs_ATS/FxChoice-4
         URL = "http://www.ecomclub.com/web_send_cashpower.php?wa=tr&fl=2&ftp="+Ftp_Ids+"&pr=1";      Sleep(200);
         res = WebRequest("GET", URL, NULL, NULL, timeout, post, 0, result, headers); }

      fl = 4;        temp = "";
      while(FileIsExist("Charts_Volatility_Chck_L-b"+IntegerToString(fl)+".txt", FILE_COMMON)) {
         CSV_FILE_READ("Charts_Volatility_Chck_L-b"+IntegerToString(fl)+".txt");
         for (i = 0; i < ArraySize(line_read_); i ++) if (line_read_[i] != "" && line_read_[i] != NULL &&
            Symb != line_read_[i]) { temp += line_read_[i] + "|";          Symb = line_read_[i]; }
         fl += 4; }

      CSV_FILE_READ("Charts_Volatility_Chck_L-c.txt");
      for (i = 0; i < ArraySize(line_read_); i ++) if (line_read_[i] != "" && line_read_[i] != NULL &&
         Symb != line_read_[i]) { temp += line_read_[i] + "|";          Symb = line_read_[i]; }

      if (temp != "") { cpt = 0;       copy_file("Charts_Volatility_Chck_L.txt", temp, false, false);          Sleep(200);
         while(! SendFTP("Charts_Volatility_Chck_L.txt", NULL) && cpt < 7) { Sleep(200);        cpt ++; }      // www/logs_ATS/FxChoice-4
         URL = "http://www.ecomclub.com/web_send_cashpower.php?wa=tr&fl=5&ftp="+Ftp_Ids+"&pr=1";      Sleep(200);
         res = WebRequest("GET", URL, NULL, NULL, timeout, post, 0, result, headers); }

      fl = 4;        temp = "";
      while(FileIsExist("Charts_Volatility_Chck_S-b"+IntegerToString(fl)+".txt", FILE_COMMON)) {
         CSV_FILE_READ("Charts_Volatility_Chck_S-b"+IntegerToString(fl)+".txt");
         for (i = 0; i < ArraySize(line_read_); i ++) if (line_read_[i] != "" && line_read_[i] != NULL &&
            Symb != line_read_[i]) { temp += line_read_[i] + "|";          Symb = line_read_[i]; }
         fl += 4; }

      CSV_FILE_READ("Charts_Volatility_Chck_S-c.txt");
      for (i = 0; i < ArraySize(line_read_); i ++) if (line_read_[i] != "" && line_read_[i] != NULL &&
         Symb != line_read_[i]) { temp += line_read_[i] + "|";          Symb = line_read_[i]; }

      if (temp != "") { cpt = 0;       copy_file("Charts_Volatility_Chck_S.txt", temp, false, false);          Sleep(200);
         while(! SendFTP("Charts_Volatility_Chck_S.txt", NULL) && cpt < 7) { Sleep(200);        cpt ++; }      // www/logs_ATS/FxChoice-4
         URL = "http://www.ecomclub.com/web_send_cashpower.php?wa=tr&fl=6&ftp="+Ftp_Ids+"&pr=1";      Sleep(200);
         res = WebRequest("GET", URL, NULL, NULL, timeout, post, 0, result, headers); }

      fl = 4;     while(FileIsExist("Charts_Volatility_End-b"+IntegerToString(fl)+".txt", FILE_COMMON)) {
         CSV_FILE_READ("Charts_Volatility_End-b"+IntegerToString(fl)+".txt");
         for (i = 0; i < ArraySize(line_read_); i ++) if (line_read_[i] != "" && line_read_[i] != NULL &&
            Symb != line_read_[i]) { Symb2s += line_read_[i] + "|";        Symb = line_read_[i]; }
         fl += 4; }

      CSV_FILE_READ("Charts_Volatility_End-c.txt");
      for (i = 0; i < ArraySize(line_read_); i ++) if (line_read_[i] != "" && line_read_[i] != NULL &&
         Symb != line_read_[i]) { Symb2s += line_read_[i] + "|";        Symb = line_read_[i]; }
//Alert("*** (2) " + Symb2s + " ***");

      if (Symb2s != "") { cpt = 0;        copy_file("Charts_Volatility_Check-2.txt", Symb2s, false, false);       Sleep(200);
         while(! SendFTP("Charts_Volatility_Check-2.txt", NULL) && cpt < 7) { Sleep(200);       cpt ++; }      // www/logs_ATS/FxChoice-4
         URL = "http://www.ecomclub.com/web_send_cashpower.php?wa=tr&fl=3&ftp="+Ftp_Ids+"&pr=1";         Sleep(200);
         res = WebRequest("GET", URL, NULL, NULL, timeout, post, 0, result, headers); }

      string Symb3s="";       for (int id=1; id <= 4; id ++) for (int id2=1; id2 <= 9; id2 ++) {
         URL = "http://www.ecomclub.com/ATS_Histo_Times_List" + id + "-" + id2 + ".txt";
         res = WebRequest("GET", URL, NULL, NULL, timeout, post, 0, result, headers);           if (res != 404) {
            if (res != 200) Print("*** Error in WebRequest (" + IntegerToString(res) + "). Error code = ", GetLastError(), " ***");
            else { PrintFormat("** The file has been successfully loaded ("+IntegerToString(res)+"), File size = %d bytes **", ArraySize(result));
               int filehandle = FileOpen("ATS_Histo_Times_List" + id + "-" + id2 + ".txt", FILE_WRITE|FILE_BIN);
               if (filehandle != INVALID_HANDLE) {
                  FileWriteArray (filehandle, result, 0, ArraySize(result));
                  FileClose(filehandle); }
               else  Print("******* handle==INVALID_HANDLE : FileOpen(\"Cash_Power_Alerts_w2.txt\"  *******");
               Symb3s += CharArrayToString(result); } }        Sleep(200); }

      string Symb5s="";       for (id = 1; id <= 4; id ++) for (id2 = 1; id2 <= 9; id2 ++)
         if (IntegerToString(id) + "-" + IntegerToString(id2) != Ftp_Ids) {
            URL = "http://www.ecomclub.com/Charts_Volatility_Check-" + id + "-" + id2 + ".txt";
            res = WebRequest("GET", URL, NULL, NULL, timeout, post, 0, result, headers);           if (res != 404) {
               if (res != 200) Print("*** Error in WebRequest (" + IntegerToString(res) + "). Error code = ", GetLastError(), " ***");
               else { PrintFormat("** The file has been successfully loaded ("+IntegerToString(res)+"), File size = %d bytes **", ArraySize(result));
                  Symb5s += CharArrayToString(result); } }        Sleep(200); } }

   int k=StringSplit(Symbs, u_sep, line_read);        im = k - 1;

   long prevChart=ChartFirst();        int per;       string Symb4s="";       cpt = 0;
   while(cpt < 25) { if ((per=ChartPeriod(prevChart)) < PERIOD_D1 && per > PERIOD_M15 &&
      Symb != ChartSymbol(prevChart)) { Symb = ChartSymbol(prevChart);   // ChartIndicatorsTotal(prevChart, 0)
         Symb4s += ChartSymbol(prevChart) + " | "; }
      prevChart = ChartNext(prevChart);         cpt ++; }            cpt = 0;

   temp = " ";       for (int pos=0; pos < OrdersTotal(); pos ++)
      if (OrderSelect(pos, SELECT_BY_POS) && StringFind(temp, OrderSymbol()) < 0) temp += OrderSymbol() + " | ";

   if (t_mod) { int cpt2=0, it=0;      i = i_;        prevChart = ChartFirst();
      while(cpt < 25 && i < fmin(k - 1, totCharts)) { while(it < 4) { bool tst=false;
         if ((per=ChartPeriod(prevChart)) > PERIOD_M15 && per < PERIOD_D1) { Symb = ChartSymbol(prevChart);
            if (! it && ! i) while((StringFind(temp, StringTrimRight(StringTrimLeft(line_read[i]))) > 0 ||
                  StringFind(Symb4s, StringTrimRight(StringTrimLeft(line_read[i]))) > 0) && i < k - 1) i ++;
//            Symb = StringTrimRight(StringTrimLeft(line_read[i]));
            for (pos = 0; pos < OrdersTotal() && ! tst; pos ++) tst = (OrderSelect(pos, SELECT_BY_POS) && Symb == OrderSymbol());
            if (! tst && StringFind(" "+Symb2s, line_read[i]) < 0 && StringFind(" "+Symb3s, line_read[i]) < 0 && StringFind(" "+Symb5s, line_read[i]) < 0) {
               if (StringFind(Symbs, Symb) < 0 || i == i_ || (i > i_ && (Symb_ == Symb || StringFind(Symb4s, Symb) >= 0)) ||
               (it < 2 && per != PERIOD_M30) || (it == 2 && per != PERIOD_H1) || (it == 3 && per != PERIOD_H4)) { if (i < k - 1) {
//Alert("******* " + Symb + " - " + it + " - " + i + " - " + im + " - " + k + " - " + StringTrimRight(StringTrimLeft(line_read[i])) + " - " + ChartPeriod(prevChart) + " *******");
                     if (! it) { FileDelete("CP_List_Sent_" + Symbol() + "_" + Period() + ".txt", FILE_COMMON);               Sleep(100);
                        tmp = Symb + " - " + it + " - " + i + " - " + im + " - " + k + " - " + StringTrimRight(StringTrimLeft(line_read[i])) + " - " + ChartPeriod(prevChart) + " - " + mOrdrsTotal(0) + " *";
                        copy_file("Charts_Volatility_Check (3).txt", TimeToStr(TimeCurrent(), TIME_DATE|TIME_MINUTES) + " - " + tmp, FILE_COMMON, true);          Sleep(100);
                        copy_file("Charts_Volat_Chk_Events.txt", TimeToStr(TimeCurrent(), TIME_DATE|TIME_MINUTES) + " - Event 2 : " + StringTrimRight(StringTrimLeft(line_read[i])), FILE_COMMON, true); }
                     StringReplace(Symb4s, Symb, StringTrimRight(StringTrimLeft(line_read[i])));         if (! it) Symb_ = Symb;
                     ChartSetSymbolPeriod(prevChart, StringTrimRight(StringTrimLeft(line_read[i])), it < 2? PERIOD_M30: it == 2? PERIOD_H1: PERIOD_H4);     Sleep(200);
                     ChartSaveTemplate(prevChart, "Charts_Volat_Chk_" + StringTrimRight(StringTrimLeft(line_read[i])) + "_" + IntegerToString(per) + "_" +
                        IntegerToString(Hour()) + IntegerToString(Minute()));/*                ResetLastError();
                     if (! WindowScreenShot("Charts_Volat_Chk_" + StringTrimRight(StringTrimLeft(line_read[i])) + "_" + IntegerToString(per), 800, 600, -1, -1, -1))
                        copy_file("Charts_Volat_Chk_Events.txt", TimeToStr(TimeCurrent(), TIME_DATE|TIME_MINUTES) + " - Event (2) : " + StringTrimRight(StringTrimLeft(line_read[i])) + " - Pb. " +
                           "WindowScreenShot() - " + IntegerToString(GetLastError()), FILE_COMMON, true);
/*                     if (StringFind(AccountCompany(), "Eightcap") >= 0) ChartApplyTemplate(prevChart, "temp ATS - Cashpower ++.tpl");
                     else ChartApplyTemplate(prevChart, ! it? "temp ATS - CP - EPP + RSI - M30.tpl": it == 1? "temp ATS - CP - EPP + RSI - M30b.tpl":
                           it == 2? "temp ATS - CP - EPP + RSI - H1.tpl": "temp ATS - CP - EPP + RSI - H4.tpl");        Sleep(200); */
                     GlobalVariableSet(StringTrimRight(StringTrimLeft(line_read[i])) + "_" + IntegerToString(per) + "_WindowScreenShot", 1.0);     if (it == 3) i ++; }
                  else  break; }          else { copy_file("Charts_Volat_Chk_Events.txt", TimeToStr(TimeCurrent(), TIME_DATE|TIME_MINUTES) + " - Event 2b : " +
                        StringTrimRight(StringTrimLeft(line_read[i])) + " - " + StringFind(Symbs, Symb) + " - " + i + " - " + i_ + " - " + Symb_ + " - " + Symb + " - " +
                        StringFind(Symb4s, Symb) + " - " + it + " - " + per, FILE_COMMON, true);
                     if (per == PERIOD_H4) { it = 3;   i ++; } } }      else { copy_file("Charts_Volat_Chk_Events.txt", TimeToStr(TimeCurrent(), TIME_DATE|TIME_MINUTES) + " - Event 2a : " +
                     StringTrimRight(StringTrimLeft(line_read[i])) + " - " + tst + " - " + StringFind(" "+Symb2s, line_read[i]) + " - " + StringFind(" "+Symb3s, line_read[i]) + " - " +
                     StringFind(" "+Symb5s, line_read[i]), FILE_COMMON, true);                  if (per == PERIOD_H4) { it = 3;    i ++; } }
            while(! tst && cpt2 < 200) { Sleep(100);           cpt2 ++;
               tst = (StringFind(Symbs, ChartSymbol(prevChart)) > 0 || ChartSymbol(prevChart) == StringTrimRight(StringTrimLeft(line_read[i-1])) ||
                  ChartSymbol(prevChart) == StringTrimRight(StringTrimLeft(line_read[i]))); } }
         prevChart = ChartNext(prevChart);            cpt2 = 0;         int cpt3=0;
         while(! ChartPeriod(prevChart) && cpt2 < 200) { while(! ChartPeriod(prevChart) && cpt3 < 200) { Sleep(100);         cpt3 ++; }
            Sleep(100);          cpt2 ++;          if (! ChartPeriod(prevChart)) prevChart = ChartNext(prevChart); }
         it ++; }          it = 0;        cpt ++; }         t_mod = false;       i_ = i;        totCharts += tot_Charts; }

      copy_file("Charts_Volatility_Check (2).txt", Symb4s, FILE_COMMON, false);        t_tim = TimeCurrent();        Sleep(200);

      FileCopy("Charts_Volatility_Check (2).txt", FILE_COMMON, "Charts_Volatility_Check-"+Ftp_Ids+".txt", false);       cpt = 0;
      while(! SendFTP("Charts_Volatility_Check-"+Ftp_Ids+".txt", NULL) && cpt < 7) { Sleep(200);      cpt ++; }      // www/logs_ATS/FxChoice-4
      URL = "http://www.ecomclub.com/web_send_cashpower.php?wa=tr&fl=4&ftp="+Ftp_Ids+"&pr=1";         Sleep(200);
      res = WebRequest("GET", URL, NULL, NULL, timeout, post, 0, result, headers); } }

void OnDeinit(const int reason) { EventKillTimer(); }

void OnTimer() { t_mod = true;         Symbs = "";       if (i_ == im) { i_ = 0;       totCharts = tot_Charts; } }

string line_read_[5];
bool CSV_FILE_READ(string filename) { string filenam2= StringSubstr(filename, 0, StringFind(filename, ".")) +
      IntegerToString(Period())+"-"+StringSubstr(Symbol(), 0, 1)+StringSubstr(Symbol(), 2, 1)+StringSubstr(Symbol(), 3, 1)+StringSubstr(Symbol(), 5, 1)+".txt";
   if (FileIsExist(filenam2, FILE_COMMON)) FileDelete(filenam2, FILE_COMMON);             Sleep(150);
   FileCopy(filename, FILE_COMMON, filenam2, FILE_COMMON);        Sleep(250 + (Seconds() <= 5? 150: 0));       filename = filenam2;
   int col=0, handle=FileOpen(filename, FILE_CSV|FILE_READ|FILE_COMMON, "|");
   if(handle > 0) { while(True) { string temp=StringTrimLeft(StringTrimRight(FileReadString(handle)));
         line_read_[col] = temp;         if (FileIsEnding(handle)) break;         col ++; }         FileClose(handle); }
   else Alert("*** File "+filename+" not found, the last error is ", GetLastError() + " ***");
   if (FileIsExist(filenam2, FILE_COMMON)) FileDelete(filenam2, FILE_COMMON);
   return(handle > 0); }

int copy_file(string filename,string temp,bool filc,bool add) { int handle, it=0;
   bool tst=false;//         filename = StringSubstr(filename, 0, StringFind(filename, ".")) + ".txt";
   while (! tst && it < 7) { if (filc) handle = FileOpen (filename, add? FILE_TXT|FILE_READ|FILE_WRITE|FILE_COMMON:
         FILE_TXT|FILE_WRITE|FILE_COMMON);         else  handle = FileOpen (filename, FILE_TXT|FILE_WRITE);
      if (handle != INVALID_HANDLE) { if (add && FileSize(handle)) FileSeek(handle, FileSize(handle), 0);
         tst = FileWrite(handle, temp);
         if (! tst) Print ("Problème : FileWrite(handle, ("+it+" - "+IntegerToString(GetLastError())+") / "+Symbol()+" ***");
         FileClose(handle); }
      else Print ("Problème : handle == INVALID_HANDLE. ("+it+" - "+IntegerToString(GetLastError())+") / "+Symbol()+" ***");     it ++; }
   return(handle); }

int mOrdrsTotal(bool Per) { int itmp=0;
   for (int pos=0; pos < OrdersTotal(); pos ++) if (OrderSelect(pos, SELECT_BY_POS) && (! Per || (StrToInteger(StringSubstr(OrderComment(), 15, 4)) == Period() &&
         Per)) && OrderSymbol() == Symbol()) itmp ++;             return(itmp); }

//       StringInit(str, fmax(line_size[i], StringLen(DoubleToStr(dtmp, 0))) - fmin(line_size[i], StringLen(DoubleToStr(dtmp, 0))), ' ');
//       temp += DoubleToStr(dtmp, 0) + (line_size[i] > StringLen(DoubleToStr(dtmp, 0))? str: "") + " | "; }
