Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 6. - page 238

 

Hello again I would like to raise a question about placing a stop on the last order.

I want to clarify that in the tester sometimes a stop is not placed on the last order.

This has not happened so far on the forward tests. But as they say, why wait?)

Code

//+-------------------------------------------------------------------------------------+
//|                        Управление StopLoss, TakeProfit                              |
//+-------------------------------------------------------------------------------------+
bool ProfitManagement()
{
double StopLossBuy = BuyAP+Profit*Point;                             //Вычисляем StopLoss
double StopLossSell = SellAP-Profit*Point;
RefreshRates();
for(int good = OrdersTotal()-1; good >= 0; good --)   // Выбираем со всего масива ордеров
 {
 if(OrderSelect (good, SELECT_BY_POS, MODE_TRADES))             
 if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)   //Выбирам ордера експерта
  { 
//-------------------------Order Buy-----------------------------------------------------  
if (BuyCount >1)                                           //Если открыти длинные позиции
 if (BuyAP < Bid)                                                //Если  мы идем по рынку  
 if (MathAbs(OrderStopLoss() - StopLossBuy) >= Tick)           // Профит не равен нужному
 if (Bid - StopLossBuy > (PipStepProfit*0.5)*Point)   // Если стоп дальше чем 0,5 пипстеп
 if (Bid - StopLossBuy > DedZone)                    // Уровень достаточно удален от цены
 if (WaitForTradeContext())                                // Свободен ли торговый поток?
 if (OrderType() == OP_BUY)                                        // Выбираем ордера Buy
 if (!OrderModify(OrderTicket(), 0, NP(StopLossBuy), 0, 0, Lime))    // Изменяем StopLoss
  {
 Alert (Symbol()," Хрень со стопами! ",   GetLastError());
 return(false);
  }
//-------------------------Окончание блока-----------------------------------------------

// далее по логике в таком же духе
 
beginner:

Can you suggest the following thing, there are N EAs on the account, which under certain conditions can all open an order at the same time, each of them checks no more than 1 order on the account, but sometimes I end up with N orders, what can I do?


read articles

Pause between trades

Error 146 ("Trade flow busy") and how to deal with it


 
 
artmedia70:

Are you sure that this part of the code is the source of the problem? From what you have shown it is difficult to draw conclusions - there are a lot of unknown variables and you can't see the opening itself.

To find the reason yourself, print or display the values of the variables with comments. Then you will be able to see their values at any time.



This is based on eOpenByTime Expert Advisor from Mr. Kim. I also added a trailing stop, closed at the end of the week and opened at a certain day of the week. In this form the Expert Advisor works as it should be.

The deal opening is performed in the following way, I have added only the day of a week of deal opening but there is nothing to screw up here

  if (DayOfWeek()==DayOfWeekOpen
  && TimeCurrent()>=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeOpen)
  && TimeCurrent()<StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeOpen)+Duration)
  {
    if (!ExistPositions("", Sell, MagicNumber)) {
      double sl, tp;
      if (Sell) {
        if (StopLoss>0) sl=Bid+StopLoss*Point; else sl=0;
        if (TakeProfit>0) tp=Bid-TakeProfit*Point; else tp=0;
      } else {
        if (StopLoss>0) sl=Ask-StopLoss*Point; else sl=0;
        if (TakeProfit>0) tp=Ask+TakeProfit*Point; else tp=0;
      }
      OpenPosition("", Sell, Lots, sl, tp, MagicNumber);
    }
  }

To be honest, I do not quite understand why TimeCurrent is compared to TimeCurrent + TimeTradeOpen where TimeTradeOpen is an external parameter of the TimeTradeOpen = "19:51" type. (This is actually the position opening time we need.) I also do not understand why this comparison works. Duration is the time during which the Expert Advisor will try to open a position.

By analogy, I have added a closing of a position on Friday.

