/* #import "shell32.dll"
 int ShellExecuteW(int hwnd,string Operation,string File,string Parameters,string Directory,int ShowCmd);
#import */

int f_mod, f_mod2, f_siz, f_siz2;            datetime t_read, t_port=0;

int OnInit() { EventSetTimer(5);
   int handle=FileOpen("Trades_List_Sent.txt", FILE_TXT|FILE_READ|FILE_COMMON);
   if (handle != INVALID_HANDLE) { f_mod2 = FileGetInteger(handle, FILE_MODIFY_DATE);
      f_siz2 = FileGetInteger(handle, FILE_SIZE);           FileClose(handle); }
   return(INIT_SUCCEEDED); }

void OnTick() { string Symb;
//   ts = ShellExecuteW(0,"open","C:\\Users\\Administrateur\\AppData\\Roaming\\MetaQuotes\\Terminal\\E88DA660F9A20E5DD9C622B8430BA4F1\\MQL4\\copy_file.bat",
//      "Trades_List_Sent.txt >>Logs\\copy_file.txt", "C:\\Users\\Administrateur\\AppData\\Roaming\\MetaQuotes\\Terminal\\E88DA660F9A20E5DD9C622B8430BA4F1\\MQL4", 2);

   if ((myHour() && DayOfWeek() == 5) || f_mod2 > f_mod || f_siz2 != f_siz) { int handle=FileOpen("Trades_List_Sent.txt", FILE_TXT|FILE_READ|FILE_COMMON), nLines=0;
      if (handle != INVALID_HANDLE) { while(true) { string line="";           line = FileReadString(handle);
         if (FileIsLineEnding(handle)) nLines ++;        if (FileIsEnding(handle)) break; }//        nLines ++;
         FileClose(handle);      Print("******* File Trades_List_Sent.txt contains "+nLines+" line"+(nLines > 1? "s": "")+" *******");
         ArrayResize(line_read, nLines + 1, 1);       Sleep(100);       CSV_FILE_READ();        string Symbs="|";       bool wa=false;

         if (myHour() && DayOfWeek() == 5) { FileDelete("Trades_List_Sent.txt", FILE_COMMON);
            for (int row=0; row < ArraySize(line_read) / 13; row ++) { if (TimeCurrent() - StrToInteger(line_read[row][12]) < 48 * 3600) {
               copy_file("Trades_List_Sent.txt", TimeToStr(TimeCurrent(), TIME_DATE|TIME_SECONDS) + " | " + line_read[row][1] + " | " + line_read[row][2] + " | " +
                  line_read[row][3] + " | " + line_read[row][4] + " | " + line_read[row][5] + " | " + line_read[row][6] + " | " + line_read[row][7] + " | " +
                  line_read[row][8] + " | " + line_read[row][9] + " | " + line_read[row][10] + " | " + line_read[row][11] + " | " + line_read[row][12], true); } } }

         else { bool tst;     for (row = 0; row < ArraySize(line_read) / 13; row ++) { tst = false;       // double lot;
               Symb = Symb_Check(line_read[row][1]);        for (int pos=0; pos < OrdersTotal() && ! tst; pos ++)
                  tst = OrderSelect(pos, SELECT_BY_POS) && Symb == OrderSymbol() && OrderMagicNumber() == line_read[row][9];
                  // && line_read[row][5] == StringSubstr(AccountCompany(), 0, 5) && StrToInteger(line_read[row][7]) <= OrderOpenTime();
               if (Symb != NULL && Symb != "") if (line_read[row][2] != "Close" && line_read[row][2] != "Modify") { if (! tst) { ResetLastError();
                     tst = OrderSend(Symb, line_read[row][2] == "Buy"? 0: 1 + StrToInteger(line_read[row][3]), StrToDouble(line_read[row][4]),
                        line_read[row][5] != "-"? StrToDouble(line_read[row][5]): line_read[row][2] == "Buy"? Ask: Bid, 5, StrToDouble(line_read[row][6]),
                        StrToDouble(line_read[row][7]), "Trades_List_Sent EA - " + line_read[row][11], StrToInteger(line_read[row][9]), StrToInteger(line_read[row][10]), clrNONE);
//                     if (tst) GlobalVariableSet(Symb + "_" + line_read[row][8] + "_" + line_read[row][11], tst);
                     if (! tst) Alert("******* OrderSend() Error: " + GetLastError() + " - " +
                           DoubleToStr(line_read[row][5] != "-"? StrToDouble(line_read[row][5]): line_read[row][2] == "Buy"? Ask: Bid, MarketInfo(Symb, MODE_DIGITS)) + " *******"); } }
                  else { string tmp;      for (int i=0; i < OrdersTotal() && ! tst; i ++) tst = OrderSelect(i, SELECT_BY_POS) && OrderSymbol() == Symb &&
                        StringSubstr((tmp=IntegerToString(OrderMagicNumber())), 5, StringLen(tmp) - 5) == line_read[row][8] &&
                        StringSubstr(OrderComment(), 22, StringLen(OrderComment()) - 22) == line_read[row][11];         int ticket;
                     if (tst) { ticket = OrderTicket();              ResetLastError();             if (line_read[row][2] == "Modify") {
                           if (StrToDouble(line_read[row][6]) > 0.0) tst = OrderModify(ticket, OrderOpenPrice(), StrToDouble(line_read[row][6]), OrderTakeProfit(), OrderExpiration(), clrNONE);
                           if (StrToDouble(line_read[row][7]) > 0.0) tst = OrderModify(ticket, OrderOpenPrice(), OrderStopLoss(), StrToDouble(line_read[row][7]), OrderExpiration(), clrNONE);
                           if (! tst) Alert("******* OrderModify() Error: " + GetLastError() + " *******"); }
                        if (line_read[row][2] == "Close") { tst = OrderClose(ticket, OrderLots(), OrderType()? Ask: Bid, 5, clrNONE);
                           if (! tst) Alert("******* OrderClose() Error: " + GetLastError() + " *******"); } } }
/*                  else if (line_read[row][5] == StringSubstr(AccountCompany(), 0, 5)) Close_All_Trades(Symb);*/ } }
   } }

   f_mod = f_mod2;      f_siz = f_siz2; }

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

