javad
javad

Reputation: 835

Get an open position ticket in MQL5

I want to get the ticket number immediately after opening the position.

The output of this code is zero:

bool r = trade.Buy(0.1, Symbol(), 0, 0, 0); 
   
   if(r) 
   {            
      position_Info.SelectByIndex(0);
      Alert(position_Info.Ticket());      
   }

But if I add a delay command, the output will be displayed correctly:

bool r = trade.Buy(0.1, Symbol(), 0, 0, 0); 
   
   if(r) 
   {      
      Sleep(2000); // <=======================HERE
      position_Info.SelectByIndex(0);
      Alert(position_Info.Ticket());      
   }

How can I do this without adding a delay command?

Upvotes: 0

Views: 2525

Answers (1)

PaulB
PaulB

Reputation: 1403

Check the documentation.

Successful completion of the Buy method does not always mean successful execution of the trade operation. It is necessary to check the result of trade request (trade server return code) using ResultRetcode() and value returned by ResultDeal().

ulong  ResultDeal() const

Return Value = Deal ticket if the deal is executed.

The following code example has been tested and confirmed as working:

#property strict

#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\PositionInfo.mqh>

CTrade   trade;
CPositionInfo position_Info;

datetime TimeBar;

//+------------------------------------------------------------------+
//| Initialization function of the expert                            |
//+------------------------------------------------------------------+
int OnInit()
{
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| "Tick" event handler function                                    |
//+------------------------------------------------------------------+
void OnTick()
{
   if(TimeBar==iTime(_Symbol,_Period,0))
   {
   return;
   }

   if(TimeBar==0)
   {
      bool res = trade.Buy(0.1, Symbol(), 0, 0, 0); 
      if(res && trade.ResultRetcode()==TRADE_RETCODE_DONE) Print(trade.ResultDeal());
      TimeBar=iTime(_Symbol,_Period,0);
   return;
   }

   TimeBar=iTime(_Symbol,_Period,0);
return;
}

Upvotes: 1

Related Questions