← К каталогу
Исходный код · ID 2993

rim 1.2.mq4

Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Получить полный код

Поиск по коду файла

const long        nAllowedAccounts[]	= {0 };			// для работы на любом счёте: { 0 };
const datetime    dtExpiredDate	= D'10.10.2026';

#property version   "1.00"
#property strict

#include <Controls\Edit.mqh>

extern string     _1 = "Настройки торговли";                            //|----------------->
extern double     lotIn                      = 1.0;                     //Ставка
extern uint       expirationIn               = 3;                       //Комментарий, мин
extern uint       secondsPre                 = 2;                       //Ранний вход, сек

extern string     _2 = "Настройки индикатора AJ ARROW ";                      //|----------------->
extern int        SignalGAP      =10;

extern string     _3 = "Настройки индикатора GoldenFilter  ";                      //|----------------->
extern bool       GFilter        = true;  // Использовать индикатор GoldenFilter как фильтр?

extern string     _4 = "Настройка времени";                             //|----------------->
extern bool       useTime                    = false;                   //Торговля по времени
extern uint       hourStart                  = 10;                      //Час начала
extern uint       hourEnd                    = 20;                      //Час окончания
extern bool       useTimeNoTrade1            = false;                   //Запрет 1
extern uint       hourStart1                 = 11;                      //Час начала
extern uint       hourEnd1                   = 13;                      //Час окончания
extern bool       useTimeNoTrade2            = false;                   //Запрет 2
extern uint       hourStart2                 = 15;                      //Час начала
extern uint       hourEnd2                   = 17;                      //Час окончания

extern string     _5 = "Настройка отбития убытков";                     //|----------------->
extern double     lotK2                      = 1.0;                     //К умн 2
extern uint       countK2                    = 2;                       //Кол. сделок

extern string     _6 = "Настройки усреднения";                          //|----------------->
extern bool       useAvg                     = true;                    //Включение
extern int        avgMax                     = 2;                       //Количество усреднений
extern double     lotK                       = 1.5;                     //К умн
extern int        Slp                        = 1;                       //Время в сек. между попытками 
extern int        error_reset                = 10;                      //Количество попыток открытия ордера
extern int        slp                        = 1 ;                      //Задержка входа в сек от момента оценки сделки 

extern string     _9 = "Алерты и сигналы на графике";      //|----------------->
extern bool       showArrows                 = true;                    //Показать стрелки
extern bool       useAlertHandle             = false;                   //Включить алерт ручной
extern bool       useAlertAuto               = false;                   //Включить алерт авто
input bool        sendTLG                    = false;                   //Send telegram
extern string     TLGComment                 = "МИР";                   //Название советника для ТГ Бота
extern string     api_token                  = "";                      //API token
extern string     chat_id                    = "";                      //Chat ID

extern string     _10  = "Общие настройки";                             //----------->
extern int        magic                      = 29072024;                //идентификатор ордеров
extern int        X0                         = 20;                      //координата X панели
extern int        Y0                         = 30;                      //координата Y панели
extern int        fontSizePanel              = 11;                      //Размер шрифта панели

extern bool       showInfo                   = false;                   //Показ инфо
extern color      clrInfo                    = clrChocolate;            //Цвет инфо
extern int        fontSizeInfo               = 11;                      //Размер шрифта инфо

extern bool       showTime                   = true;                    //Показ таймера
extern color      clrTime                    = clrDodgerBlue;           //Цвет таймера
extern int        fontSizeTime               = 11;                      //Размер шрифта таймера

color    clBG         = clrWhite;         // Цвет фона
color    clOpenBuy    = clrLime;          // Цвет значка открытия покупки
color    clOpenSell   = clrHotPink;       // Цвет значка открытия продажи