void OnTimer() { int handle=FileOpen("Trades_List_Sent.txt", FILE_TXT|FILE_READ|FILE_COMMON);
   if (handle != INVALID_HANDLE) { f_mod2 = FileGetInteger(handle, FILE_MODIFY_DATE);
      f_siz2 = FileGetInteger(handle, FILE_SIZE);           FileClose(handle); }

   bool tst=false;      for (int pos=0; pos < OrdersTotal() && ! tst; pos ++)
      tst = OrderSelect(pos, SELECT_BY_POS) && float(OrderMagicNumber() / 10) == 8888;
   if (! tst/*OrdersTotal()*/ && FileIsExist("Trades_List_Closed (1).txt", FILE_COMMON))
      FileMove("Trades_List_Closed (1).txt", FILE_COMMON, "Trades_List_Closed (0).txt", FILE_COMMON);
   if (tst/*OrdersTotal()*/ && FileIsExist("Trades_List_Closed (0).txt", FILE_COMMON))
      FileMove("Trades_List_Closed (0).txt", FILE_COMMON, "Trades_List_Closed (1).txt", FILE_COMMON);
   tst = false;         for (pos = 0; pos < OrdersTotal() && ! tst; pos ++)
      tst = OrderSelect(pos, SELECT_BY_POS) && OrderMagicNumber() == 88887;
   if (! tst/*OrdersTotal()*/ && FileIsExist("Trades_List_Closed (1a).txt", FILE_COMMON))
      FileMove("Trades_List_Closed (1a).txt", FILE_COMMON, "Trades_List_Closed (0a).txt", FILE_COMMON);
   if (tst/*OrdersTotal()*/ && FileIsExist("Trades_List_Closed (0a).txt", FILE_COMMON))
      FileMove("Trades_List_Closed (0a).txt", FILE_COMMON, "Trades_List_Closed (1a).txt", FILE_COMMON);
   tst = false;         for (pos = 0; pos < OrdersTotal() && ! tst; pos ++)
      tst = OrderSelect(pos, SELECT_BY_POS) && OrderMagicNumber() == 88886;
   if (! tst/*OrdersTotal()*/ && FileIsExist("Trades_List_Closed (1b).txt", FILE_COMMON))
      FileMove("Trades_List_Closed (1b).txt", FILE_COMMON, "Trades_List_Closed (0b).txt", FILE_COMMON);
   if (tst/*OrdersTotal()*/ && FileIsExist("Trades_List_Closed (0b).txt", FILE_COMMON))
      FileMove("Trades_List_Closed (0b).txt", FILE_COMMON, "Trades_List_Closed (1b).txt", FILE_COMMON);

   string temp="", tktmp;     if (Seconds() > 50 && TimeCurrent() - t_port > 30) { t_port = TimeCurrent();
      for (pos = 0; pos < OrdersTotal(); pos ++) if (OrderSelect(pos, SELECT_BY_POS)) {
         tktmp = StringSubstr(OrderComment(), 22, StringLen(OrderComment()) - 22);
         temp += (pos? "\r\n": "") + OrderTicket() + " | " + OrderSymbol() + " | " + OrderType() + " | " + OrderLots() + " | " + OrderOpenPrice() +
            " | " + OrderStopLoss() + " | " + OrderTakeProfit() + " | " + OrderComment() + " | " + OrderMagicNumber() + " | " + OrderExpiration() +
            " | " + OrderOpenTime() + " | " + OrderClosePrice() + " | " + OrderCloseTime() + " | " + OrderProfit() + " | " + (tktmp != ""? tktmp: "-"); }
      copy_file("Trades_List_Port.txt", temp, false); } }

string line_read[][13];
void CSV_FILE_READ() { string filename="Trades_List_Sent.txt", filenam2="Trades_List_Sent-2.txt";
   if (FileIsExist(filenam2, FILE_COMMON)) FileDelete(filenam2, FILE_COMMON);       Sleep(100);
   FileCopy(filename, FILE_COMMON, filenam2, FILE_COMMON);        Sleep(100);       filename = filenam2;
   int row=0, col=0, handle=FileOpen(filename, FILE_CSV|FILE_READ|FILE_COMMON, "|");
   if(handle > 0) { while(True) { string temp=StringTrimLeft(StringTrimRight(FileReadString(handle)));
         line_read[row][col] = temp;         if (FileIsEnding(handle)) break;
         if (FileIsLineEnding(handle)) { col = 0;     row ++; }
         else  col ++; }         FileClose(handle); }
   else Alert("*** File "+filename+" not found, the last error is ", GetLastError() + " ***"); }

double NormPrice(double Price,string Symb) { return NormalizeDouble(Price, MarketInfo(Symb, MODE_DIGITS)); }

void Close_All_Trades(string Symb) { string temp;
  for (int pos=OrdersTotal()-1; pos >= 0; pos --) if (OrderSelect(pos, SELECT_BY_POS)) { bool result = false;
    if (Symb == OrderSymbol()/* && (mgc_num == OrderMagicNumber() || ! OrderMagicNumber())*/) {
       switch(OrderType()) {
          //Close opened long positions
          case OP_BUY  : result = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),5,Pink);   // Slippage
                         break;
          //Close opened short positions
          case OP_SELL : result = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),5,Pink);   // Slippage
                         break;
          //Close pending orders
            case OP_BUYLIMIT  : result = OrderDelete( OrderTicket() );     break;
            case OP_BUYSTOP   : result = OrderDelete( OrderTicket() );     break;
            case OP_SELLLIMIT : result = OrderDelete( OrderTicket() );     break;
            case OP_SELLSTOP  : result = OrderDelete( OrderTicket() ); }
       if (result == false) Sleep(2000); } }

  if (pos < OrdersTotal() - 1) {
      temp = "***** Account / " + Symb + " Reached. All Trades Have Been Closed. ("+DoubleToStr(AccountBalance(),2)+" - "+Hour()+") *****";      Alert(temp); } }

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

bool myHour() { return(StrToInteger(StringSubstr(TimeToStr(TimeLocal(), TIME_MINUTES), 0, 2)) == 23 &&
      StrToInteger(StringSubstr(TimeToStr(TimeLocal(), TIME_MINUTES), 3, 2)) >= 30); }

string Symb_Check(string Symb) { ResetLastError();          string s_comp=AccountCompany();
   int i_comp=StringSubstr(s_comp,0,5) == "Black"? 0: StringSubstr(s_comp,0,5) == "FX Ch"? 1: StringSubstr(s_comp,0,5) == "Trade"? 2: StringSubstr(s_comp,0,5) == "Vanta"? 3:
      StringSubstr(s_comp,0,5) == "Eight"? 4: 5;
   switch(i_comp) {
         case 0  :      if (Symb == "UKOUSD") Symb = "BRENT";
         break;
         case 1  :      if (Symb == "US30INDEX") Symb = "US30";      if (Symb == "BRENTCRUD") Symb = "UKOUSD";
         break;
         case 2  :
         break;
         case 3  :
         break;
         case 4  :
         break;
         default :
      if (Symb == "GOLD" || Symb == "Gold") Symb = "XAUUSD";      if (Symb == "Silver") Symb = "XAGUSD"; }

      Symb += i_comp? "": Symb != "BRENT"? "p": "";      // _p =
 return(Symb); }
