OrderSend() questions - page 3

 
 komposter:

Accounting for orders in MT5 is a whole science:Handling trade events in the Expert Advisor using the OnTrade() function

No pause will save you from reopening, a situation can always occur, in which the order will take 1 second longer to execute.

ps: And do not forget about magic.

The enabler?

No amount of science will save you from the machinations of global meth

of global meta-phobia.

Trying

 
her.human:
Thinking before you post is considered good style.
 

Unfortunately, MT5 has many more traps than MT4.

The problem with the delayed data update after successful execution ofOrderSend() is solved in the very last line of the following example:

MqlTradeRequest request;
MqlTradeResult result;
...
OrderSend(request,result);
...
Ticket=false;
Error==result.retcode;
if(Error==10008 || Error==10009){Ticket=true;}
...
if(Ticket==true){while(!HistoryDealSelect(result.deal)){RefreshRates();Sleep(1);}}   

Update function:

bool RefreshRates()
  {
   MqlTick tick;
   return(SymbolInfoTick(Symbol(),tick));
  }
 
sergey1294:

Here you go, it should work.


//+------------------------------------------------------------------+
//|                                                         Deal.mq5 |
//|                        Copyright 2012, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2012, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create timer
   EventSetTimer(1);

//---
   return(0);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- destroy timer
   EventKillTimer();

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---

   if(zOrderSend(_Symbol,0.1,ORDER_TYPE_BUY)==10009) // 10009 TRADE_RETCODE_DONE Заявка выполнена
     {
      Alert("Купили!");
     }
   else Alert("Не купили....");
  }
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
  {
//---

  }
//+------------------------------------------------------------------+
uint zOrderSend(string zSymbol,double zVolume,ENUM_ORDER_TYPE zORDER_TYPE)
  {
   MqlTradeRequest      request;
   MqlTradeCheckResult  ch_result;
   MqlTradeResult       result;

// обнулим структуру запроса перед заполнением
   ZeroMemory(request);

   Alert("*****************",zSymbol," ",zVolume," ",zORDER_TYPE);
// заполняем структуру
   request.action=TRADE_ACTION_DEAL;
   request.type_filling=ORDER_FILLING_AON;
   request.symbol=zSymbol;
   request.type=zORDER_TYPE;
   request.deviation=30;
   request.sl=0.0;
   request.tp=0.0;
   request.volume=zVolume;
   if(zORDER_TYPE==ORDER_TYPE_BUY)request.price=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   if(zORDER_TYPE==ORDER_TYPE_SELL)request.price=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);

// выводим на печать заполненную структуру торгового запроса
   Alert("   ENUM_TRADE_REQUEST_ACTIONS    request.action;           // Тип выполняемого действия                                     =",request.action,"=");
   Alert("   ulong                         request.magic;            // Штамп эксперта (идентификатор magic number)                   =", request.magic,         "=" );
   Alert("   ulong                         request.order;            // Тикет ордера                                                  =", request.order,         "=" );
   Alert("   string                        request.symbol;           // Имя торгового инструмента                                     =", request.symbol,        "=" );
   Alert("   double                        request.volume;           // Запрашиваемый объем сделки в лотах                            =", request.volume,        "=" );
   Alert("   double                        request.price;            // Цена                                                          =", request.price,         "=" );
   Alert("   double                        request.stoplimit;        // Уровень StopLimit ордера                                      =", request.stoplimit,     "=" );
   Alert("   double                        request.sl;               // Уровень Stop Loss ордера                                      =", request.sl,            "=" );
   Alert("   double                        request.tp;               // Уровень Take Profit ордера                                    =", request.tp,            "=" );
   Alert("   ulong                         request.deviation;        // Максимально приемлемое отклонение от запрашиваемой цены       =", request.deviation,     "=" );
   Alert("   ENUM_ORDER_TYPE               request.type;             // Тип ордера                                                    =", request.type,          "=" );
   Alert("   ENUM_ORDER_TYPE_FILLING       request.type_filling;     // Тип ордера по исполнению                                      =", request.type_filling,  "=" );
   Alert("   ENUM_ORDER_TYPE_TIME          request.type_time;        // Тип ордера по времени действия                                =", request.type_time,     "=" );
   Alert("   datetime                      request.expiration;       // Срок истечения ордера (для ордеров типа ORDER_TIME_SPECIFIED) =", request.expiration,    "=" );
   Alert("   string                        request.comment;          // Комментарий к ордеру                                          =", request.comment,       "=" );