int      slip = 10;
int      countLoss = 0;
string   GVnLoss, GVstopping, GVhandle, GVcountK2, GVtimeBarCloseLoss, GVlossInRow;
int      countHistLoss, countHistProfit;
bool     testing = false;
string   expertName = "Tank_";
string   nameOBJ = "Tank_";
datetime timeCurrent, timeOpenPos = 0, timeLastWork;
int      nBuy = 0, nSell = 0;
int      nBuyPre = 0, nSellPre = 0;
int      widthW = 150;
color    frame_clr;

CEdit    commEdit, volumeEdit;
uint     expiration = expirationIn;
double   lotW = lotIn, lotOpenPos;
int      profitOpenPos;

string   serv;

int OnInit()
{
      // код доступен только после оплаты
   }

void DrawPanel(int x, int y)
{
   clBG = (color)ChartGetInteger(0, CHART_COLOR_BACKGROUND);
   frame_clr = (color)(0xFFFFFF - clBG);
   int highW = 75;
   if (GlobalVariableGet(GVhandle) == 1) highW = 160;
   RectLabelCreate(0, nameOBJ + "Head_BG", 0, x, y, widthW, highW, clBG, frame_clr, STYLE_SOLID, 1, false, false, false, true, 0);
   ObjectSetString(0, nameOBJ + "Head_BG", OBJPROP_TOOLTIP, " ");
   ObjectSetInteger(0, nameOBJ + "Head_BG", OBJPROP_SELECTABLE, false);

   if (GlobalVariableGet(GVhandle) == 1) {
      ButtonCreate(0, nameOBJ + "Auto", 0, CORNER_LEFT_UPPER, x + 5, y + 5, 140, 30, "Ручной", "Tahoma", 11, clrBlack, clrAliceBlue, clrAliceBlue, true);

      ButtonCreate(0, nameOBJ + "BTN_UP", 0, CORNER_LEFT_UPPER, x + 5, y + 40, 140, 30, "Выше", "Tahoma", 11, clrWhite, clrBlue, clrBlue, false);
      ButtonCreate(0, nameOBJ + "BTN_DN", 0, CORNER_LEFT_UPPER, x + 5, y + 75, 140, 30, "Ниже", "Tahoma", 11, clrWhite, clrTomato, clrTomato, false);

      CreateFieldComment(x + 110, y + 110);
      CreateFieldVolume(x + 110, y + 135);

      ObjectDelete(0, nameOBJ + "STOP");
   }

   if (GlobalVariableGet(GVhandle) == 0) {
      ButtonCreate(0, nameOBJ + "Auto", 0, CORNER_LEFT_UPPER, x + 5, y + 5, 140, 30, "Авто", "Tahoma", 11, clrBlack, clrPowderBlue, clrPowderBlue, false);
      if (GlobalVariableGet(GVstopping) == 0)
         ButtonCreate(0, nameOBJ + "STOP", 0, CORNER_LEFT_UPPER, x + 5, y + 40, 140, 30, "Остановить", "Tahoma", 11, clrBlack, clrLightSalmon, clrLightSalmon, false);
      if (GlobalVariableGet(GVstopping) == 1)
         ButtonCreate(0, nameOBJ + "STOP", 0, CORNER_LEFT_UPPER, x + 5, y + 40, 140, 30, "Возобновить", "Tahoma", 11, clrBlack, clrLightGreen, clrLightGreen, true);
      ObjectDelete(0, nameOBJ + "BTN_UP");
      ObjectDelete(0, nameOBJ + "BTN_DN");
      ObjectsDeleteAll(0, nameOBJ + "comm");
      ObjectsDeleteAll(0, nameOBJ + "volume");
      lotW = lotIn;
      expiration = expirationIn;
   }

   ChartRedraw(0);
}

void OnDeinit(const int reason)
{
   ObjectsDeleteAll(0, expertName);
   ObjectsDeleteAll(0, nameOBJ);
   Comment("");
   if (testing) {
      GlobalVariablesDeleteAll(expertName);
   }
   HideTestIndicators(false);
   EventKillTimer();
}

void OnTick()
{
      // код доступен только после оплаты
   }

