OrderSend() questions

 

The first day of the Championship has shown that my Expert Advisor does not work as intended, namely, instead of a single pending order it places several unidirectional pending orders. This is approximately the following structure:

bool flag_order=false;
...
if(OrderSend(request,result)) flag_order=true;  //из блока обработки (модификации) имеющихся отложенных ордеров
...
if(flag_order==false)                            //из блока выставления отложенных ордеров
  {
   ...
   OrderSend(request,result);
  }                                           
Question: Does the terminal wait for the OrderSend() function from the first block to finish processing [i.e. wait for the request to be received], or immediately pass to the next operator (block) after sending a trade request to the server?
 

We will, of course, check your case.

But in general the OrderSend function works according to the help.

Возвращаемое значение

In case ofsuccessful basic check of structures (pointer check) it returns true - it does not indicate successful execution of trade operation. To get a more detailed description of the result of the function, we should analyze the fields of the result structure .

Документация по MQL5: Торговые функции / OrderSend
Документация по MQL5: Торговые функции / OrderSend
  • www.mql5.com
Торговые функции / OrderSend - Документация по MQL5
 
alexvd:

We will, of course, check your case.

But in general, the OrderSend function works according to the help.

No, I'm not complaining, I just want to understand. Maybe I screwed up somewhere else... I also analyzed result structure fields where I thought they should be [as I was taught :)].

But as I understand it, at least it's supposed that pass to next operator should be done only after the terminal completely handles OrderSend() function [including getting and handling fields of result structure]?

(Sorry, in previous question I made a typo: I specified request instead of result)

 
Yedelkin:

The first day of the Championship has shown that my Expert Advisor does not work as intended, namely, instead of a single pending order it places several unidirectional pending orders. This is approximately the same structure:

Question: Does the terminal wait for the OrderSend() function from the first block to finish processing [i.e. wait for the request to be received], or does it immediately switch to the next operator (block) after sending a trade request to the server?

I confirm the problem. After setting the OrderSend() of a pending order, OrdersTotal does not always see it.

I set a pause after OrderSend(). But it didn't help the robot at the championship today :)

 

Good afternoon, All.

I'm trying to make a program that would just open an order according to the market. i.e. I send a Symbol, Volume and Order Type there, in a loop until a Position with the direction I want appears.

The log gives out

2012.01.09 16:08:42 Trades '9066293' : failed instant buy 1.00 EURUSD at 0.0000 (deviation: 103117312) [Invalid stops].

So if I open at the market, why do I need to specify the opening price? I don't need any stops.

I would open by F9.

Please, advise me where I screwed up or write some code for opening an order.

I am filling the structure with such a minimum:

uint zOrderSend (string zSymbol, double zVolume, string zORDER_TYPE)
  {
zSymbol = "EURUSD";
zVolume = 1;
zORDER_TYPE ="Buy";
  Alert ("*****************", zSymbol," ", zVolume," ", zORDER_TYPE);
//--- готовим запрос
   MqlTradeRequest request;
   request.action=TRADE_ACTION_DEAL;
//   request.magic=0;
   request.symbol=zSymbol;
//   request.volume=zVolume;
   request.volume=zVolume;
//   request.price=0;
//   request.sl=0;
//   request.tp=0;
//   request.deviation=SymbolInfoInteger("EURUSD",SYMBOL_SPREAD);                                         // slippage                           
//   request.deviation=50;
//--- сформируем тип ордера
if (zORDER_TYPE == "Buy" ) {request.type =  ORDER_TYPE_BUY ;}    // тип ордера = 0
if (zORDER_TYPE == "Sell") {request.type =  ORDER_TYPE_SELL;}    // тип ордера = 1
Alert ("Тип ордера: request.type = ",request.type);
   request.type_filling = ORDER_FILLING_FOK;
   request.type_time = ORDER_TIME_GTC;
//   request.comment = "";
The entire Expert Advisor test for opening a position is in the file.
Files:
 
awkozlov:

Good afternoon, All.

I'm trying to make a program that would just open a market order. i.e. i send there a Symbol, Volume and Order Type, in a loop until a Position with the direction i want appears.

And something gives me = Invalid Stops, while I don't need any Stops for a market order. I do not know where I am going wrong...

The entire test of the Expert Advisor to open a position is in the file.


Here you go, it should work.

//+------------------------------------------------------------------+
//|                                                         Deal.mq5 |
//|                        Copyright 2012, MetaQuotes Software Corp. |
//|                                              https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2012, MetaQuotes Software Corp."
#property link      "https://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;
  }
//+------------------------------------------------------------------+
 
sergey1294:

there you go, it should work.


Thank you. It's working. And so fast that it doesn't have time to update the Position information.

As a result, 2 orders are placed.

It can be fixed with a 1 millisecond pause !


   if(zOrderSend(_Symbol,0.1,ORDER_TYPE_BUY)==10009) // 10009 TRADE_RETCODE_DONE Заявка выполнена
     {
Sleep (1);
       Alert("Купили!");
     }
   else Alert("Не купили....");
  }
 
awkozlov:

... does not have time to update the position information.

As a result, 2 orders are placed.

This can be solved by pausing for 1 millisecond !

Just keep in mind that pause is not a panacea:

 
Yedelkin:

Just bear in mind that pausing is not a panacea:

KimV's order check function won't help?
 
-Alexey-:
Does KimV's order check function not help?
I must have missed a topic like this. Where can I find out about KimV's order verification feature?
Reason: