Better Way To Get Recently Order Ticket?

 

 Hello, I am currently using this method to get an order ticket when the order is placed successfully. Is this method the best practice? Is there any other more effective and secure way? Thank you in advance.

if(trade.PositionOpen(_Symbol, orderType, lot, NULL, NULL, NULL, cmt)) {
  ulong ticket;
  for(int i = 0; i < PositionsTotal(); ++i) {
    if(cPosition.SelectByIndex(i) && cPosition.Time() == TimeTradeServer() && cPosition.Magic() == magicNumber && cPosition.Symbol() == _Symbol) {
      cPosition.InfoInteger(POSITION_TICKET, ticket);
      // Do sth with ticket...
    } 
  }
}
Documentation on MQL5: Trade Functions / OrderGetTicket
Documentation on MQL5: Trade Functions / OrderGetTicket
  • www.mql5.com
OrderGetTicket - Trade Functions - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
PositionGetTicket(PositionsTotal()-1);

I would prefer this.

 
Le Minh Duc:

 Hello, I am currently using this method to get an order ticket when the order is placed successfully. Is this method the best practice? Is there any other more effective and secure way? Thank you in advance.

Most of the times on a real account the position can not be selected immediately after sending the order.

To solve this synchronously, you have to wait until the order is filled or cancelled. 

If you need the order ticket and not the position ticket then you can simply use 

ulong ticket=trade.ResultOrder();
 
Yashar Seyyedin #:

I would prefer this.

PositionGetTicket(PositionsTotal()-1);

This may be the most elegant way

Laszlo Tormasi #:

Most of the times on a real account the position can not be selected immediately after sending the order.

To solve this synchronously, you have to wait until the order is filled or cancelled. 

If you need the order ticket and not the position ticket then you can simply use 

ulong ticket=trade.ResultOrder();

Another option, it quite slow. But this will probably ensure asynchrony in live test

I just test it with a simple script:

#include <Trade/Trade.mqh>
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
CTrade trade;
void OnStart() {

  ulong time1;
  ulong time2;
  ulong ticket;
  ulong timeTemp = GetMicrosecondCount();

  for(int i = 100000; i >= 0; --i) {
    ticket = PositionGetTicket(PositionsTotal()-1);
  }
  time1 = timeTemp;

  timeTemp = GetMicrosecondCount();
  for(int i = 100000; i >= 0; --i) {
    ticket = trade.ResultOrder();
  }
  time2 = timeTemp;

//--- Result
  Print(time1, "ms");
  Print(time2, "ms");
}
//+------------------------------------------------------------------+

And the result