void OnTimer()
{
   int periodMinutes = _Period;
   timeCurrent = TimeCurrent();
   int localTime     = (int)TimeLocal();
   int barTime       = (int)Time[0];
   int diff          = (int)MathMax(round((timeCurrent - localTime) / 3600.0) * 3600, -24 * 3600);

   int timeFor = barTime + periodMinutes * 60 - localTime - diff;
   string time = GetTime(timeFor);
   time = (TerminalInfoInteger(TERMINAL_CONNECTED)) ? time : time + " x";

   if (ObjectFind(0, nameOBJ + "Timer") >= 0)
      ObjectSetString(0, nameOBJ + "Timer", OBJPROP_TEXT, time);

   bool  tradeTime = true;
   if (useTime && (timeCurrent < StrToTime(IntegerToString(hourStart) + ":00:00") || timeCurrent >= StrToTime(IntegerToString(hourEnd) + ":00:00"))) tradeTime = false;
   if (useTimeNoTrade1 && (timeCurrent >= StrToTime(IntegerToString(hourStart1) + ":00:00") && timeCurrent < StrToTime(IntegerToString(hourEnd1) + ":00:00"))) tradeTime = false;
   if (useTimeNoTrade2 && (timeCurrent >= StrToTime(IntegerToString(hourStart2) + ":00:00") && timeCurrent < StrToTime(IntegerToString(hourEnd2) + ":00:00"))) tradeTime = false;

   CountTrades();

   if (nBuy + nSell == 1) {

      if (useAvg) {
         if (GlobalVariableGet(GVstopping) != 1 && tradeTime) {
            if (timeCurrent >= timeOpenPos + expiration * 60 - secondsPre - 2)     
               Print("timeOpenPos=", TimeToString(timeOpenPos, TIME_SECONDS), " Profit=", profitOpenPos);
            if (profitOpenPos <= 0 && timeCurrent >= timeOpenPos + expiration * 60 - secondsPre-2) {     
               int nLoss = (int)GlobalVariableGet(GVnLoss);
               nLoss++;
               GlobalVariableSet(GVnLoss, nLoss); 
               if (nLoss <= avgMax) {
                  double lot = NormLots(lotOpenPos * lotK);
                  if (lot > 0) {
                     if (nBuy > 0) {
                     Sleep (slp*1000);
                        Print("Усреднение BUY ", nLoss, " Profit=", profitOpenPos);
                        int ticket=OpenPosition(_Symbol, OP_BUY, lot, 0, 0, magic, IntegerToString(expiration));    // приказ на открытие усреднения

                        int kod_error=GetLastError();     // узнаем код ошибки, 0 если не ошибки
                        Print(kod_error);                 // выводим в принт номер ошибки
                        if ((kod_error != 0)&&( ticket<=0))  // если сделка не открылась
                        {
                        for (int i=1; i<=error_reset; i++)   // ЦИКЛ , будем делать то что внизу, N количество раз
                                     { 
                                     Sleep(Slp*1000); RefreshRates(); // Отдыхаем, сколько прописано в настройках секунд
                                     ticket=OpenPosition(_Symbol, OP_BUY, lot, 0, 0, magic, IntegerToString(expiration)); //приказ на открытие усреднения  
                                     Print (GetLastError());    //выводим в принт номер ошибки, в любом случае даже если сделка открылась, будет тогда 0 
                                     if ( ticket>0) {Print("Усреднение BUY успешно"); break;} //Если сделка открылась, цикл больше не повторяем, иначе возвращаемся вначало и повторяем попытки
                                     }
                        }
                               if (ticket<=0) Print("Усреднение BUY не открылось за отведенное количество попыток", GetLastError());// Если так ничего и не вышло, Принт и номер ошибки

                        return;
                     }
                     if (nSell > 0) {
                     Sleep (slp*1000);
                        Print("Усреднение SELL ", nLoss, " Profit=", profitOpenPos);
                        int ticket_S=OpenPosition(_Symbol, OP_SELL, lot, 0, 0, magic, IntegerToString(expiration));

                        int kod_error=GetLastError();
                        Print(kod_error);
                        if ((kod_error != 0)&&( ticket_S<=0))
                        {
                        for (int i=1; i<=error_reset; i++) 
                                     { 
                                     Sleep(Slp*1000); RefreshRates(); 
                                     ticket_S=OpenPosition(_Symbol, OP_SELL, lot, 0, 0, magic, IntegerToString(expiration));
                                     Print (GetLastError());
                                     if ( ticket_S>0) {Print("Усреднение BUY успешно"); break;}
                                     }
                        }
                               if (ticket_S<=0) Print("Усреднение BUY не открылось за отведенное количество попыток", GetLastError());

                        return;

                     }
                  }
               }
            }
         }
      }
   }

   if (nBuy == 0 && nBuyPre > 0) { //Закрылся BUY

      double lotOpen = 0;
      datetime timeBarOpen = 0;
      double profitPos = ProfitLastPos(OP_BUY, magic, lotOpen, timeBarOpen);
      if (profitPos != EMPTY_VALUE) {
         if (profitPos > 0) {
            Print("Закрылся BUY в профит ", DoubleToStr(profitPos, 2));
            GlobalVariableSet(GVcountK2, 0);
            GlobalVariableDel(GVtimeBarCloseLoss);
            GlobalVariableSet(GVlossInRow, 0);
            GlobalVariableSet(GVnLoss, 0);
            if (sendTLG) {
               int res = 0;
               string sendMess = "chat_id=" + chat_id + "&text=" + TLGComment + " " +  "Закрылся BUY в профит " + _Symbol + " " + StringSubstr(EnumToString((ENUM_TIMEFRAMES)Period()), 7);
               res = SendMessage(sendMess);
            }
         }
         else {
            Print("Закрылся BUY в убыток ", DoubleToStr(profitPos, 2));
            GlobalVariableSet(GVtimeBarCloseLoss, timeBarOpen);
            int count = (int)GlobalVariableGet(GVlossInRow);
            count++;
            GlobalVariableSet(GVlossInRow, count);
         }
      }
      else
         Print("Неизвестный результат закрытия");
   }
   if (nSell == 0 && nSellPre > 0) { //Закрылся SELL
      double lotOpen = 0;
      datetime timeBarOpen = 0;
      double profitPos = ProfitLastPos(OP_SELL, magic, lotOpen, timeBarOpen);
      if (profitPos != EMPTY_VALUE) {
         if (profitPos > 0) {
            Print("Закрылся SELL в профит ", DoubleToStr(profitPos, 2));
            GlobalVariableSet(GVcountK2, 0);
            GlobalVariableDel(GVtimeBarCloseLoss);
            GlobalVariableSet(GVlossInRow, 0);
            GlobalVariableSet(GVnLoss, 0);
            if (sendTLG) {
               int res = 0;
               string sendMess = "chat_id=" + chat_id + "&text=" + TLGComment + " " + "Закрылся SELL в профит " + _Symbol + " " + StringSubstr(EnumToString((ENUM_TIMEFRAMES)Period()), 7);
               res = SendMessage(sendMess);
            }
         }
         else {
            Print("Закрылся SELL в убыток ", DoubleToStr(profitPos, 2));
            GlobalVariableSet(GVtimeBarCloseLoss, timeBarOpen);
            int count = (int)GlobalVariableGet(GVlossInRow);
            count++;
            GlobalVariableSet(GVlossInRow, count);
         }
      }
      else
         Print("Неизвестный результат закрытия");
   }

   if ( Volume[0]<10   ) {    //     timeFor <= (int)secondsPre && timeCurrent >= timeLastWork + PeriodSeconds()
      timeLastWork = timeCurrent;
      Work(tradeTime);
   }

   nBuyPre = nBuy;
   nSellPre = nSell;

}