// отправляем структуру запроса на проверку
   if(OrderCheck(request,ch_result)==false)
     {
      Alert("OrderCheck выявил ошибку: "+IntegerToString(ch_result.retcode)+"/"+ch_result.comment);
      return ch_result.retcode;
     }
// отправляем запрос на торговый сервер
   if(OrderSend(request,result)==false)
     {
      Alert("OrderSend возвратил ошибку: "+IntegerToString(result.retcode)+"/"+result.comment);
      return result.retcode;
     }
// выводим на печать структуру ответа сервера
   Alert("Код результата операции сервера: " + IntegerToString(result.retcode));
   Alert("deal Тикет сделки "                + IntegerToString(result.deal));
   Alert("order Тикет ордера "               + IntegerToString(result.order));
   Alert("volume Объем сделки "              + DoubleToString (result.volume));
   Alert("price Цена в сделке "              + DoubleToString (result.price));
   Alert("bid(цены реквоты) "                + DoubleToString (result.bid));
   Alert("ask(цены реквоты) "                + DoubleToString (result.ask));
   Alert("Комментарий: "+result.comment);

   return result.retcode;
  }
//+------------------------------------------------------------------+

In this great code - everything worked fine,

but there has been a change in the programming language.

mql5 has been removed.

ORDER_FILLING_AON;

And now the compilation does not work in this place.

Can you tell me how to fill in the structure correctly now?

// заполняем структуру
   request.action=TRADE_ACTION_DEAL;
   request.type_filling=ORDER_FILLING_AON;
   request.symbol=zSymbol;
   request.type=zORDER_TYPE;
   request.deviation=30;
   request.sl=0.0;
   request.tp=0.0;
   request.volume=zVolume;
   if(zORDER_TYPE==ORDER_TYPE_BUY)request.price=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   if(zORDER_TYPE==ORDER_TYPE_SELL)request.price=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
 
awkozlov:

In this wonderful code - everything worked fine,

but there was a change in the programming language.

mql5 has been removed

The answer is here - https://www.mql5.com/ru/forum/6343/page8#comment_189991. Yes, they missed this point and didn't announce it in the announcements for some reason.
 

Thanks a lot, Rosh!

Although. I've changed - to "take what's available" as I have an aggressive flip that's unlikely to happen.

Really curious, what tools did the developers mean by the primary acronyms in Russian or imported transcription?

Just out of curiosity, how verbally were the 2 variants implied ?

 
awkozlov:

Just out of curiosity, how were the 2 options verbally implied ?

  • ORDER_FILLING_AON - A trade can only be executed in the volume specified and at a price that is equal to or better than that specified in the order. If sufficient volume of offers for the order symbol is not available in the market at the moment, the order will not be executed.
  • ORDER_FILLING_CANCEL - An agreement to execute a trade at the maximum volume available on the market within the volume specified in the order, and at a price equal to or better than that specified in the order. In this case no additional orders are placed for the missing volume.
  •  

    Since we can have two execution policies for a market order, ORDER_FILLING_FOK and ORDER_FILLING_IOC, how appropriate would it be to fill in the request.type_filling field in a trade request as follows:

    request.type_filling=ORDER_FILLING_FOK | ORDER_FILLING_IOC
    The compiler only generates the warning: implicit enum conversion. Is that enough for the request to be processed correctly regardless of the execution policy set by the broker/dealer?
     
    Yedelkin:
    The compiler only generates the warning: implicit enum conversion. Is that enough for the request to be processed correctly regardless of the execution policy set by the broker/dealer?

    It's like "black coffee and milk" - two mutually exclusive policies. Here are more links in English:

    Fill Or Kill (FOK) Definition | Investopedia
    Fill Or Kill (FOK) Definition | Investopedia
    • www.investopedia.com
    A type of time-in-force designation used in securities trading that instructs a brokerage to execute a transaction immediately and completely or not at all. This type of order is most likely to be used by active traders and is usually for a large quantity of stock. The order must be filled in its entirety or canceled (killed). The purpose of a...
     
    Yedelkin:

    Since we can have two execution policies for a market order, ORDER_FILLING_FOK and ORDER_FILLING_IOC,

    This means that you can choose between the two options.
    Reason: