Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1556

 
Aleksei Gureev #:

I'm sure it'll be a lot better now. And I won't be draining as fast as I used to.

Good luck in trading!

Regards, Vladimir.

 
MrBrooklin #:

Good luck with your trading!

Regards, Vladimir.

Thank you! Likewise.

 

Good morning everyone!

I must have missed something in OOP self-training. I take a function to modify a pending order:

OrderModify

Изменяет параметры отложенного ордера.

bool  OrderModify( 
   ulong                 ticket,         // тикет ордера 
   double                price,          // цена исполнения 
   double                sl,             // цена stop loss  
   double                tp,             // цена take profit 
   ENUM_ORDER_TYPE_TIME  type_time,      // тип по истечению 
   datetime              expiration,     // истечение 
   double                stoplimit       // цена Limit ордера  
   )
 
Параметры
ticket
[in]  Тикет ордера.
price
[in]  Новая цена, по которой ордер должен быть исполнен (либо предыдущее значение, если изменение не нужно).
sl
[in]  Новая цена, по которой сработает Stop Loss (либо предыдущее значение, если изменение не нужно).
tp
[in]  Новая цена, по которой сработает Take Profit (либо предыдущее значение, если изменение не нужно).
type_time
[in]  Новый тип ордера по истечению из перечисления ENUM_ORDER_TYPE_TIME (либо предыдущее значение, если изменение не нужно).
expiration
[in]  Новый срок истечения отложенного ордера (либо предыдущее значение, если изменение не нужно).
stoplimit
[in]  Новая цена, по которой будет выставлен Limit ордер при достижении ценой значения price. Указывается только для StopLimit ордеров.

Возвращаемое значение
true - в случае успешной базовой проверки структур, иначе false.

Примечание
Успешное окончание работы метода OrderModify(...) не всегда означает успешное совершение торговой операции. 
Необходимо проверять результат выполнения торгового запроса (код возврата торгового сервера) вызовом метода ResultRetcode().

and I specify only ticket, price, sl and tp values. The compiler generates an error that the number of parameters is incorrect. As far as I remember, if other parameters are not needed to modify a pending order, they could be omitted. Or am I confused with something?

But when I fill the parameters type_time and expiration that I do not need with zeros, then there is no error.

Regards, Vladimir.

 
MrBrooklin pending order:

and I specify only ticket, price, sl and tp values. The compiler generates an error that the number of parameters is incorrect. As far as I remember, if other parameters are not needed to modify a pending order, they could be omitted. Or am I confused with something?

But when I fill the parameters type_time and expiration that I don't need with zeros, then there is no error.

Regards, Vladimir.

OOP has nothing to do with it, you should observe syntax when calling a function

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
OrderModify(0,0,0,0,0,0,0);
  
  }
//+------------------------------------------------------------------+
bool  OrderModify( 
   ulong                 ticket,         // тикет ордера 
   double                price,          // цена исполнения 
   double                sl,             // цена stop loss  
   double                tp,             // цена take profit 
   ENUM_ORDER_TYPE_TIME  type_time,      // тип по истечению 
   datetime              expiration,     // истечение 
   double                stoplimit       // цена Limit ордера  
   )
{
//тело функции
return(true);
}
 
MrBrooklin pending order:

and I specify only ticket, price, sl and tp values. The compiler generates an error that the number of parameters is incorrect. As far as I remember, if other parameters are not needed to modify a pending order, they could be omitted. Or am I confused with something?

But when I fill the parameters type_time and expiration that I don't need with zeros, then there is no error.

Regards, Vladimir.

Hi Vladimir. You should zeroise the structure before filling it. There is rubbish stuck in these fields and the compiler considers it as entered values.

 
Alexey Viktorov #:

Hi Vladimir. You should zeroise the structure before filling it. There is rubbish stuck in these fields and the compiler considers it as entered values.

He has an error in compilation, not in sending the order.

I agree with the zeros.
 
lynxntech #:

OOP has nothing to do with it, you have to respect the syntax when calling a function

In procedural programming in MQL5 to modify a pending order the use of

   ENUM_ORDER_TYPE_TIME  type_time,      // тип по истечению 
   datetime              expiration,     // истечение

is not required at all. This may be the reason for misunderstanding how the OrderModify() function works in OOP.

Regards, Vladimir.

 
Alexey Viktorov #:

Hi Vladimir. You should zeroise the structure before filling it. There is rubbish stuck in these fields and the compiler considers it as entered values.

Hi Alexey, thanks for the hint.

Regards, Vladimir.

 
MrBrooklin #:

In MQL5 procedural programming to modify a pending order the use of

is not required at all. This may be the reason for misunderstanding how the OrderModify() function works in OOP.

Regards, Vladimir.