void Work(bool  tradeTime)
{

   if (showInfo && (IsVisualMode() || !testing)) {
      DrawStats();
   }

   if (GlobalVariableGet(GVstopping) == 1 || !tradeTime) return;

   int signal = GetSignal();

   if (showArrows) {
      if (signal == 1) {
         ArrowBuyCreate(0, "BUY_" + IntegerToString(Time[1]), 0, Time[1], Open[1], clrBlue, 0, 1, false, false, true, 0);
         if (GlobalVariableGet(GVhandle) == 1)
            if (useAlertHandle) Alert("BUY " + _Symbol + " " + StringSubstr(EnumToString((ENUM_TIMEFRAMES)Period()), 7));
            else if (useAlertAuto) Alert("BUY " + _Symbol + " " + StringSubstr(EnumToString((ENUM_TIMEFRAMES)Period()), 7));
      }
      if (signal == -1) {
         ArrowSellCreate(0, "SELL_" + IntegerToString(Time[1]), 0, Time[1], Open[1], clrRed, 0, 1, false, false, true, 0);
         if (GlobalVariableGet(GVhandle) == 1)
            if (useAlertHandle) Alert("SELL " + _Symbol + " " + StringSubstr(EnumToString((ENUM_TIMEFRAMES)Period()), 7));
            else if (useAlertAuto) Alert("SELL " + _Symbol + " " + StringSubstr(EnumToString((ENUM_TIMEFRAMES)Period()), 7));
      }
   }

   if (GlobalVariableGet(GVhandle) == 0 && nBuy + nSell == 0) {
      double tp = 0, sl = 0, lot = NormLots(lotW);
      double lotOpen = 0;
      datetime timeBarOpen = 0;
      double profitPos = ProfitLastPos(-1, magic, lotOpen, timeBarOpen);
      bool useK2 = false;
      if (profitPos != EMPTY_VALUE) {
         if (profitPos < 0) {
            lot = NormLots(lotOpen * lotK2);
            useK2 = true;
         }
         if (profitPos == 0) lot = NormLots(lotOpen);
         if (profitPos > 0) {
            lot = NormLots(lotW);
            if (countK2 > 0) GlobalVariableDel(GVcountK2);
         }
      }

      if (signal == 1) {                //сигнал в BUY
         if (countK2 > 0 && (uint)GlobalVariableGet(GVcountK2) >= countK2) {
            lot = NormLots(lotW);
            useK2 = false;
            GlobalVariableDel(GVcountK2);
         }

         if (lot > 0) {
            if (useK2) Print("Кум 2 ", lot);
            else Print("Начальный BUY ", lot);
            OpenPosition(_Symbol, OP_BUY, lot, 0, 0, magic, IntegerToString(expiration));
            GlobalVariableSet(GVnLoss, 0);
            if (sendTLG) {
               int res = 0;
               string sendMess = "chat_id=" + chat_id + "&text=" + TLGComment + " " + "BUY " + _Symbol + " " + StringSubstr(EnumToString((ENUM_TIMEFRAMES)Period()), 7);
               res = SendMessage(sendMess);
            }
            return;
         }
      }
      if (signal == -1) {                //сигнал в SELL
         if (countK2 > 0 && (uint)GlobalVariableGet(GVcountK2) >= countK2) {
            lot = NormLots(lotW);
            useK2 = false;
            GlobalVariableDel(GVcountK2);
         }

         if (lot > 0) {
            if (useK2) Print("Кум 2 ", lot);
            else Print("Начальный SELL ", lot);
            OpenPosition(_Symbol, OP_SELL, lot, 0, 0, magic, IntegerToString(expiration));
            GlobalVariableSet(GVnLoss, 0);
            if (sendTLG) {
               int res = 0;
               string sendMess = "chat_id=" + chat_id + "&text=" + TLGComment + " " + "SELL " + _Symbol + " " + StringSubstr(EnumToString((ENUM_TIMEFRAMES)Period()), 7);
               res = SendMessage(sendMess);
            }
            return;
         }
      }
   }
}