if (DayOfWeek()==DayOfWeekClose
  && TimeCurrent()>=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeClose)
   && TimeCurrent()<StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeClose)+Duration)
{  if (OrdersTotal()>0)
   {  for (int i=OrdersTotal()-1; i>=0; i--)
      {  if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
         {  
            if (OrderType()==OP_BUY)
            {  RefreshRates();
               OrderClose(OrderTicket(),OrderLots(),Bid,1000);
               return(0);
            }
            if (OrderType()==OP_SELL)
            {  RefreshRates();
               OrderClose(OrderTicket(),OrderLots(),Ask,1000);
               return(0);
            }
         }
}  }  }

So far, everything was working.

Then I wanted to add a condition that looks at a candlestick at a given time and a given day of the week, if the candlestick is bullish, then sell, if it is bearish, then buy.

In the same way, I have copied these 3 lines, which have worked before, but now for some reason they do not want to.

if (DayOfWeek()==DayOfWeekIf
 && TimeCurrent()>=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeIf)
 && TimeCurrent()<StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeIf)+Duration)
   {
    if  (iClose("XAUUSD",PERIOD_H1,0)-iOpen("XAUUSD",PERIOD_H1,0)>=0)
    Sell = true;
    if  (iOpen("XAUUSD",PERIOD_H1,0)-iClose("XAUUSD",PERIOD_H1,0)>0)
    Sell =false;
   }

After that the code for position opening follows. TimeTradeIf has a similar format TimeTradeIf = "19:51" and is also set via external parameters.

The whole code is quite long, do you need to insert?

 
Limita:

Hello again I would like to raise a question about placing a stop on the last order.

I want to clarify that in the tester sometimes a stop is not placed on the last order.

This has not happened so far on the forward tests. But as they say, why wait?)

Code


Found the problem. The code is OK. it's the writer who demands the impossible ))
 
Antonius:


It is based on eOpenByTime Expert Advisor from esteemed Mr. Kim. I also added a trailing stop, closed at the end of the week and opened at a certain day of the week. In this form the EA works as it should.

The deal opening is performed in the following way, only the day of the week of deal opening is added by me but there is nothing to screw up here

To be honest, I do not quite understand why TimeCurrent is compared with TimeCurrent + TimeTradeOpen, where TimeTradeOpen is an external parameter of the TimeTradeOpen = "19:51" type. (This is actually the position opening time we need.) I also do not understand why this comparison works. Duration is the time during which the Expert Advisor will try to open a position.

By analogy, I have added a closing of a position on Friday.

So far, everything was working.

Then I wanted to add a condition that looks at a candlestick at a given time and a given day of the week, if the candlestick is bullish, then sell, if it is bearish, then buy.

In the same way, I have copied these 3 lines, which have worked before, but now for some reason they do not want to.

After that the code for position opening follows. TimeTradeIf has a similar format TimeTradeIf = "19:51" and is also set via external parameters.

The entire code is quite long, should I paste it?

To be honest, I have already forgotten what the problem is. In this code section I see that only short positions are checked and the opening of short positions is also specified:

if (!ExistPositions("", Sell, MagicNumber)) {            // вместо Sell должно быть OP_SELL или 1
   double sl, tp;
   if (Sell) {
      if (StopLoss>0) sl=Bid+StopLoss*Point; else sl=0;
      if (TakeProfit>0) tp=Bid-TakeProfit*Point; else tp=0;
      } 
   else {                                                // Это расчёт для OP_BUY - зачем он тут?
      if (StopLoss>0) sl=Ask-StopLoss*Point; else sl=0;
      if (TakeProfit>0) tp=Ask+TakeProfit*Point; else tp=0;
      }
   OpenPosition("", Sell, Lots, sl, tp, MagicNumber);    // вместо Sell должно быть OP_SELL или 1
   }                                                     // ну и, если нужен Buy, то OP_BUY или 0
 
artmedia70:

To be honest, I've forgotten what the problem is. In this code section I see that only short positions are checked and only short positions are opened:


The Sell variable is external and contains true or false, 1 or 0, respectively,

extern bool   Sell       = False;      // True-Sell, False-Buy

Kim's is eOpenByTime.

The logic, the algorithm of actions, is flawed.

If he would drop the start() function and variables, what they carry, then we can suggest something.

 
r772ra:

Artem, this is correct, the Sell variable is external and carries the value true or false, 1 or 0 respectively,

I looked at Kim's, eOpenByTime.

The logic, the algorithm of actions, is flawed.

If he would show the start() function and variables, what they bear, then we can suggest something.





The idea is this: if a candle is bullish on a certain DayOfWeekIf at a certain time TimeTradeIf, then Sell = true (sell), if it is bearish, then Sell = false (buy).

It should be, but in the test I only get trades for sale.

eOpenByTime allows to open deal at given time, I added more at given day of week if (DayOfWeek()==DayOfWeekOpen, where DayOfWeekOpen = 1,2,3,4,5

I'm attaching the code in two parts, there's no other way around, I've highlighted the problem condition. Everything works as it should without it, i.e. we set Sell and open a deal at the right time at the right day of the week.

Only trawl has been cut out.

//+----------------------------------------------------------------------------+
//|                                                          e-OpenByTime.mq4  |
//|                                                                            |
//|  Идея      : Владимир,  sibtrade@hotbox.ru                                 |
//|  Реализация: Ким Игорь В. aka KimIV, http://www.kimiv.ru                   |
//|                                                                            |
//|  2007.04.27  Открытие позиции в заданное время.                            |
//|  2008.04.10  Параметр MarketWatch.                                         |
//|  2008.04.14  Параметр Duration.                                            |
//+----------------------------------------------------------------------------+

#property copyright "Владимир & KimIV"
#property link  "http://www.kimiv.ru"

//------- Внешние параметры советника -----------------------------------------+
extern string _P_Trade = "---------- Параметры торговли";
extern int    DayOfWeekOpen    = 3;    // День недели открытия позиции
extern string TimeTradeOpen  = "19:51";    // Время открытия позиции
extern int    DayOfWeekIf    = 3;    // День недели условия
extern string TimeTradeIf    = "19:51"; // Время условия
extern int    DayOfWeekClose  = 5;    // День недели закрытия позиции
extern string TimeTradeClose  = "19:51";    // Время закрытия позиции

extern int    Duration   = 300;        // Продолжительность в секундах
//extern bool   Sell       = False;      // True-Sell, False-Buy
extern double Lots       = 0.1;        // Размер лота
extern int    StopLoss   = 30;         // Размер стопа в пунктах
extern int    TakeProfit = 60;         // Размер тейка в пунктах

extern string _P_Expert = "---------- Параметры советника";
extern int    MagicNumber   = 0;
extern int    NumberAccount = 0;            // Номер торгового счёта
extern bool   UseSound      = True;         // Использовать звуковой сигнал
extern string NameFileSound = "expert.wav"; // Наименование звукового файла
extern bool   ShowComment   = True;         // Показывать комментарий
extern bool   MarketWatch   = True;         // Запросы под исполнение "Market Watch".
extern int    Slippage      = 3;            // Проскальзывание цены
extern int    NumberOfTry   = 5;            // Количество торговых попыток
                                                
//------- Глобальные переменные советника -------------------------------------+
bool  gbDisabled = False;         // Флаг блокировки советника
bool  gbNoInit   = False;         // Флаг неудачной инициализации
color clOpenBuy  = LightBlue;     // Цвет значка открытия покупки
color clOpenSell = LightCoral;    // Цвет значка открытия продажи

bool   Sell;
//------- Подключение внешних модулей -----------------------------------------+
#include <stdlib.mqh>        // Стандартная библиотека МТ4

//int deinit()
//  {
//----
   
//----
 //  return(0);
 // }
  
//+----------------------------------------------------------------------------+
//|                                                                            |
//|  ПРЕДОПРЕДЕЛЁННЫЕ ФУНКЦИИ                                                  |
//|                                                                            |
//+----------------------------------------------------------------------------+
//|  Функция инициализации                                                     |
//+----------------------------------------------------------------------------+
void init() {
  gbNoInit=False;
  if (!IsTradeAllowed()) {
    Message("Для нормальной работы советника необходимо\n"+
            "Разрешить советнику торговать");
    gbNoInit=True; return;
  }
  if (!IsLibrariesAllowed()) {
    Message("Для нормальной работы советника необходимо\n"+
            "Разрешить импорт из внешних экспертов");
    gbNoInit=True; return;
  }
  if (!IsTesting()) {
    if (IsExpertEnabled()) Message("Советник будет запущен следующим тиком");
    else Message("Отжата кнопка \"Разрешить запуск советников\"");
  }
}

//+----------------------------------------------------------------------------+
//|  Функция деинициализации                                                   |
//+----------------------------------------------------------------------------+
void deinit() {
 if (!IsTesting()) Comment("");
 
      ObjectDelete("SLb"); //Трейлингстоп
   ObjectDelete("SLs"); //Трейлингстоп
   return(0);
    
 }

//+----------------------------------------------------------------------------+
//|  expert start function                                                     |
//+----------------------------------------------------------------------------+
void start() {

  if (gbDisabled) {
    Message("Критическая ошибка! Советник ОСТАНОВЛЕН!"); return;
  }
  if (gbNoInit) {
    Message("Не удалось инициализировать советник!"); return;
  }
  if (!IsTesting()) {
    if (NumberAccount>0 && NumberAccount!=AccountNumber()) {
      Comment("Торговля на счёте: "+AccountNumber()+" ЗАПРЕЩЕНА!");
      return;
    } else Comment("");
    if (ShowComment) {
      string st="CurTime="+TimeToStr(TimeCurrent(), TIME_MINUTES)
               +"  TimeTrade="+TimeTradeOpen
               +"  Позиция="+GetNameOP(Sell)
               +"  Lots="+DoubleToStr(Lots, 1)
               +"  StopLoss="+DoubleToStr(StopLoss, 0)+" п."
               +"  TakeProfit="+DoubleToStr(TakeProfit, 0)+" п."
               +IIFs(MarketWatch, "  MarketWatch", "")
               ;
      Comment(st);
    } else Comment("");
  }

   // ================= Условие =====================================
 //Sell = false;
 if (DayOfWeek()==DayOfWeekIf
 && TimeCurrent()>=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeIf)
 && TimeCurrent()<StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeIf)+Duration)
   {
    if  (iClose("XAUUSD",PERIOD_H1,0)-iOpen("XAUUSD",PERIOD_H1,0)>=0)
    Sell = true;
    if  (iOpen("XAUUSD",PERIOD_H1,0)-iClose("XAUUSD",PERIOD_H1,0)>0)
    Sell =false;
   }
   // Без условия все работает правильно. Sell тогда задаем во внешних параметрах. 
    
    
   // ================= Открытие позиции =====================================
  if (DayOfWeek()==DayOfWeekOpen
  && TimeCurrent()>=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeOpen)
  && TimeCurrent()<StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeOpen)+Duration)
  {
    if (!ExistPositions("", Sell, MagicNumber)) {
      double sl, tp;
      if (Sell) {
        if (StopLoss>0) sl=Bid+StopLoss*Point; else sl=0;
        if (TakeProfit>0) tp=Bid-TakeProfit*Point; else tp=0;
      } else {
        if (StopLoss>0) sl=Ask-StopLoss*Point; else sl=0;
        if (TakeProfit>0) tp=Ask+TakeProfit*Point; else tp=0;
      }
      OpenPosition("", Sell, Lots, sl, tp, MagicNumber);
    }
  }

  
