//+------------------------------------------------------------------+
//|                  HistoryInfo_mod (08-02-2012 modified by smshev) |
//|                               Copyright © 2011, Vladimir Hlystov |
//|                                         http://cmillion.narod.ru |
//+------------------------------------------------------------------+
#property copyright "Vladimir Hlystov"
#property link      "cmillion@narod.ru"
#property indicator_separate_window
extern string     MagikInfo            = "";             //Магики через запятую, если "" то все магики
extern string     SybmolInfo           = "";             //Торговые инструменты через запятую, если "" то все инструменты
extern datetime   DateInfoStart        = D'01.01.2010';  //начинать с даты
extern datetime   DateInfoEnd          = D'01.01.2030';  //заканчивая датой
extern bool       ScanFromToday        = true;           //сканировать от текущей даты указанный временной период (по умолчанию только текущий день)
extern bool       ScanCurrentWeek      = true;           //сканировать с начала текущей недели
extern bool       ScanCurrentMonth     = false;          //сканировать с начала текущего месяца
extern bool       ShowCurrent          = true;           //показывать текущие открытые сделки
extern int        DaysToScan           = 1;              //сколько дней сканировать от текущей даты в прошлое для режима ScanFromToday=True и ScanCurrentWeek=False и ScanCurrentMonth=False (если <1, то только текущий день)
extern bool       ShowHistory          = true;           //показывать историю за выбранный период
extern bool       ShowMagics           = true;           //показывать строку по магикам (также отключается при ShowHistory = false)
extern bool       ShowMagicsDetails    = true;           //показывать подробную информацию по магикам (также отключается при ShowHistory = false и/или ShowMagics = false)
extern bool       ShowLast10Days       = true;           //показывать результаты торговли за последние 10 дней (также отключается при ShowHistory = false)
extern bool       ShowProfitByStopLoss = true;           //показывать результат сделок при срабатывании их StopLoss на текущем уровне
extern bool       СalcStartDep         = true;           //вычислять депозит на начало периода
extern bool       LogInfoToFile        = true;           //сохранять информацию в файл CSV (в папке <терминал>\experts\files) с именем "HI-<ГОД>-<ТФ>.csv"
extern bool       SendMailInfo         = false;          //отправка информации на почту
extern int        Shift                = 80;             //ширина между столбцами данных
extern color      WhiteColor           = LightGray;      //цвет вывода информации
extern int        WorkingWindow        = 0;              //номер рабочего окно индикатора (для установки нескольких копий индикатора на один график, если 0, то будет работать только в одном окне - в первом, в котором будет найден данный индикатор)
//--------------------------------------------------------------------
string Magiks, Symbl[100], NameInd = "HistoryInfo_v8_mod", Font = "Tahoma",
       txtInfo, txt, TimeSkan, FileName;

double Today[10], HistoryOrders[15][10000], Orders[6][10000], SymbolProfit[2][100], SymbolHistoryProfit[2][100], MagikProfit[11][100], HistoryLot[2][100], TekLot[2][100],
       StartDep = 0.0, AccStartDep = 0.0, TS, ProfitAll, MaxSumDD, AccEquity, AccProfit, AccBalance;

int de_y, de_m, de_d, d_m[12], vert_corr, RealWorkingWindow, StartShift,
    HistoryType[2][100], TekType[2][100], Magik[100],
    Nsymb, Nmag, hn, tn, HistOrdsTot, n_oht = 0, n_oct = 0, LogFileHandle = -1;

datetime PrevTickDate, LOT, OOT, CandleTime = -1, LastLoggedCandle = -1;

bool SecondInstanceInOneWindow = false, isNewDay = false;