int GetSignal()
{
   double IndArrowBUY          = iCustom (NULL,0,"AJ ARROW",SignalGAP,1,1);
   double IndArrowSELL         = iCustom (NULL,0,"AJ ARROW",SignalGAP,0,1);
   double IndArrowBUY1         = iCustom (NULL,0,"AJ ARROW",SignalGAP,1,2);
   double IndArrowSELL1        = iCustom (NULL,0,"AJ ARROW",SignalGAP,0,2);

   double IndGoldenFilterSELL  = iCustom (NULL,0,"GoldenFilter",1,1);
   double IndGoldenFilterBUY   = iCustom (NULL,0,"GoldenFilter",0,1);

 Comment ("");
 if (IndGoldenFilterSELL >0 && IndGoldenFilterSELL <1  && IndGoldenFilterBUY   ==EMPTY_VALUE)    Comment ("Красный Голден Фильтр");
 if (IndGoldenFilterBUY  >0 && IndGoldenFilterBUY  <1 && IndGoldenFilterSELL  ==EMPTY_VALUE)    Comment ("Синий Голден Фильтр");
 if (IndGoldenFilterSELL >0 && IndGoldenFilterSELL <1  && IndGoldenFilterBUY  >0 && IndGoldenFilterBUY  <1)    Comment ("Красный и синий Голден Фильтр");

   int sign = 0;

if (  IndArrowBUY <100000 && IndArrowBUY>0   && (!GFilter || (GFilter && IndGoldenFilterBUY  >0 && IndGoldenFilterBUY  <1 )))
   {
    sign = 1; // Покупка
   } 
if ( IndArrowSELL <100000 && IndArrowSELL>0  && (!GFilter || (GFilter && IndGoldenFilterSELL >0 && IndGoldenFilterSELL <1 ))   )
   {
    sign = -1; // Продажа
   }
 return sign;
}