//================= Закрытие всех ордеров в пятницу =====================================  
  
  if (DayOfWeek()==DayOfWeekClose
  && TimeCurrent()>=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeClose)
   && TimeCurrent()<StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeClose)+Duration)
{  if (OrdersTotal()>0)
   {  for (int i=OrdersTotal()-1; i>=0; i--)
      {  if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
         {  
            if (OrderType()==OP_BUY)
            {  RefreshRates();
               OrderClose(OrderTicket(),OrderLots(),Bid,1000);
               return(0);
            }
            if (OrderType()==OP_SELL)
            {  RefreshRates();
               OrderClose(OrderTicket(),OrderLots(),Ask,1000);
               return(0);
            }
         }
}  }  }
  
}

//+----------------------------------------------------------------------------+
//|                                                                            |
//|  ПОЛЬЗОВАТЕЛЬСКИЕ ФУНКЦИИ                                                  |
//|                                                                            |
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 06.03.2008                                                     |
//|  Описание : Возвращает флаг существования позиций                          |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    ot - время открытия             ( 0   - любое время открытия)           |
//+----------------------------------------------------------------------------+
bool ExistPositions(string sy="", int op=-1, int mn=-1, datetime ot=0) {
  int i, k=OrdersTotal();

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; 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);
}

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Возвращает наименование торговой операции                      |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    op - идентификатор торговой операции                                    |
//+----------------------------------------------------------------------------+
string GetNameOP(int op) {
  switch (op) {
    case OP_BUY      : return("Buy");
    case OP_SELL     : return("Sell");
    case OP_BUYLIMIT : return("Buy Limit");
    case OP_SELLLIMIT: return("Sell Limit");
    case OP_BUYSTOP  : return("Buy Stop");
    case OP_SELLSTOP : return("Sell Stop");
    default          : return("Unknown Operation");
  }
}

 
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Возвращает наименование таймфрейма                             |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    TimeFrame - таймфрейм (количество секунд)      (0 - текущий ТФ)         |
//+----------------------------------------------------------------------------+
string GetNameTF(int TimeFrame=0) {
  if (TimeFrame==0) TimeFrame=Period();
  switch (TimeFrame) {
    case PERIOD_M1:  return("M1");
    case PERIOD_M5:  return("M5");
    case PERIOD_M15: return("M15");
    case PERIOD_M30: return("M30");
    case PERIOD_H1:  return("H1");
    case PERIOD_H4:  return("H4");
    case PERIOD_D1:  return("Daily");
    case PERIOD_W1:  return("Weekly");
    case PERIOD_MN1: return("Monthly");
    default:         return("UnknownPeriod");
  }
}

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.02.2008                                                     |
//|  Описание : Возвращает одно из двух значений взависимости от условия.      |
//+----------------------------------------------------------------------------+
string IIFs(bool condition, string ifTrue, string ifFalse) {
  if (condition) return(ifTrue); else return(ifFalse);
}

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Вывод сообщения в коммент и в журнал                           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    m - текст сообщения                                                     |
//+----------------------------------------------------------------------------+
void Message(string m) {
  Comment(m);
  if (StringLen(m)>0) Print(m);
}

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 28.11.2006                                                     |
//|  Описание : Модификация одного предварительно выбранного ордера.           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    pp - цена установки ордера                                              |
//|    sl - ценовой уровень стопа                                              |
//|    tp - ценовой уровень тейка                                              |
//|    ex - дата истечения                                                     |
//+----------------------------------------------------------------------------+
void ModifyOrder(double pp=-1, double sl=0, double tp=0, datetime ex=0) {
  bool   fm;
  color  cl;
  double op, pa, pb, os, ot;
  int    dg=MarketInfo(OrderSymbol(), MODE_DIGITS), er, it;

  if (pp<=0) pp=OrderOpenPrice();
  if (sl<0 ) sl=OrderStopLoss();
  if (tp<0 ) tp=OrderTakeProfit();
  
  pp=NormalizeDouble(pp, dg);
  sl=NormalizeDouble(sl, dg);
  tp=NormalizeDouble(tp, dg);
  op=NormalizeDouble(OrderOpenPrice() , dg);
  os=NormalizeDouble(OrderStopLoss()  , dg);
  ot=NormalizeDouble(OrderTakeProfit(), dg);

  if (pp!=op || sl!=os || tp!=ot) {
    for (it=1; it<=NumberOfTry; it++) {
      if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) break;
      while (!IsTradeAllowed()) Sleep(5000);
      RefreshRates();
      fm=OrderModify(OrderTicket(), pp, sl, tp, ex, cl);
      if (fm) {
        if (UseSound) PlaySound(NameFileSound); break;
      } else {
        er=GetLastError();
        pa=MarketInfo(OrderSymbol(), MODE_ASK);
        pb=MarketInfo(OrderSymbol(), MODE_BID);
        Print("Error(",er,") modifying order: ",ErrorDescription(er),", try ",it);
        Print("Ask=",pa,"  Bid=",pb,"  sy=",OrderSymbol(),
              "  op="+GetNameOP(OrderType()),"  pp=",pp,"  sl=",sl,"  tp=",tp);
        Sleep(1000*10);
      }
    }
  }
}

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 10.04.2008                                                     |
//|  Описание : Открывает позицию по рыночной цене.                            |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (NULL или "" - текущий символ)          |
//|    op - операция                                                           |
//|    ll - лот                                                                |
//|    sl - уровень стоп                                                       |
//|    tp - уровень тейк                                                       |
//|    mn - MagicNumber                                                        |
//+----------------------------------------------------------------------------+
void OpenPosition(string sy, int op, double ll, double sl=0, double tp=0, int mn=0) {
  color    clOpen;
  datetime ot;
  double   pp, pa, pb;
  int      dg, err, it, ticket=0;
  string   lsComm=WindowExpertName()+" "+GetNameTF(Period());

  if (sy=="" || sy=="0") sy=Symbol();
  if (op==OP_BUY) clOpen=clOpenBuy; else clOpen=clOpenSell;
  for (it=1; it<=NumberOfTry; it++) {
    if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) {
      Print("OpenPosition(): Остановка работы функции");
      break;
    }
    while (!IsTradeAllowed()) Sleep(5000);
    RefreshRates();
    dg=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();
    if (MarketWatch)
      ticket=OrderSend(sy, op, ll, pp, Slippage, 0, 0, lsComm, mn, 0, clOpen);
    else
      ticket=OrderSend(sy, op, ll, pp, Slippage, sl, tp, lsComm, mn, 0, clOpen);
    if (ticket>0) {
      if (UseSound) PlaySound(NameFileSound); break;
    } else {
      err=GetLastError();
      if (pa==0 && pb==0) Message("Проверьте в Обзоре рынка наличие символа "+sy);
      // Вывод сообщения об ошибке
      Print("Error(",err,") opening position: ",ErrorDescription(err),", try ",it);
      Print("Ask=",pa," Bid=",pb," sy=",sy," ll=",ll," op=",GetNameOP(op),
            " pp=",pp," sl=",sl," tp=",tp," mn=",mn);
      // Блокировка работы советника
      if (err==2 || err==64 || err==65 || err==133) {
        gbDisabled=True; break;
      }
      // Длительная пауза
      if (err==4 || err==131 || err==132) {
        Sleep(1000*300); break;
      }
      if (err==128 || err==142 || err==143) {
        Sleep(1000*66.666);
        if (ExistPositions(sy, op, mn, ot)) {
          if (UseSound) PlaySound(NameFileSound); break;
        }
      }
      if (err==140 || err==148 || err==4110 || err==4111) break;
      if (err==141) Sleep(1000*100);
      if (err==145) Sleep(1000*17);
      if (err==146) while (IsTradeContextBusy()) Sleep(1000*11);
      if (err!=135) Sleep(1000*7.7);
    }
  }
  if (MarketWatch && ticket>0 && (sl>0 || tp>0)) {
    if (OrderSelect(ticket, SELECT_BY_TICKET)) ModifyOrder(-1, sl, tp);
  }
  
  
}
//+----------------------------------------------------------------------------+
 
Antonius:


What's the problem, it works.

Reason: