/* #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, tim_port=0, tim_Hst, nxt_tim=0;
double TS=MarketInfo(Symbol(), MODE_TICKSIZE), TV=MarketInfo(Symbol(), MODE_TICKVALUE), TV_=MarketInfo("USDCHF", MODE_TICKVALUE), TsTv=TV/TV_;

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); }

   if (GlobalVariableCheck("All_tim_Balance")) tim_Hst = GlobalVariableGet("All_tim_Balance");
   else { tim_Hst = TimeCurrent();        GlobalVariableSet("All_tim_Balance", tim_Hst); }
   return(INIT_SUCCEEDED); }

void OnTick() { string Symb;        double maxBal=0.0, dtmp;      bool t_Nxt3=false;      int ticket, Per=30;
//   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);

   while(Per <= 240 && ! (Seconds() % 5)) { for (int pos=OrdersTotal()-1; pos >= 0; pos --) if (OrderSelect(pos, SELECT_BY_POS)) { ticket = OrderTicket();
      if (GlobalVariableCheck(OrderSymbol() + "_t_Nxt3")) t_Nxt3 = GlobalVariableGet(OrderSymbol() + "_t_Nxt3");
      if (GlobalVariableCheck(OrderSymbol() + "_NxtTim")) nxt_tim = GlobalVariableGet(OrderSymbol() + "_NxtTim");
      if (GlobalVariableCheck(OrderSymbol() + "_MaxBal")) maxBal = GlobalVariableGet(OrderSymbol() + "_MaxBal");
      if ((dtmp=f_Profit(OrderSymbol(), Per, 1)) != GlobalVariableGet(OrderSymbol() + "_Balance")) GlobalVariableSet(OrderSymbol() + "_Balance", dtmp);
      if (GlobalVariableGet(OrderSymbol() + "_Balance") > maxBal) {
         maxBal = GlobalVariableGet(OrderSymbol() + "_Balance");        GlobalVariableSet(OrderSymbol() + "_MaxBal", maxBal); }
      if (! OrderCloseTime()) { if (maxBal - GlobalVariableGet(OrderSymbol() + "_Balance") - f_Profit(OrderSymbol(), Per, 0) > 25.0 * TsTv &&
         (iCustom(OrderSymbol(), Per, "ind Profil Marché (de CMA).ex4", 0, 1) > 60.0 || iCustom(OrderSymbol(), Per, "ind Profil Marché (de CMA).ex4", 2, 1) > 65.0)) {
            Close_All_Trades(true);                      CreateVLine(TimeCurrent(), Period(), false, 2);
            nxt_tim = TimeCurrent() + 24 * 3600;         while(TimeDayOfWeek(nxt_tim)) nxt_tim += 24 * 3600;//         CreateVLine(nxt_tim, Period(), true, 2);
            GlobalVariableSet(OrderSymbol() + "_NxtTim", nxt_tim);
Alert("******* END! : " + GlobalVariableGet(OrderSymbol() + "_Balance") + " - " + maxBal + " - " + f_Profit(OrderSymbol(), Per, 0) + " - " +
   f_Profit(OrderSymbol(), Per, 1) + " - " + TimeToStr(nxt_tim, TIME_DATE) + " *******");       t_Nxt3 = true;       GlobalVariableSet(OrderSymbol() + "_t_Nxt3", t_Nxt3);
            maxBal = GlobalVariableGet(OrderSymbol() + "_Balance");        GlobalVariableSet(OrderSymbol() + "_MaxBal", maxBal); }           // keybd_event(19, 0, 0, 0);
         if (t_Nxt3 && TimeCurrent() >= nxt_tim) { CreateVLine(nxt_tim, Period(), true, 2);     t_Nxt3 = false;      GlobalVariableSet(OrderSymbol() + "_t_Nxt3", t_Nxt3); }
/* if (! (Minute() % 20)) Alert("******* TEST END! : " + GlobalVariableGet(Symbol() + "_Day_Balance") + " - " + GlobalVariableGet(Symbol() + "_Balance") + " - " +
   f_Profit(1) + " - " + maxBal + " - " + (maxBal - GlobalVariableGet(Symbol() + "_Balance")) + " - " + TimeToStr(nxt_tim, TIME_DATE) + " - " + t_Nxt3 + " *******");
      if ((GlobalVariableGet(Symbol() + "_Day_Balance") + OrderProfit()) >= 12.0 * TsTv) { Close_All_Trades();           nxt_tim = TimeCurrent() + 24 * 3660; }
if (Day() == 5 && Hour() >= 16) Alert("******* Day_Balance! : " + GlobalVariableGet(Symbol() + "_Day_Balance") + " - " + OrderProfit() + " - " + t_DrDn + " *******");*/ } }
     Per = (Per == 60? 240: Per == 30? 60: 500); }

   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 ++)
            if (line_read[row][1] != "" && line_read[row][1] != NULL) { tst = false;         // double lot;
               Symb = Symb_Check(line_read[row][1]);        for (pos = 0; pos < OrdersTotal() && ! tst; pos ++)
                  tst = (OrderSelect(pos, SELECT_BY_POS) && Symb == OrderSymbol() && IntegerToString(OrderMagicNumber()) == line_read[row][9] &&
                     StringSubstr(OrderComment(), 22, StringLen(OrderComment()) - 22) == line_read[row][11]) || GlobalVariableCheck(Symb + "_ticket_" + line_read[row][11]);
                     // && 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();
                     ticket = mOrdrSend(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);
                     GlobalVariableSet(Symb + "_ticket_" + line_read[row][11], 1);              tst = ticket > 0;
Alert("******* OrderSend() OK - " + ticket + " - " + Symb + " - " + line_read[row][11] + " - " + nxt_tim + " - " + TimeToStr(nxt_tim, TIME_DATE|TIME_MINUTES) + " *******");
//                     if (tst) GlobalVariableSet(Symb + "_" + line_read[row][8] + "_" + line_read[row][11], tst);
                     if (! tst) Alert("******* mOrdrSend() Error: " + GetLastError() + " - " +
                           DoubleToStr(line_read[row][5] != "-"? StrToDouble(line_read[row][5]): line_read[row][2] == "Buy"? Ask: Bid, MarketInfo(Symb, MODE_DIGITS)) + " *******"); }
/*else  Alert("******* OrderSend() NO - " + OrderTicket() + " - " + OrderSymbol() + " - " + line_read[row][11] + " - " + nxt_tim + " - " + TimeToStr(nxt_tim, TIME_DATE|TIME_MINUTES) + " *******");*/ }
                  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) - 6) == line_read[row][8] &&
                        StringSubstr(OrderComment(), 22, StringLen(OrderComment()) - 22) == line_read[row][11];
                     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);
Alert("******* OrderModify() - " + Symb + " - " + ticket + " - " + line_read[row][11] + " - SL: " + line_read[row][6] + " *******"); }
                           if (StrToDouble(line_read[row][7]) > 0.0) { tst = OrderModify(ticket, OrderOpenPrice(), OrderStopLoss(), StrToDouble(line_read[row][7]), OrderExpiration(), clrNONE);
Alert("******* OrderModify() - " + Symb + " - " + ticket + " - " + line_read[row][11] + " - TP: " + line_read[row][7] + " *******"); }
                           if (! tst) Alert("******* OrderModify() Error: " + GetLastError() + " *******"); }
                        if (line_read[row][2] == "Close") { tst = OrderClose(ticket, OrderLots(), OrderType()? Ask: Bid, 5, clrNONE);
Alert("******* OrderClose() - " + Symb + " - " + ticket + " - " + line_read[row][11] + " *******");         GlobalVariableDel(Symb + "_ticket_" + line_read[row][11]);
                           if (! tst) Alert("******* OrderClose() Error: " + GetLastError() + " *******"); }
                        if (line_read[row][2] == "Delete") { tst = OrderDelete(ticket, clrNONE);
Alert("******* OrderDelete() - " + Symb + " - " + ticket + " - " + line_read[row][11] + " *******");        GlobalVariableDel(Symb + "_ticket_" + line_read[row][11]);
                           if (! tst) Alert("******* OrderDelete() 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();         GlobalVariableDel(Symbol() + "_tim_Balance"); }

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() - tim_port > 30) { tim_port = TimeCurrent();
      for (pos = 0; pos < OrdersTotal(); pos ++) if (OrderSelect(pos, SELECT_BY_POS)/* && Symbol() == OrderSymbol()*/) {
         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"+/*IntegerToString(Period())+"-"+StringSubstr(Symbol(), 0, 1)+
         StringSubstr(Symbol(), 2, 1)+StringSubstr(Symbol(), 3, 1)+StringSubstr(Symbol(), 5, 1)+*/".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
            if (OrderSelect(OrderTicket(), SELECT_BY_TICKET)) {
               GlobalVariableSet(Symbol() + "_Day_Balance", GlobalVariableGet(Symbol() + "_Day_Balance") + OrderProfit());
               if (OrderProfit() < 0.0) GlobalVariableSet(Symbol() + "_Balance", GlobalVariableGet(Symbol() + "_Balance") + OrderProfit()); }      break;
          //Close opened short positions
          case OP_SELL : result = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),5,Pink);   // Slippage
            if (OrderSelect(OrderTicket(), SELECT_BY_TICKET)) {
               GlobalVariableSet(Symbol() + "_Day_Balance", GlobalVariableGet(Symbol() + "_Day_Balance") + OrderProfit());
               if (OrderProfit() < 0.0) GlobalVariableSet(Symbol() + "_Balance", GlobalVariableGet(Symbol() + "_Balance") + OrderProfit()); }      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); }