void CloseAll()
{
   for (int i = OrdersTotal() - 1; i >= 0; i--) {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         if (OrderSymbol() == _Symbol && (OrderType() == OP_BUY || OrderType() == OP_SELL) && OrderMagicNumber() == magic) {
            ClosePosBySelect();
         }
   }
}

void ClosePosBySelect()
{
   bool   fc;
   double ll, pa, pb, pp;
   if (OrderType() == OP_BUY || OrderType() == OP_SELL) {
      for (int it = 1; it <= 5; it++) {
         if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) break;
         while (!IsTradeAllowed()) Sleep(5000);
         RefreshRates();
         pa = MarketInfo(OrderSymbol(), MODE_ASK);
         pb = MarketInfo(OrderSymbol(), MODE_BID);
         if (OrderType() == OP_BUY) {
            pp = pb;
         }
         else {
            pp = pa;
         }
         ll = OrderLots();
         fc = OrderClose(OrderTicket(), ll, pp, slip, clrYellow);
         if (fc) {
            break;
         }
         else {
            int err = GetLastError();
            Print("Error(", err, ") close position: ", Error(err), ", try ", it);
         }
      }
   }
   else Print("Incorrect trade operation. Close ", GetNameOP(OrderType()));
}

int OpenPosition(string sy, int op, double ll, double slO = 0, double tpO = 0, int mn = 0, string lsComm = "")
{
   color    clOpen;
   datetime ot;
   double   pp, pa, pb;
   int      dg, err, it, ticket = 0;

   if (sy == "" || sy == "0") sy = Symbol();
   if (op == OP_BUY) clOpen = clOpenBuy;
   else clOpen = clOpenSell;
   for (it = 1; it <= 1; it++) {
      if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) {
         Print("OpenPosition(): Остановка работы функции");
         break;
      }
      while (!IsTradeAllowed()) Sleep(5000);
      RefreshRates();
      dg = (int)MarketInfo(sy, MODE_DIGITS);
      pa = MarketInfo(sy, MODE_ASK);
      pb = MarketInfo(sy, MODE_BID);
      if (op == OP_BUY) pp = pa;
      else pp = pb;
      pp = NormalizeDouble(pp, dg);
      ot = TimeCurrent();
      ticket = OrderSend(sy, op, ll, pp, slip, slO, tpO, lsComm, mn, 0, clOpen);
      if (ticket > 0) {
         break;
      }
      else {
         err = GetLastError();
         if (pa == 0 && pb == 0) Print("NOT Symbol " + sy);

         Print("Error(", err, ") opening position: ", Error(err), ", try ", it);
         Print("Ask=", pa, " Bid=", pb, " sy=", sy, " ll=", ll, " op=", GetNameOP(op),
               " pp=", pp, " sl=", slO, " tp=", tpO, " mn=", mn);
      }
   }
   return(ticket);
}