can you insert a function from the procedural variant?

 
lynxntech #:

can you insert a function from the procedural version?

I can. Taken from MetaEditor 5 Reference Manual

Пример торговой операции TRADE_ACTION_MODIFY для модификации уровней цен отложенного ордера:



#define  EXPERT_MAGIC 123456  // MagicNumber эксперта
//+------------------------------------------------------------------+
//| Модификация отложенных ордеров                                   |
//+------------------------------------------------------------------+
void OnStart()
  {
//-- объявление и инициализация запроса и результата
   MqlTradeRequest request={};
   MqlTradeResult  result={};
   int total=OrdersTotal(); // количество установленных отложенных ордеров
//--- перебор всех установленных отложенных ордеров
   for(int i=0; i<total; i++)
     {
      //--- параметры ордера
      ulong  order_ticket=OrderGetTicket(i);                             // тикет ордера
      string order_symbol=Symbol();                                      // символ
      int    digits=(int)SymbolInfoInteger(order_symbol,SYMBOL_DIGITS);  // количество знаков после запятой
      ulong  magic=OrderGetInteger(ORDER_MAGIC);                         // MagicNumber ордера
      double volume=OrderGetDouble(ORDER_VOLUME_CURRENT);                // текущий объем ордера
      double sl=OrderGetDouble(ORDER_SL);                                // текущий Stop Loss ордера
      double tp=OrderGetDouble(ORDER_TP);                                // текущий Take Profit ордера
      ENUM_ORDER_TYPE type=(ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE); // тип ордера
      int offset = 50;                                                   // отступ от текущей цены для установки ордера, в пунктах
      double price;                                                      // цена срабатывания ордера
      double point=SymbolInfoDouble(order_symbol,SYMBOL_POINT);          // размер пункта
      //--- вывод информации об ордере
      PrintFormat("#%I64u %s  %s  %.2f  %s  sl: %s  tp: %s  [%I64d]",
                  order_ticket,
                  order_symbol,
                  EnumToString(type),
                  volume,
                  DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),digits),
                  DoubleToString(sl,digits),
                  DoubleToString(tp,digits),
                  magic);
      //--- если MagicNumber совпадает, Stop Loss и Take Profit не заданы
      if(magic==EXPERT_MAGIC && sl==0 && tp==0)
        {
         request.action=TRADE_ACTION_MODIFY;                           // тип торговой операции
         request.order = OrderGetTicket(i);                            // тикет ордера
         request.symbol   =Symbol();                                   // символ
         request.deviation=5;                                          // допустимое отклонение от цены
        //--- установка уровня цены, тейк-профит и стоп-лосс ордера в зависимости от его типа
         if(type==ORDER_TYPE_BUY_LIMIT)
           {
            price = SymbolInfoDouble(Symbol(),SYMBOL_ASK)-offset*point; 
            request.tp = NormalizeDouble(price+offset*point,digits);
            request.sl = NormalizeDouble(price-offset*point,digits);
            request.price    =NormalizeDouble(price,digits);                // нормализованная цена открытия
           }
         else if(type==ORDER_TYPE_SELL_LIMIT)
           {
           price = SymbolInfoDouble(Symbol(),SYMBOL_BID)+offset*point; 
            request.tp = NormalizeDouble(price-offset*point,digits);
            request.sl = NormalizeDouble(price+offset*point,digits);
            request.price    =NormalizeDouble(price,digits);                 // нормализованная цена открытия
           }
         else if(type==ORDER_TYPE_BUY_STOP)
           {
           price = SymbolInfoDouble(Symbol(),SYMBOL_ASK)+offset*point; 
            request.tp = NormalizeDouble(price+offset*point,digits);
            request.sl = NormalizeDouble(price-offset*point,digits);
            request.price    =NormalizeDouble(price,digits);                 // нормализованная цена открытия
           }
         else if(type==ORDER_TYPE_SELL_STOP)
           {
           price = SymbolInfoDouble(Symbol(),SYMBOL_BID)-offset*point; 
            request.tp = NormalizeDouble(price-offset*point,digits);
            request.sl = NormalizeDouble(price+offset*point,digits);
            request.price    =NormalizeDouble(price,digits);                 // нормализованная цена открытия
           }
         //--- отправка запроса
         if(!OrderSend(request,result))
            PrintFormat("OrderSend error %d",GetLastError());  // если отправить запрос не удалось, вывести код ошибки
         //--- информация об операции   
         PrintFormat("retcode=%u  deal=%I64u  order=%I64u",result.retcode,result.deal,result.order);
         //--- обнуление значений запроса и результата
         ZeroMemory(request);
         ZeroMemory(result);
        }
     }
  }
//+------------------------------------------------------------------+

Regards, Vladimir.