//--------------------------------------------------------------------
int deinit()
{
   if(LogInfoToFile && LogFileHandle > 0)
   {  
      int UR = UninitializeReason();
      if(UR == REASON_CHARTCLOSE || UR == REASON_REMOVE || UR == REASON_ACCOUNT || UR == REASON_CHARTCHANGE)
      {
         for(int i = 0; i <= Nsymb; i++)
         {
//            SymbolHistoryProfit[1][i] = MathMin(SymbolProfit[2][i], SymbolHistoryProfit[1][i]);
//            if(SymbolHistoryProfit[1][i] > 0.0)   {SymbolHistoryProfit[1][i] = 0.0;}
            string SimbMaxDD = StringConcatenate(SimbMaxDD, Symbl[i], ";", DoubleToStr(SymbolHistoryProfit[1][i], 2));
            if(i < Nsymb) {SimbMaxDD = StringConcatenate(SimbMaxDD, ";");}
         }
//         if(MaxSumDD > ProfitAll && ProfitAll < 0)  {MaxSumDD = ProfitAll;}
//         if(MaxSumDD > 0.0)   {MaxSumDD = 0.0;}
         FileWrite(LogFileHandle, "Time", TimeToStr(Time[1]), "AccN", AccountNumber(), "AccBal", AccBalance, "AccEq", AccEquity, "AccPr", AccProfit, SimbMaxDD, "MaxDD", MaxSumDD, StringConcatenate("HI_Deinit=", UR));
         FileFlush(LogFileHandle); 
      }
      FileClose(LogFileHandle);
   }
   if(!SecondInstanceInOneWindow) {ObjectsDeleteAll(RealWorkingWindow);}
}
//--------------------------------------------------------------------
int init()
{
   d_m[1] = 31;
   if(MathMod(Year() - 1976, 4) == 0) {d_m[2] = 29;} else {d_m[2] = 28;}
//      d_m[2] = TimeDay(StrToTime(DoubleToStr(de_y, 0) + "." + DoubleToStr(3, 0) + "." + DoubleToStr(1, 0)) - 1);
   d_m[3] = 31;
   d_m[4] = 30;
   d_m[5] = 31;
   d_m[6] = 30;
   d_m[7] = 31;
   d_m[8] = 31;
   d_m[9] = 30;
   d_m[10] = 31;
   d_m[11] = 30;
   d_m[12] = 31;

   if(!ShowHistory && !ShowCurrent) {ShowCurrent = true;}
   if(!ShowHistory) {ShowMagics = false;}
   if(!ShowMagics) {ShowMagicsDetails = false;}
   if(ShowHistory && ShowCurrent) {vert_corr = 0;}
   if(ShowHistory && !ShowCurrent) {vert_corr += -72;}
   if(!ShowHistory && ShowCurrent) {vert_corr += -72;}

   if(
      StringLen(StringTrimLeft(StringTrimRight(StringConcatenate(MagikInfo, "")))) == 0
      ||
      StrToDouble(StringSubstr(StringTrimLeft(StringTrimRight(StringConcatenate(MagikInfo, ""))), 0, 1)) <= 0
     ) {Magiks = "";}
   else {Magiks = StringTrimLeft(StringTrimRight(MagikInfo));}

   if(
      StringLen(StringTrimLeft(StringTrimRight(StringConcatenate(SybmolInfo, "")))) == 0
     ) {SybmolInfo = "";}
   else {SybmolInfo = StringTrimLeft(StringTrimRight(SybmolInfo));}

   SecondInstanceInOneWindow = false;
   if (WorkingWindow == 0)
   {
      RealWorkingWindow = WindowFind(NameInd);
   }
   else
   {
      RealWorkingWindow = WorkingWindow;
   }
   if(ObjectFind("hi8_copyright" + RealWorkingWindow) >= 0) {SecondInstanceInOneWindow = true;}

   StartShift = 180;
   LOT = DateInfoStart;
   isNewDay = true;
   HistOrdsTot = 0;
   hn = HistoryOrders();
   PrevTickDate = 0;
   
   CandleTime = Time[0];
   if(LogInfoToFile)
   {
      FileName = StringConcatenate("HI-", DoubleToStr(Year(), 0), "-", DoubleToStr(Period(), 0), ".csv");
      LogFileHandle = FileOpen(FileName, FILE_CSV|FILE_READ|FILE_WRITE,';');
      if(LogFileHandle < 0)   //файл не найден или занят
      {
         LogFileHandle = FileOpen(FileName, FILE_CSV|FILE_WRITE,';');
         if(LogFileHandle > 0)
         {
            FileClose(LogFileHandle);
            LogFileHandle = FileOpen(FileName, FILE_CSV|FILE_READ|FILE_WRITE,';');
            if(LogFileHandle > 0)
            {
               Print(NameInd, " ", Symbol(), " ", Period(), "Предупреждение!! Не удалось создать заново LOG-файл - ", FileName, ". Файл был перезаписан пустым. ERROR - ", GetLastError());
            }
            else
            {
               Print(NameInd, " ", Symbol(), " ", Period(), "Ошибка!! Не удалось создать заново LOG-файл - ", FileName, ". ERROR - ", GetLastError());
               LogInfoToFile = false;
            }
         }
         else   //не удалось создать файл
         {
            Print(NameInd, " ", Symbol(), " ", Period(), "Ошибка!! Не удалось создать заново LOG-файл - ", FileName, ". ERROR - ", GetLastError());
            LogInfoToFile = false;
         }
      }
      
      if(LogInfoToFile && LogFileHandle > 0)
      {
         while(!FileIsEnding(LogFileHandle))
         {
            if(FileReadString(LogFileHandle) == "AccN")
            {
               if(FileReadString(LogFileHandle) != DoubleToStr(AccountNumber(), 0))    //файл от другого счета
               {
                  FileClose(LogFileHandle);
                  LogFileHandle = FileOpen(FileName, FILE_CSV|FILE_WRITE,';');
                  if(LogFileHandle > 0)
                  {
                     FileClose(LogFileHandle);
                     LogFileHandle = FileOpen(FileName, FILE_CSV|FILE_READ|FILE_WRITE,';');
                     if(LogFileHandle < 0)   //не удалось создать файл
                     {
                        Print(NameInd, " ", Symbol(), " ", Period(), "Ошибка!! Не удалось открыть LOG-файл - ", FileName, ". Обнаружен лог с другого счета. Файл был перезаписан пустым. ERROR - ", GetLastError());
                        LogInfoToFile = false;
                     }
                     break;
                  }
                  else
                  {
                     Print(NameInd, " ", Symbol(), " ", Period(), "Ошибка!! Не удалось открыть создать заново LOG-файл - ", FileName, ". ERROR - ", GetLastError());
                     LogInfoToFile = false;
                     break;
                  }
               }

               double SymbMDD = 0.0;
               string TmpLoggedStr;
               while(!FileIsEnding(LogFileHandle))
               {
                  if(FileReadString(LogFileHandle) == "MaxDD")
                  {
                     SymbMDD = StrToDouble(FileReadString(LogFileHandle));
                     if(MaxSumDD > SymbMDD && SymbMDD < 0) {MaxSumDD = SymbMDD;}
                  }
               }         
               
               break;
            }
         }         
         FileSeek(LogFileHandle, 0, SEEK_END);
      }
   }
      
   return;
}   
//--------------------------------------------------------------------
int start()                                  
{
   if(WorkingWindow == 0 && WindowOnDropped() > 0) {RealWorkingWindow = WindowOnDropped();}
   if(SecondInstanceInOneWindow)
      {
         Print(NameInd, " ", Symbol(), " ", Period(), " - Detected another running instance of the indicator in the same terminal window! Remove one of the copies or assign a different number of working window!");
         return;
      }
   if(RealWorkingWindow <= 0)
      {
         RealWorkingWindow = WindowFind(NameInd);
      }
   if(RealWorkingWindow > (WindowsTotal() - 1))
      {
         Alert(NameInd, " ", Symbol(), " ", Period(), " - Specified in the settings of the indicator operating window has been found! ", "Specified window number: ", WorkingWindow, ", windows founded:", WindowsTotal() - 1);
         return;
      }
   if((WindowFind(NameInd) >= 0 && RealWorkingWindow < 0 && ObjectFind("hi8_copyright" + WindowFind(NameInd)) >= 0) || (RealWorkingWindow > (WindowsTotal() - 1)))
      {
         Print(NameInd, " ", Symbol(), " ", Period(), " - Specified in the settings of the indicator operating window has been found! ", "Specified window number: ", WorkingWindow, ", windows founded:", WindowsTotal() - 1);
         return;
      }

   n_oht = OrdersHistoryTotal();
   DateInfoEnd = TimeCurrent();
   if(
      TimeDay(DateInfoEnd) > TimeDay(PrevTickDate)
      ||
      TimeMonth(DateInfoEnd) > TimeMonth(PrevTickDate)
      ||
      TimeYear(DateInfoEnd) > TimeYear(PrevTickDate)
     )
      {
         ObjectsDeleteAll(RealWorkingWindow);
         isNewDay = true;
         hn = HistoryOrders();
         if(ObjectFind("hi8_copyright" + RealWorkingWindow) <= 0) {ObjectCreate("hi8_copyright" + RealWorkingWindow, OBJ_LABEL, RealWorkingWindow, 0, 0);}
         ObjectSet("hi8_copyright" + RealWorkingWindow, OBJPROP_CORNER, 2);
         ObjectSet("hi8_copyright" + RealWorkingWindow, OBJPROP_YDISTANCE, 5);
         ObjectSet("hi8_copyright" + RealWorkingWindow, OBJPROP_XDISTANCE, 5);
         ObjectSetText("hi8_copyright" + RealWorkingWindow, "Copyright © 2010 cmillion@narod.ru", 8, Font, WhiteColor);
         Text("DateInfo" + RealWorkingWindow, StringConcatenate("The range of dates from  ", TimeToStr(DateInfoStart + 1, TIME_DATE), " to ", TimeToStr(DateInfoEnd, TIME_DATE), " total ", TimeSkan), 430, 2, WhiteColor, 8, RealWorkingWindow); //шапка
         if(Magiks == "") txt = "Magiс-numbers - Any";
         else  txt = StringConcatenate("Magiс-numbers - ", Magiks);
         Text("Magik" + RealWorkingWindow, txt, 740, 2, WhiteColor, 8, RealWorkingWindow);//шапка
         Text("i0" + RealWorkingWindow, StringConcatenate("Information on the account  ", AccountNumber(), " / ", AccountCompany()), 100, 2, WhiteColor, 8, RealWorkingWindow);//шапка
         if(ShowHistory) {Text("Orders h" + RealWorkingWindow, " ", 100, 35, WhiteColor, 8, RealWorkingWindow);}
         if(ShowCurrent) {Text("Orders f" + RealWorkingWindow," ", 100, 118 + vert_corr, WhiteColor, 8, RealWorkingWindow);}
         Text("i2" + RealWorkingWindow, " ", 5, 25, WhiteColor, 8, RealWorkingWindow);
         Text("i3" + RealWorkingWindow, " ", 5, 35, WhiteColor, 8, RealWorkingWindow);
         Text("i4" + RealWorkingWindow, " ", 5, 45, WhiteColor, 8, RealWorkingWindow);
         Text("i5" + RealWorkingWindow, " ", 5, 55, WhiteColor, 8, RealWorkingWindow);
         Text("i6" + RealWorkingWindow, " ", 5, 65, WhiteColor, 8, RealWorkingWindow);
         Text("i7" + RealWorkingWindow, " ", 5, 85, WhiteColor, 8, RealWorkingWindow);
         Text("i8" + RealWorkingWindow, " ", 5, 95, WhiteColor, 8, RealWorkingWindow);
         Text("i9" + RealWorkingWindow, " ", 5, 105, WhiteColor, 8, RealWorkingWindow);
         Text("i10" + RealWorkingWindow, " ", 5, 115, WhiteColor, 8, RealWorkingWindow);
         Text("i11" + RealWorkingWindow, " ", 5, 125, WhiteColor, 8, RealWorkingWindow);
         if(ShowHistory) {Text("History" + RealWorkingWindow, "History:", 100, 20, SteelBlue, 10, RealWorkingWindow);}
         if(ShowCurrent) {Text("Current" + RealWorkingWindow, "Current:", 100, 103 + vert_corr, SteelBlue, 10, RealWorkingWindow);}
         if(ShowHistory && ShowMagics) {Text("MagikP" + RealWorkingWindow, "Magic №:", 100, 176 + vert_corr, SteelBlue, 10, RealWorkingWindow);}
         //---
      }

   PrevTickDate = DateInfoEnd;

   if(ShowHistory)
   {
      hn = HistoryOrders();
      if(hn > 10000) {Alert("Buffers overflow", n_oht); return;}
      ArrayInitialize(HistoryType, 0.0);
      ArrayInitialize(HistoryLot, 0.0);
      for(int i = 0; i <= Nsymb; i++)
      {                                               
         SymbolHistoryProfit[0][i] = 0;
         for(int j = 0; j < hn; j++)
         {
            if(i == HistoryOrders[0][j])//Symbol
            {
               SymbolHistoryProfit[0][i] += HistoryOrders[2][j];//профит 
               if(HistoryOrders[1][j] == OP_BUY)  {HistoryType[0][i]++; HistoryLot[0][i] += HistoryOrders[3][j];}
               if(HistoryOrders[1][j] == OP_SELL) {HistoryType[1][i]++; HistoryLot[1][i] += HistoryOrders[3][j];}
            }
         }
      }

      double ProfitAll = 0.0, ProfitAllSL = 0.0, SumBLot = 0.0, SumSLot = 0.0;
      int SumB = 0, SumS = 0, SumBp = 0, SumBl = 0, SumSp = 0, SumSl = 0,
          SumpB = 0, SumpS = 0, SumpBp = 0, SumpBl = 0, SumpSp = 0, SumpSl = 0;

      if(SendMailInfo) txtInfo = StringConcatenate("Account statement ", AccountNumber(), " ", AccountCompany(), " date ", TimeToStr(TimeCurrent(), TIME_DATE|TIME_MINUTES), "\n\nHistory\n====================\n");
      for(i = 0; i <= Nsymb; i++)
      {  
         ProfitAll += SymbolHistoryProfit[0][i];
         SumB += HistoryType[0][i];
         SumS += HistoryType[1][i];
         SumBLot += HistoryLot[0][i];
         SumSLot += HistoryLot[1][i];

         if (StringLen(Symbl[i]) < 2) continue;
         Text(Symbl[i] + RealWorkingWindow, Symbl[i],                                                                                                          StartShift + Shift * i, 20, SteelBlue, 10, RealWorkingWindow);//символ
         Text(StringConcatenate(Symbl[i], "Hprofit", RealWorkingWindow), DoubleToStr(SymbolHistoryProfit[0][i], 2),                                            StartShift + Shift * i, 35, Color(SymbolHistoryProfit[0][i]), 9, RealWorkingWindow);//профит
         Text(StringConcatenate(Symbl[i], "Hlot",    RealWorkingWindow), "Type  Lot ",                                                                         StartShift + Shift * i, 48, SteelBlue, 8, RealWorkingWindow);
         Text(StringConcatenate(Symbl[i], "Hb",      RealWorkingWindow), StringConcatenate("B ", HistoryType[0][i], "    ", DoubleToStr(HistoryLot[0][i], 2)), StartShift + Shift * i, 60, Color(SymbolHistoryProfit[0][i]), 8, RealWorkingWindow);//всего Buy
         Text(StringConcatenate(Symbl[i], "Hs",      RealWorkingWindow), StringConcatenate("S ", HistoryType[1][i], "    ", DoubleToStr(HistoryLot[1][i], 2)), StartShift + Shift * i, 70, Color(SymbolHistoryProfit[0][i]), 8, RealWorkingWindow);//всего Sell
         if(LogInfoToFile)
         {
            SymbolHistoryProfit[1][i] = MathMin(SymbolProfit[2][i], SymbolHistoryProfit[1][i]);
            if(SymbolHistoryProfit[1][i] > 0.0)   {SymbolHistoryProfit[1][i] = 0.0;}
            MaxSumDD = MathMin(SymbolHistoryProfit[1][i], MaxSumDD);
            if(MaxSumDD > 0)  {MaxSumDD = 0.0;}
            Text(StringConcatenate(Symbl[i], "HMDD",    RealWorkingWindow), "Max.drawdown",                                                                    StartShift + Shift * i, 80, SteelBlue, 8, RealWorkingWindow);
            Text(StringConcatenate(Symbl[i], "HMDDp",   RealWorkingWindow), DoubleToStr(SymbolHistoryProfit[1][i], 2),                                         StartShift + Shift * i, 90, Color(SymbolHistoryProfit[0][i]), 8, RealWorkingWindow);
   //         if(SymbolHistoryProfit[1][i] <= SymbolProfit[2][i])  {Text(StringConcatenate(Symbl[i], "HMDDp",   RealWorkingWindow), DoubleToStr(SymbolHistoryProfit[1][i], 2),                                            StartShift + Shift * i, 90, Color(SymbolHistoryProfit[0][i]), 8, RealWorkingWindow);}
   //                                                         else {Text(StringConcatenate(Symbl[i], "HMDDp",   RealWorkingWindow), DoubleToStr(SymbolHistoryProfit[1][i], 2),                                            StartShift + Shift * i, 90, Color(SymbolProfit[0][i]), 8, RealWorkingWindow);}
         }
         
         if(SendMailInfo) {txtInfo = StringConcatenate(txtInfo, Symbl[i], "   Buy ", Ch32(HistoryType[0][i], 0), "   lot ", Ch32(HistoryLot[0][i], 2),"   Sell ", Ch32(HistoryType[1][i], 0), "   lot ", Ch32(HistoryLot[1][i], 2), "   ", DoubleToStr(SymbolHistoryProfit[0][i], 2), "\n");}
      }
      if(SendMailInfo) {txtInfo = StringConcatenate(txtInfo, "====================\nTOTAL", " ", DoubleToStr(ProfitAll,2), "\n\n");}

      if((hn + tn) > 0)
      {
         Text("symbolAll"  + RealWorkingWindow, "Total:",                                                                                         StartShift + Shift * i, 20, SteelBlue, 10, RealWorkingWindow);//шапка
         Text("profitAll"  + RealWorkingWindow, DoubleToStr(ProfitAll, 2),                                                                        StartShift + Shift * i, 35, Color(ProfitAll), 10, RealWorkingWindow);//общий профит
         if(StartDep != 0.0) {Text("profitAll%" + RealWorkingWindow, StringConcatenate(DoubleToStr(100 * ProfitAll / StartDep, 1), "%"),          StartShift + Shift * (i + 1), 35, Color(ProfitAll), 10, RealWorkingWindow);}//общий профит
         Text("SumLot"     + RealWorkingWindow, "Type  Lot ",                                                                                     StartShift + Shift * i, 48, SteelBlue, 8, RealWorkingWindow);//всего Buy
         Text("SumBLot"    + RealWorkingWindow, StringConcatenate("B ", SumB, "    ", DoubleToStr(SumBLot, 2)),                                   StartShift + Shift * i, 60, Color(ProfitAll), 8, RealWorkingWindow);//общий профит
         Text("SumSLot"    + RealWorkingWindow, StringConcatenate("S ", SumS, "    ", DoubleToStr(SumSLot, 2)),                                   StartShift + Shift * i, 70, Color(ProfitAll), 8, RealWorkingWindow);//общий профит
         if(LogInfoToFile)
         {
            Text(StringConcatenate(Symbl[i], "HMDDsum",    RealWorkingWindow), "Max.drawdown",                                                    StartShift + Shift * i, 80, SteelBlue, 8, RealWorkingWindow);
            Text(StringConcatenate(Symbl[i], "HMDDpsum",   RealWorkingWindow), DoubleToStr(MaxSumDD, 2),                                          StartShift + Shift * i, 90, Color(ProfitAll), 8, RealWorkingWindow);
         }
      }

      if(ShowLast10Days)
      {
         i += 1;
         for(j = 0; j < 10; j++)
         { 
            Text("Yesterday"  + RealWorkingWindow + j, StringConcatenate(TimeToStr(iTime(NULL, PERIOD_D1, j),TIME_DATE), "  ", DoubleToStr(Today[j], 2)), StartShift + Shift * (i + 1), 20 + 12 * j, Color(Today[j]), 10, RealWorkingWindow);
            if(StartDep != 0.0) {Text("Yesterday%" + RealWorkingWindow + j, StringConcatenate(DoubleToStr(100 * Today[j] / StartDep, 1), "%"), StartShift + Shift * (i + 1) + 130, 20 + 12 * j, Color(Today[j]), 10, RealWorkingWindow);}
         }
      }
      ObjectSetText("Orders h" + RealWorkingWindow, StringConcatenate("Orders ", hn), 8, Font, WhiteColor);


      if(ShowMagics && (hn + tn) > 0)
      {
         ProfitAll = 0;
         SumBLot = 0.0;
         SumSLot = 0.0;
         SumB = 0;
         SumS = 0;
         SumpB = 0;
         SumpS = 0;
         
         for(i = 0; i <= Nmag; i++)
         {
            if(Magik[i] >= 0)
            Text(StringConcatenate(Magik[i], "M",       RealWorkingWindow), DoubleToStr(Magik[i], 0),          StartShift + Shift * i, 176 + vert_corr, SteelBlue, 10, RealWorkingWindow);//символ
            Text(StringConcatenate(Magik[i], "profitM", RealWorkingWindow), DoubleToStr(MagikProfit[0][i], 2), StartShift + Shift * i, 188 + vert_corr, Color(MagikProfit[0][i]), 10, RealWorkingWindow);//профит
            ProfitAll += MagikProfit[0][i];

            if(ShowMagicsDetails)
               {
                  SumBp += MagikProfit[1][i];
                  SumBl += MagikProfit[2][i];
                  SumSp += MagikProfit[3][i];
                  SumSl += MagikProfit[4][i];
                  SumB += (MagikProfit[1][i] + MagikProfit[2][i]);
                  SumS += (MagikProfit[3][i] + MagikProfit[4][i]);
                  SumpBp += MagikProfit[5][i];
                  SumpBl += MagikProfit[6][i];
                  SumpSp += MagikProfit[7][i];
                  SumpSl += MagikProfit[8][i];
                  SumBLot += MagikProfit[9][i];
                  SumSLot += MagikProfit[10][i];
                  SumpB += (MagikProfit[5][i] + MagikProfit[6][i]);
                  SumpS += (MagikProfit[7][i] + MagikProfit[8][i]);
                  Text(StringConcatenate(Magik[i], "Mlot",    RealWorkingWindow), "Type  Lot ",                                                                         StartShift + Shift * i, 201 + vert_corr, SteelBlue, 8, RealWorkingWindow);
                  Text(StringConcatenate(Magik[i], "Mb",      RealWorkingWindow), StringConcatenate("B ", MagikProfit[1][i] + MagikProfit[2][i], "    ", DoubleToStr(MagikProfit[9][i], 2)), StartShift + Shift * i, 212 + vert_corr, Color(MagikProfit[0][i]), 8, RealWorkingWindow);//всего Buy
                  Text(StringConcatenate(Magik[i], "Ms",      RealWorkingWindow), StringConcatenate("S ", MagikProfit[3][i] + MagikProfit[4][i], "    ", DoubleToStr(MagikProfit[10][i], 2)), StartShift + Shift * i, 222 + vert_corr, Color(MagikProfit[0][i]), 8, RealWorkingWindow);//всего Sell
                  Text(StringConcatenate(Magik[i], "Mdeto",   RealWorkingWindow), "Orders (P/L)",                                                                       StartShift + Shift * i, 232 + vert_corr, SteelBlue, 8, RealWorkingWindow);
                  Text(StringConcatenate(Magik[i], "Mdetocb", RealWorkingWindow), StringConcatenate("B ", DoubleToStr(MagikProfit[1][i] + MagikProfit[2][i], 0), "   (", DoubleToStr(MagikProfit[1][i], 0), "/", DoubleToStr(MagikProfit[2][i], 0),")"),                  StartShift + Shift * i, 242 + vert_corr, Color(MagikProfit[0][i]), 8, RealWorkingWindow);
                  Text(StringConcatenate(Magik[i], "Mdetocs", RealWorkingWindow), StringConcatenate("S ", DoubleToStr(MagikProfit[3][i] + MagikProfit[4][i], 0), "   (", DoubleToStr(MagikProfit[3][i], 0), "/", DoubleToStr(MagikProfit[4][i], 0),")"),                  StartShift + Shift * i, 252 + vert_corr, Color(MagikProfit[0][i]), 8, RealWorkingWindow);
                  Text(StringConcatenate(Magik[i], "Mdetp",   RealWorkingWindow), "Pips (P/L)",                                                                         StartShift + Shift * i, 263 + vert_corr, SteelBlue, 8, RealWorkingWindow);
                  Text(StringConcatenate(Magik[i], "Mdetpcb", RealWorkingWindow), StringConcatenate("B ", DoubleToStr(MagikProfit[5][i] + MagikProfit[6][i], 0), " (", DoubleToStr(MagikProfit[5][i], 0), "/", DoubleToStr(MagikProfit[6][i], 0),")"),                  StartShift + Shift * i, 272 + vert_corr, Color(MagikProfit[0][i]), 8, RealWorkingWindow);
                  Text(StringConcatenate(Magik[i], "Mdetpcs", RealWorkingWindow), StringConcatenate("S ", DoubleToStr(MagikProfit[7][i] + MagikProfit[8][i], 0), " (", DoubleToStr(MagikProfit[7][i], 0), "/", DoubleToStr(MagikProfit[8][i], 0),")"),                  StartShift + Shift * i, 282 + vert_corr, Color(MagikProfit[0][i]), 8, RealWorkingWindow);
               }
         }
         Text("magAll" +                                RealWorkingWindow, "Total:",                           StartShift + Shift * i, 176 + vert_corr, SteelBlue, 10, RealWorkingWindow);//шапка
         Text("profitAllM" +                            RealWorkingWindow, DoubleToStr(ProfitAll, 2),          StartShift + Shift * i, 188 + vert_corr, Color(ProfitAll), 10, RealWorkingWindow);//общий профит
         if(ShowMagicsDetails)
            {
               Text(StringConcatenate(Magik[i], "Mdetlall",   RealWorkingWindow), "Type  Lot ",                StartShift + Shift * i, 201 + vert_corr, SteelBlue, 8, RealWorkingWindow);
               Text(StringConcatenate("MITdetlcb", RealWorkingWindow), StringConcatenate("B ", DoubleToStr(SumB, 0), "    ", DoubleToStr(SumBLot, 2)),                  StartShift + Shift * i, 212 + vert_corr, Color(ProfitAll), 8, RealWorkingWindow);
               Text(StringConcatenate("MITdetlcs", RealWorkingWindow), StringConcatenate("S ", DoubleToStr(SumS, 0), "    ", DoubleToStr(SumSLot, 2)),                  StartShift + Shift * i, 222 + vert_corr, Color(ProfitAll), 8, RealWorkingWindow);
               Text(StringConcatenate(Magik[i], "Mdetall",   RealWorkingWindow), "Orders (P/L)",               StartShift + Shift * i, 232 + vert_corr, SteelBlue, 8, RealWorkingWindow);
               Text(StringConcatenate("MITdetocb", RealWorkingWindow), StringConcatenate("B ", DoubleToStr(SumB, 0), "   (", SumBp, "/", SumBl, ")"),                  StartShift + Shift * i, 242 + vert_corr, Color(ProfitAll), 8, RealWorkingWindow);
               Text(StringConcatenate("MITdetocs", RealWorkingWindow), StringConcatenate("S ", DoubleToStr(SumS, 0), "   (", SumSp, "/", SumSl, ")"),                  StartShift + Shift * i, 252 + vert_corr, Color(ProfitAll), 8, RealWorkingWindow);
               if(SumB != 0.0) {Text(StringConcatenate("MITdetocb%", RealWorkingWindow), StringConcatenate("", DoubleToStr(MathRound(10000 * SumBp / SumB) / 100, 2), "%"),                  StartShift + Shift * (i + 1), 242 + vert_corr, Color(ProfitAll), 8, RealWorkingWindow);}
                          else {Text(StringConcatenate("MITdetocb%", RealWorkingWindow), StringConcatenate("", "   0.00", "%"),                  StartShift + Shift * (i + 1), 242 + vert_corr, Color(ProfitAll), 8, RealWorkingWindow);}
               if(SumS != 0.0) {Text(StringConcatenate("MITdetocs%", RealWorkingWindow), StringConcatenate("", DoubleToStr(MathRound(10000 * SumSp / SumS) / 100, 2), "%"),                  StartShift + Shift * (i + 1), 252 + vert_corr, Color(ProfitAll), 8, RealWorkingWindow);}
                          else {Text(StringConcatenate("MITdetocs%", RealWorkingWindow), StringConcatenate("", "   0.00", "%"),                  StartShift + Shift * (i + 1), 252 + vert_corr, Color(ProfitAll), 8, RealWorkingWindow);}
               if((SumB + SumS) != 0.0) {Text(StringConcatenate("MITdetocall", RealWorkingWindow), StringConcatenate(DoubleToStr(SumB + SumS, 0), " (", SumBp + SumSp, "/", SumBl + SumSl, ") ", DoubleToStr(MathRound(10000 * (SumBp + SumSp) / (SumB + SumS)) / 100, 2), "%"),                  StartShift + Shift * (i + 1.5), 247 + vert_corr, Color(ProfitAll), 8, RealWorkingWindow);}
                                   else {Text(StringConcatenate("MITdetocall", RealWorkingWindow), StringConcatenate("", "   0.00", "%"),                  StartShift + Shift * (i + 1.5), 247 + vert_corr, Color(ProfitAll), 8, RealWorkingWindow);}
               Text(StringConcatenate(Magik[i], "Mdetpall",   RealWorkingWindow), "Pips (P/L)",                StartShift + Shift * i, 263 + vert_corr, SteelBlue, 8, RealWorkingWindow);
               Text(StringConcatenate("MITdetpcb", RealWorkingWindow), StringConcatenate("B ", DoubleToStr(SumpB, 0), " (", SumpBp, "/", SumpBl, ")"),                  StartShift + Shift * i, 272 + vert_corr, Color(ProfitAll), 8, RealWorkingWindow);
               Text(StringConcatenate("MITdetpcs", RealWorkingWindow), StringConcatenate("S ", DoubleToStr(SumpS, 0), " (", SumpSp, "/", SumpSl, ")"),                  StartShift + Shift * i, 282 + vert_corr, Color(ProfitAll), 8, RealWorkingWindow);
            }
      }
   }
   //==================
   //--- текущие ордера
   //==================
   if(ShowCurrent)
   {
      tn = TekOrders();

      if(tn > 10000) {Alert("Buffers overflow", n_oct); return;}
      ArrayInitialize(TekType, 0.0);
      ArrayInitialize(TekLot, 0.0);
      for(i = 0; i <= Nsymb; i++)
      {
         SymbolProfit[0][i] = 0;
         SymbolProfit[1][i] = 0;
         for(j = 0; j < tn; j++)
         {
            if(i == Orders[0][j])//Symbol
            {
               SymbolProfit[0][i] += Orders[2][j];//профит
               SymbolProfit[1][i] += Orders[5][j];//профит по StopLoss-у
               if(Orders[1][j] == OP_BUY)  {TekType[0][i]++; TekLot[0][i] += Orders[3][j];}
               if(Orders[1][j] == OP_SELL) {TekType[1][i]++; TekLot[1][i] += Orders[3][j];}
            }
         }
         if(SymbolProfit[0][i] < SymbolHistoryProfit[1][i]) {SymbolHistoryProfit[1][i] = SymbolProfit[0][i];}
         if(SymbolProfit[2][i] < SymbolHistoryProfit[1][i]) {SymbolProfit[2][i] = SymbolProfit[0][i];}
      }

      ProfitAll = 0.0;
      ProfitAllSL = 0.0;
      SumBLot = 0.0;
      SumSLot = 0.0;
      SumB = 0;
      SumS = 0;
      if(txtInfo != "" && SendMailInfo) txtInfo = StringConcatenate(txtInfo, "\nFloating\n====================\n");

      for(i = 0; i <= Nsymb; i++)
      {  
         if(StringLen(Symbl[i]) < 2) continue;
         Text(StringConcatenate(Symbl[i], "T",       RealWorkingWindow), Symbl[i],                                                                StartShift + Shift * i, 103  + vert_corr, SteelBlue, 10, RealWorkingWindow);//символ
         Text(StringConcatenate(Symbl[i], "profitT", RealWorkingWindow), DoubleToStr(SymbolProfit[0][i], 2),                                      StartShift + Shift * i, 115 + vert_corr, Color(SymbolProfit[0][i]), 10, RealWorkingWindow);//профит
         if(ShowProfitByStopLoss)//профит по текущему StopLoss
            {
               if(SymbolProfit[1][i] != 0) 
                  {Text(StringConcatenate(Symbl[i], "profitSLT", RealWorkingWindow),   DoubleToStr(SymbolProfit[1][i], 2),                        StartShift + Shift * i, 127 + vert_corr, Color(SymbolProfit[1][i]), 10, RealWorkingWindow);}
               else
                  {Text(StringConcatenate(Symbl[i], "profitSLT", RealWorkingWindow),   " ",                                                       StartShift + Shift * i, 127 + vert_corr, Color(SymbolProfit[1][i]), 10, RealWorkingWindow);}
            }
         Text(StringConcatenate(Symbl[i], "Tlot", RealWorkingWindow), "Type  Lot ",                                                               StartShift + Shift * i, 143 + vert_corr, SteelBlue, 8, RealWorkingWindow);
         Text(StringConcatenate(Symbl[i], "bT",  RealWorkingWindow), StringConcatenate("B ", TekType[0][i], "    ", DoubleToStr(TekLot[0][i],2)), StartShift + Shift * i, 155 + vert_corr, Color(SymbolProfit[0][i]), 8, RealWorkingWindow);//всего Buy
         Text(StringConcatenate(Symbl[i], "sT",  RealWorkingWindow), StringConcatenate("S ", TekType[1][i], "    ", DoubleToStr(TekLot[1][i],2)), StartShift + Shift * i, 165 + vert_corr, Color(SymbolProfit[0][i]), 8, RealWorkingWindow);//всего Sell
         ProfitAll   += SymbolProfit[0][i];
         ProfitAllSL += SymbolProfit[1][i];
         SumB += TekType[0][i];
         SumS += TekType[1][i];
         SumBLot += TekLot[0][i];
         SumSLot += TekLot[1][i];
         
         MaxSumDD = MathMin(MaxSumDD, MathMin(SymbolHistoryProfit[1][i], ProfitAll));
         if(MaxSumDD > 0)  {MaxSumDD = 0.0;}
         if(txtInfo != "" && SendMailInfo && (TekType[0][i] != 0 || TekType[1][i] != 0)) {txtInfo = StringConcatenate(txtInfo, Symbl[i], "   Buy ", Ch32(TekType[0][i], 0), "   lot ", Ch32(TekLot[0][i], 2),"   Sell ",Ch32(TekType[1][i], 0), "   lot ", Ch32(TekLot[1][i], 2), "   ", DoubleToStr(SymbolProfit[0][i], 2), "(", DoubleToStr(SymbolProfit[1][i], 2), ")", "\n");}
      }
      if(n_oct > 0)
      {
         Text("TotalCurr" +   RealWorkingWindow, "Total:", StartShift + Shift * i, 103 + vert_corr, SteelBlue, 10, RealWorkingWindow);
         if(txtInfo != "") {txtInfo = StringConcatenate(txtInfo, "====================\nTOTAL ", DoubleToStr(ProfitAll, 2), "(", DoubleToStr(ProfitAllSL, 2), ")", "\n\n");}
         Text("profitAllT"  + RealWorkingWindow, DoubleToStr(ProfitAll, 2), StartShift + Shift * i, 115 + vert_corr, Color(ProfitAll), 10, RealWorkingWindow);//общий профит
         if(StartDep != 0) {Text("profitAllT%" + RealWorkingWindow, StringConcatenate(DoubleToStr(100 * ProfitAll/StartDep,1), "%"), StartShift + Shift * (i + 1), 115 + vert_corr, Color(ProfitAll), 10, RealWorkingWindow);}//общий профит%

         Text("TSumLot"     + RealWorkingWindow, "Type  Lot ",                                                            StartShift + Shift * i, 143 + vert_corr, SteelBlue, 8, RealWorkingWindow);//всего Buy
         Text("TSumBLot"    + RealWorkingWindow, StringConcatenate("B ", SumB, "    ", DoubleToStr(SumBLot, 2)),          StartShift + Shift * i, 155 + vert_corr, Color(ProfitAll), 8, RealWorkingWindow);//общий профит
         Text("TSumSLot"    + RealWorkingWindow, StringConcatenate("S ", SumS, "    ", DoubleToStr(SumSLot, 2)),          StartShift + Shift * i, 165 + vert_corr, Color(ProfitAll), 8, RealWorkingWindow);//общий профит
         if(ShowProfitByStopLoss)//общий профит по StopLoss-ам
         {
            if(ProfitAllSL != 0)
            {
               Text("profitAllSLT" + RealWorkingWindow, DoubleToStr(ProfitAllSL, 2), StartShift + Shift * (i), 127 + vert_corr, Color(ProfitAllSL), 10, RealWorkingWindow);
               if(StartDep != 0) {Text("profitAllSLT%" + RealWorkingWindow, StringConcatenate(DoubleToStr(100 * ProfitAllSL / StartDep,1), "%"), StartShift + Shift * (i + 1), 127 + vert_corr, Color(ProfitAllSL), 10, RealWorkingWindow);}
            }
            else
            {
               Text("profitAllSLT"  + RealWorkingWindow, " ", StartShift + Shift * (i), 127 + vert_corr, Color(ProfitAllSL), 10, RealWorkingWindow);
               Text("profitAllSLT%" + RealWorkingWindow, " ", StartShift + Shift * (i + 1), 127 + vert_corr, Color(ProfitAllSL), 10, RealWorkingWindow);
            }
         }
      }
      if((n_oct - tn) > 0) {ObjectSetText("Orders f" + RealWorkingWindow, StringConcatenate("Orders ", tn, "+", n_oct - tn), 8, Font, WhiteColor);}
                      else {ObjectSetText("Orders f" + RealWorkingWindow, StringConcatenate("Orders ", tn), 8, Font, WhiteColor);}
   }

   //---

   AccEquity = AccountEquity();
   AccProfit = AccountBalance() - AccStartDep;
   AccBalance = AccountBalance();
   ObjectSetText("i2" + RealWorkingWindow, StringConcatenate("Symbols  ", Nsymb+1), 8, Font, WhiteColor);
   ObjectSetText("i3" + RealWorkingWindow, StringConcatenate("Balance   ", DoubleToStr(AccBalance, 2)), 8, Font, WhiteColor);
   ObjectSetText("i4" + RealWorkingWindow, StringConcatenate("Equity     ", DoubleToStr(AccEquity,2)), 8, Font, WhiteColor);
   if(СalcStartDep)  {ObjectSetText("i5" + RealWorkingWindow, StringConcatenate("Balance on ", TimeToStr(DateInfoStart + 1, TIME_DATE), "  ", DoubleToStr(StartDep, 2)), 8, Font, WhiteColor);}
   if(AccountMargin() != 0.0) {ObjectSetText("i6" + RealWorkingWindow, StringConcatenate("FreeMar. ", DoubleToStr(AccountFreeMargin(), 2), " (", DoubleToStr(100 * AccountEquity() / AccountMargin(), 2), "%)"), 8, Font, WhiteColor);}
   ObjectSetText("i7" + RealWorkingWindow, StringConcatenate("Deposit   ", DoubleToStr(AccStartDep, 2)), 8, Font, WhiteColor);
   ObjectSetText("i8" + RealWorkingWindow, StringConcatenate("Profit      ", DoubleToStr(AccProfit, 2)), 8, Font, WhiteColor);
   ObjectSetText("i9" + RealWorkingWindow, StringConcatenate("Leverage ", "1:", AccountLeverage()), 8, Font, WhiteColor);
   ObjectSetText("i10" + RealWorkingWindow, StringConcatenate("Currency ", AccountCurrency()), 8, Font, WhiteColor);
   if(IsDemo())   {txtInfo = "Demo acc.";}  else  {txtInfo = "Real acc.";}
   ObjectSetText("i11" + RealWorkingWindow, StringConcatenate("Type       ", txtInfo), 8, Font, WhiteColor);


   if(LogInfoToFile && LogFileHandle > 0)
   {
      string SimbMaxDD = "";

      if(CandleTime < Time[0] && LastLoggedCandle < Time[0])
      {
         for(i = 0; i <= Nsymb; i++)
         {
//            SymbolHistoryProfit[1][i] = MathMin(SymbolProfit[2][i], SymbolHistoryProfit[1][i]);
//            if(SymbolHistoryProfit[1][i] > 0.0)   {SymbolHistoryProfit[1][i] = 0.0;}
            SimbMaxDD = StringConcatenate(SimbMaxDD, Symbl[i], ";", DoubleToStr(SymbolHistoryProfit[1][i], 2));
            if(i < Nsymb) {SimbMaxDD = StringConcatenate(SimbMaxDD, ";");}
         }
//         if(MaxSumDD > ProfitAll && ProfitAll < 0)  {MaxSumDD = ProfitAll;}
         FileWrite(LogFileHandle, "Time", TimeToStr(Time[1]), "AccN", AccountNumber(), "AccBal", AccBalance, "AccEq", AccEquity, "AccPr", AccProfit, SimbMaxDD, "MaxDD", MaxSumDD, "HI_NewCandle");
         FileFlush(LogFileHandle); 
         CandleTime = Time[0];
         LastLoggedCandle = Time[0];
      }
   }
 
   if(SendMailInfo)
   {
      SendMail(StringConcatenate(NameInd, " ", AccountCompany(), " ",AccountNumber()),
               StringConcatenate(txtInfo, "\nProfit ", TimeToStr(iTime(NULL,PERIOD_D1, 0), TIME_DATE), " = ", DoubleToStr(Today[0], 2),
                                 "\nProfit ", TimeToStr(iTime(NULL,PERIOD_D1, 1), TIME_DATE), " = ", DoubleToStr(Today[1], 2),
                                 "\n\nAll orders ", n_oct, " market ",tn,
                                 "\nEquity     ", DoubleToStr(AccountEquity(), 2),
                                 "\nFreeMargin ", DoubleToStr(AccountFreeMargin(), 2),
                                 "\nBalance    ", DoubleToStr(AccountBalance(), 2)));
   }
   return(0);
}
//--------------------------------------------------------------------
int SymbolNum(string Symb)
{
   for(int i = 0; i < 100; i++)
   {                                               
      if(Symb == Symbl[i]) return(i);
      if(StringLen(Symbl[i]) < 2) break;
   }
   Symbl[i] = Symb;
   Nsymb = i;


   if(LogInfoToFile && LogFileHandle > 0)
   {
      if(FileSize(LogFileHandle) > 0)
      {
         int InitFilePos = MathRound(FileTell(LogFileHandle));
         FileSeek(LogFileHandle, 0, SEEK_SET);
         double SymbMDD = 0.0;
         string TmpLoggedStr;

         while(!FileIsEnding(LogFileHandle))
         {
            if(FileReadString(LogFileHandle) == Symb)
            {
               SymbMDD = StrToDouble(FileReadString(LogFileHandle));
               if(SymbolHistoryProfit[1][i] > SymbMDD && SymbMDD < 0) {SymbolHistoryProfit[1][i] = SymbMDD;}
            }
         }         
         FileSeek(LogFileHandle, InitFilePos, SEEK_SET);
      }
   }

   return(i);
}
//--------------------------------------------------------------------
int MagikNum(int Magic)
{
   for(int i = 0; i < 100; i++)
   {                                               
      if(Magic == Magik[i]) return(i);
      if(Magik[i] < 0) break;
   }
   Magik[i] = Magic;
   Nmag = i;
   return(i);
}
//--------------------------------------------------------------------
int CalcDecimalPos(double price)
{
   int nzero = 1;
   string prc = StringTrimLeft(StringTrimRight(DoubleToStr(price, Digits)));
   int str_len = StringLen(prc);
   while(StringSubstr(prc, str_len - nzero, 1) == "0" && Digits >= nzero)
   {
      nzero++; prc = StringTrimLeft(StringTrimRight(DoubleToStr(price, Digits - nzero)));
   }
   int zap_pos = StringFind(prc, ".", 0) + 1;
   if(zap_pos <= 0) {zap_pos = StringFind(prc, ",", 0) + 1;}
   int dec_pos = StringLen(prc) - zap_pos;
//if(dec_pos < 4) {Print(price, " ", prc, " ", zap_pos, " ",dec_pos);}
   return(dec_pos);
}
//--------------------------------------------------------------------
int HistoryOrders()                                  
{
   if(ScanFromToday)
   {
      DateInfoEnd = TimeCurrent();  //заканчивая датой
      DateInfoStart = DateInfoEnd;  //начинать с даты
      de_y = TimeYear(DateInfoEnd);
      de_m = TimeMonth(DateInfoEnd);

      if(ScanCurrentMonth) {ScanCurrentWeek = false;}

      if(!ScanCurrentWeek && !ScanCurrentMonth)
         {
            if(DaysToScan < 1)
               {
                  DaysToScan = 1;
               }
         }

      if(ScanCurrentWeek)
         {
            DaysToScan = TimeDayOfWeek(DateInfoEnd);
            if(DaysToScan < 1)
               {
                  DaysToScan = 6;
               }
         }

      if(ScanCurrentMonth)
         {
            DaysToScan = TimeDay(DateInfoEnd);
            if(DaysToScan < 1)
               {
                  DaysToScan = 1;
               }
         }

      de_d = TimeDay(DateInfoEnd) - DaysToScan;
      while(de_d < 1) 
         {
            de_m--; de_d += d_m[de_m];
            if(de_m < 1) {de_y--; de_m += 12;}
         }
      DateInfoStart = StrToTime(DoubleToStr(de_y, 0) + "." + DoubleToStr(de_m, 0) + "." + DoubleToStr(de_d, 0) + " 23:59:59");

      TS = MathCeil((DateInfoEnd - DateInfoStart) / 86400);   //время сканирования в часах
      if(TS > 0) {TimeSkan = StringConcatenate(TS + 1, " days");}
      else {TimeSkan = "1 day";}

//      ObjectSetText("DateInfo", StringConcatenate("The range of dates from  ", TimeToStr(DateInfoStart, TIME_DATE), " to ", TimeToStr(DateInfoEnd, TIME_DATE), " total ", TimeSkan), 8, Font, WhiteColor);
   }

   OrderSelect(n_oht - 1, SELECT_BY_POS, MODE_HISTORY);
   if(
       !isNewDay &&
       (HistOrdsTot == n_oht || (n_oht - HistOrdsTot == 1 && (OrderProfit() == 0.0 || OrderProfit() == EMPTY_VALUE)))
     )
   {
      return(hn);
   }

   StartDep = AccountBalance();
   DateInfoEnd = TimeCurrent();

   int n, OMN, nr;
   string Symb;
   datetime StartInfo = DateInfoEnd, EndInfo = 0;
   double Profit = 0.0;
   ArrayInitialize(Today, 0.0);
   ArrayInitialize(HistoryOrders, 0.0);
   ArrayInitialize(Magik, -1);
   ArrayInitialize(MagikProfit, 0.0);
   AccStartDep = 0.0;
   HistOrdsTot = n_oht;
   LOT = DateInfoStart;
   
   for(int i = n_oht - 1; i >= 0; i--)
   {                                   
      if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))
      {
         if(OrderSymbol() == "" || OrderType() > 1)
            {
               if(OrderType() == 6)
                  {
                     AccStartDep += OrderProfit();
                  }
               continue;
            }

         Symb = OrderSymbol();
         OOT = OrderCloseTime();
         if(СalcStartDep) {if(OOT >= DateInfoStart && OOT < DateInfoEnd) {StartDep -= OrderProfit() + OrderSwap() + OrderCommission();}}
         if(SybmolInfo != "" && StringFind(SybmolInfo, Symb, 0) < 0) {continue;}
         OMN = OrderMagicNumber();
         if(Magiks != "" && StringFind(Magiks, DoubleToStr(OMN, 0), 0) < 0) {continue;}
         Profit = OrderProfit() + OrderSwap() + OrderCommission();
         nr = CalcDecimalPos(MarketInfo(Symb, MODE_POINT));
//Print(nr, " ", Symb, " ", MarketInfo(Symb, MODE_POINT));
         if(OOT > LOT) {LOT = OOT;}
         if(OOT >= iTime(NULL, PERIOD_D1, 0)) Today[0] += Profit;

         for(int j = 1; j < 10; j++)
         {
            if(OOT >= iTime(NULL, PERIOD_D1, j) && OOT < iTime(NULL, PERIOD_D1, j - 1)) {Today[j] += Profit;}
         }

         if(OOT >= DateInfoStart && OOT < DateInfoEnd)
         {
            HistoryOrders[0][n] = SymbolNum(Symb);
            HistoryOrders[2][n] = Profit;
            HistoryOrders[3][n] = OrderLots();
            HistoryOrders[4][n] = MagikNum(OMN);

            if(OrderType() == OP_BUY)
            {
               if(StartInfo > OOT) StartInfo = OOT;
               if(EndInfo < OOT) EndInfo = OOT;
               HistoryOrders[1][n] = OP_BUY;
               HistoryOrders[13][n] = HistoryOrders[3][n];
               if(Profit < 0.0)
                 {
                  HistoryOrders[6][n]++;
                  HistoryOrders[10][n] -= MathRound(MathAbs(NormalizeDouble(OrderOpenPrice(), nr) - NormalizeDouble(OrderClosePrice(), nr)) * MathPow(10, nr));
                 }
               else
                 {
                  HistoryOrders[5][n]++;
                  HistoryOrders[9][n] += MathRound(MathAbs(NormalizeDouble(OrderClosePrice(), nr) - NormalizeDouble(OrderOpenPrice(), nr)) * MathPow(10, nr));
                 }
            }

            if(OrderType() == OP_SELL)
            {
               if(StartInfo > OOT) StartInfo=OOT;
               if(EndInfo<OOT) EndInfo = OOT;
               HistoryOrders[1][n] = OP_SELL;
               HistoryOrders[14][n] = HistoryOrders[3][n];
               if(Profit < 0.0)
                 {
                  HistoryOrders[8][n]++;
                  HistoryOrders[12][n] -= MathRound(MathAbs(NormalizeDouble(OrderClosePrice(), nr) - NormalizeDouble(OrderOpenPrice(), nr)) * MathPow(10, nr));
                 }
               else
                 {
                  HistoryOrders[7][n]++;
                  HistoryOrders[11][n] += MathRound(MathAbs(NormalizeDouble(OrderOpenPrice(), nr) - NormalizeDouble(OrderClosePrice(), nr)) * MathPow(10, nr));
                 }
            }
//Print(n, " ", OMN, " ", Symb, " ", nr, " ", MarketInfo(Symb, MODE_POINT), " ", HistoryOrders[1][n], " ", Profit, " ", HistoryOrders[9][n], " ", HistoryOrders[10][n], " ", HistoryOrders[11][n], " ", HistoryOrders[12][n] );
            n++;
         }
      }   
      if(n > 10000) {Comment("Buffers overflow", n_oht); return(n);}
   }

   if(ShowMagics)
   {
      for(i = 0; i <= Nmag; i++)
      {                                               
         for(j = 0; j <= n; j++)
         {
            if(i == HistoryOrders[4][j])//Magik
            {
               MagikProfit[0][i] += HistoryOrders[2][j];//профит 
               MagikProfit[1][i] += HistoryOrders[5][j];//кол-во прибыльных сделок BUY
               MagikProfit[2][i] += HistoryOrders[6][j];//кол-во убыточных сделок BUY
               MagikProfit[3][i] += HistoryOrders[7][j];//кол-во прибыльных сделок SELL
               MagikProfit[4][i] += HistoryOrders[8][j];//кол-во убыточных сделок SELL
               MagikProfit[5][i] += HistoryOrders[9][j];//кол-во прибыльных пипсов BUY
               MagikProfit[6][i] += HistoryOrders[10][j];//кол-во убыточных пипсов BUY
               MagikProfit[7][i] += HistoryOrders[11][j];//кол-во прибыльных пипсов SELL
               MagikProfit[8][i] += HistoryOrders[12][j];//кол-во убыточных пипсов SELL
               MagikProfit[9][i] += HistoryOrders[13][j];//сумма объемов BUY
               MagikProfit[10][i] += HistoryOrders[14][j];//сумма объемов SELL
            }
         }
      }
   }

   if(!ScanFromToday)
   {
      TS = MathCeil((EndInfo - StartInfo) / 86400);   //время сканирования в часах
      if(TS >= 0)
      {
         if(TS > 0) 
            {
               TimeSkan = StringConcatenate(TS, " days");
            }
         if(TS == 0) TimeSkan = "1 day";
      }
      if(TS == 0) {ObjectSetText("DateInfo", StringConcatenate("The range of dates from  ", TimeToStr(DateInfoStart, TIME_DATE), " to ", TimeToStr(DateInfoEnd, TIME_DATE), " was not any trades"), 8, Font, Red);}
   }
   
   if(AccStartDep == 0.0) {AccStartDep = StartDep;}
   isNewDay = false;
   return(n);
}
//--------------------------------------------------------------------
int TekOrders()                                  
{
   int n = 0, OMN;
   string Symb;
   ArrayInitialize(Orders, 0.0);
   n_oct = OrdersTotal();

   for (int i = n_oct - 1; i >= 0; i--)
   {                                               
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
         if(OrderSymbol() == "" || OrderType() > 1) {continue;}

         Symb = OrderSymbol();
         if (SybmolInfo != "" && StringFind(SybmolInfo, Symb, 0) < 0) {continue;}
         OMN = OrderMagicNumber();
         if (Magiks != "" && StringFind(Magiks, DoubleToStr(OMN, 0), 0) < 0) continue;
         OOT = OrderOpenTime();
         if (DateInfoEnd < OOT) continue;

         Orders[0][n] = SymbolNum(Symb);
         Orders[2][n] = OrderProfit() + OrderSwap() + OrderCommission();
         Orders[3][n] = OrderLots();
         Orders[4][n] = MagikNum(OMN);

         if (OrderType() == OP_BUY)
         {
            Orders[1][n] = OP_BUY;
            if(OrderStopLoss() > 0) {Orders[5][n] = (MathPow(10, Digits - 4) * MarketInfo(OrderSymbol(), MODE_TICKVALUE) * OrderLots() * (OrderStopLoss() - OrderOpenPrice()) / MarketInfo(OrderSymbol(), MODE_POINT)) + OrderSwap() + OrderCommission();}
         }
         if (OrderType() == OP_SELL)
         {
            Orders[1][n] = OP_SELL;
            if(OrderStopLoss() > 0) {Orders[5][n] = (MathPow(10, Digits - 4) * MarketInfo(OrderSymbol(), MODE_TICKVALUE) * OrderLots() * (OrderOpenPrice() - OrderStopLoss()) / MarketInfo(OrderSymbol(), MODE_POINT)) + OrderSwap() + OrderCommission();}
         }

         n++;
      }   
      if (n > 10000) {Comment("Buffers overflow!!!", n_oht); return(n);}
   }
   return(n);
}
//--------------------------------------------------------------------
color Color(double x)
{
   if(x < 0.0) return(Red);
   if(x > 0.0) return(Green);
   else {return(WhiteColor);}
}
//--------------------------------------------------------------------
color Text(string name, string txt, int x, int y, color C, int w, int Win)
{  
   ObjectCreate(name, OBJ_LABEL, Win, 0, 0);
   ObjectSet(name, OBJPROP_CORNER, 0);
   ObjectSet(name, OBJPROP_YDISTANCE, y);
   ObjectSet(name, OBJPROP_XDISTANCE, x);
   ObjectSetText(name, txt, w, Font, C);
}
//--------------------------------------------------------------------
string Ch32(double n,int k)
{
   string text = DoubleToStr(n, k);
   if(n > 1000) {return(text);}
   if(n > 100) {return(text + " ");}
   if(n > 10) {return(text + "  ");}
   return(text + "   ");
}
//--------------------------------------------------------------------