bool ExistPositions(string sy = "", int op = -1, int mn = -1, datetime ot = 0)
{
   if (sy == "0") sy = Symbol();
   for (int i = 0; i < OrdersTotal(); i++) {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
         if (OrderSymbol() == sy || sy == "") {
            if (OrderType() == OP_BUY || OrderType() == OP_SELL) {
               if (op < 0 || OrderType() == op) {
                  if (mn < 0 || OrderMagicNumber() == mn) {
                     if (ot <= OrderOpenTime()) return true;
                  }
               }
            }
         }
      }
   }
   return false;
}

void CountTrades()
{
   nBuy = 0;
   nSell = 0;
   profitOpenPos = 0;
   lotOpenPos = 0;
   timeOpenPos = 0;
   for (int i = OrdersTotal() - 1; i >= 0; i--)
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
         if (OrderSymbol() == Symbol() && OrderMagicNumber() == magic) {
            if (OrderType() == OP_BUY) {
               nBuy++;
               timeOpenPos = OrderOpenTime();
               profitOpenPos = (int)((Close[0] - OrderOpenPrice()) / _Point);
               lotOpenPos = OrderLots();
            }
            if (OrderType() == OP_SELL) {
               nSell++;
               timeOpenPos = OrderOpenTime();
               profitOpenPos = (int)((OrderOpenPrice() - Close[0]) / _Point);
               lotOpenPos = OrderLots();
            }
         }
      }
}

double NormLots(double lot)
{
   int lotdigits = 0;
   double maxLot = MarketInfo(_Symbol, MODE_MAXLOT);
   double minLot = MarketInfo(_Symbol, MODE_MINLOT);
   double lotstep = MarketInfo(_Symbol, MODE_LOTSTEP);
   if (lotstep == 0.01)   lotdigits = 2;
   if (lotstep == 0.1)    lotdigits = 1;
   if (lotstep == 1)      lotdigits = 0;
   double tradeLot = NormalizeDouble(lot, lotdigits);
   if(tradeLot > maxLot) tradeLot = maxLot;
   if(tradeLot < minLot) tradeLot = minLot;
   return tradeLot;
}

double ProfitLastPos(int op, int mn, double & lot, datetime & timeBarOpen)
{
   if (OrdersHistoryTotal() == 0) {
      return EMPTY_VALUE;
   }
   datetime t = 0;
   int  j = -1;
   for (int i = OrdersHistoryTotal() - 1; i >= 0; i--) {
      if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
         if (OrderSymbol() == _Symbol) {
            if (OrderType() == OP_BUY || OrderType() == OP_SELL) {
               if (op < 0 || OrderType() == op) {
                  if (mn < 0 || OrderMagicNumber() == mn) {
                     if (t < OrderCloseTime()) {
                        t = OrderCloseTime();
                        j = i;
                     }
                  }
               }
            }
         }
      }
   }
   if (OrderSelect(j, SELECT_BY_POS, MODE_HISTORY)) {
      double profit = 0; //OrderProfit();
      {
         if (OrderType() == OP_BUY) {
            profit = (OrderClosePrice() - OrderOpenPrice()) / _Point;
         }
         if (OrderType() == OP_SELL) {
            profit = (OrderOpenPrice() - OrderClosePrice()) / _Point;
         }
      }
      lot = OrderLots();
      timeBarOpen = Time[iBarShift(_Symbol, PERIOD_CURRENT, OrderOpenTime())];
      return profit;
   }
   return EMPTY_VALUE;
}