double f_Profit(string Symb,int Per,bool t_Hst) { double dtmp=0.0;
   for (int pos=0; pos < (t_Hst? OrdersHistoryTotal(): OrdersTotal()); pos ++) if (OrderSelect(pos, SELECT_BY_POS, t_Hst? MODE_HISTORY: MODE_TRADES) &&
      Symb == OrderSymbol() && OrderProfit() && (! t_Hst || OrderOpenTime() > tim_Hst) &&
      StringSubstr(OrderComment(), 5, StringLen(OrderComment()) - 5) == IntegerToString(Per)) dtmp += OrderProfit();
   return dtmp; }

void CreateVLine(datetime Ltim,int Per,bool Buy2,int Epp) {
   ObjectCreate(0, "EA_vert-" + IntegerToString(Ltim), OBJ_VLINE, 0, Ltim > 0? Ltim: Time[0], 0);
   ObjectSetInteger(0, "EA_vert-" + IntegerToString(Ltim), OBJPROP_COLOR, Epp < 2? Buy2? clrGreen: clrPurple: Buy2? clrYellowGreen: clrLightPink);
   ObjectSetInteger(0, "EA_vert-" + IntegerToString(Ltim), OBJPROP_STYLE, STYLE_DOT);
   ObjectSetInteger(0, "EA_vert-" + IntegerToString(Ltim), OBJPROP_WIDTH, /*Per==PERIOD_M5*/Epp? Epp == 1? 1: 3: 2); }

int mOrdrSend(string symb,int type,double lots,double prx,int slip,double sl,double tp,string comm,long mgcnum,datetime exp,int clr) {
      if (GlobalVariableCheck(symb + "_NxtTim")) nxt_tim = GlobalVariableGet(symb + "_NxtTim");          else  nxt_tim = 0;         if (TimeCurrent() >= nxt_tim)
Alert("*** OrderSend() - " + symb + " - " + type + " - " + lots + " - " + prx + " - " + slip + " - " + sl + " - " + tp + " - " + comm + " - " + mgcnum + " - " +
   exp + " - " + clr + " - " + nxt_tim + " - " + TimeToStr(nxt_tim, TIME_DATE|TIME_MINUTES) + " ***");
   return (TimeCurrent() < nxt_tim? -1: OrderSend(symb, type, lots, prx, slip, sl, tp, comm, mgcnum, exp, clr)); }