string GetNameOP(int op)
{
   switch (op) {
   case OP_BUY      :
      return("Buy");
   case OP_SELL     :
      return("Sell");
   case OP_BUYLIMIT :
      return("BuyLimit");
   case OP_SELLLIMIT:
      return("SellLimit");
   case OP_BUYSTOP  :
      return("BuyStop");
   case OP_SELLSTOP :
      return("SellStop");
   default          :
      return("Unknown Operation");
   }
}

double ND(double d)
{
   return (NormalizeDouble(d, Digits));
}

void DrawStats()
{
   double balance = AccountBalance();

   double dayProfit = GetProfitForDay(0);

   string expName = expertName + "1";
   if (ObjectFind(expName) == -1) {
      ObjectCreate(expName, OBJ_LABEL, 0, 0, 0);
      ObjectSet(expName, OBJPROP_CORNER, 1);
      ObjectSet(expName, OBJPROP_XDISTANCE, 10);
      ObjectSet(expName, OBJPROP_YDISTANCE, 15);
   }
   ObjectSetText(expName, "Заработок сегодня: " + DoubleToStr(dayProfit, 2) + "/" + DoubleToStr(dayProfit * 100.0 / balance, 1), fontSizeInfo, "Tahoma", clrInfo);

   dayProfit = GetProfitForDay(1);

   expName = expertName + "2";
   if (ObjectFind(expName) == -1) {
      ObjectCreate(expName, OBJ_LABEL, 0, 0, 0);
      ObjectSet(expName, OBJPROP_CORNER, 1);
      ObjectSet(expName, OBJPROP_XDISTANCE, 10);
      ObjectSet(expName, OBJPROP_YDISTANCE, 30);
   }
   ObjectSetText(expName, "Заработок вчера: " + DoubleToStr(dayProfit, 2) + "/" + DoubleToStr(dayProfit * 100.0 / balance, 1), fontSizeInfo, "Tahoma", clrInfo);

   double profit = GetProfitForMonth();

   expName = expertName + "3";
   if (ObjectFind(expName) == -1) {
      ObjectCreate(expName, OBJ_LABEL, 0, 0, 0);
      ObjectSet(expName, OBJPROP_CORNER, 1);
      ObjectSet(expName, OBJPROP_XDISTANCE, 10);
      ObjectSet(expName, OBJPROP_YDISTANCE, 45);
   }
   ObjectSetText(expName, "Прибыль за месяц: " + DoubleToStr(profit, 2) + "/" + DoubleToStr(profit * 100.0 / balance, 1), fontSizeInfo, "Tahoma", clrInfo);

   expName = expertName + "4";
   if (ObjectFind(expName) == -1) {
      ObjectCreate(expName, OBJ_LABEL, 0, 0, 0);
      ObjectSet(expName, OBJPROP_CORNER, 1);
      ObjectSet(expName, OBJPROP_XDISTANCE, 10);
      ObjectSet(expName, OBJPROP_YDISTANCE, 60);
   }
   ObjectSetText(expName, "Убыточных подряд: " + DoubleToString(GlobalVariableGet(GVlossInRow), 0), fontSizeInfo, "Tahoma", clrInfo);

   expName = expertName + "5";
 

Показано первые 50% кода (символов: 39523)

Что вы получите после оплаты

На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.

Чтобы оформить заказ, введите email и перейдите к оплате.

Стоимость полного кода
3 952₽