I am unable to get closing time for any position and ontrade not working - page 2

 
Anshul Chouhan #:

Thankyou so much for the help ,
what you mean to say is that there is no any function or any method inbuilt in mql5 to get closing time for history deals .
I am using onTrade and OntradeTransaction function onwards but then too I am unable to get the closing time of a single deal also if i am getting by any means of calculation it is ' 1708507218 ' in this format which concludes to 1970.01.01 00:00 on converting to date 

this is the code i am using 
No.

You are still working with tickets. Stop using tickets across positions, orders and deals.

They are all different.

There is only position_id that is all the same when identifying a deal to an order or an order to a position or a deal to a position.

That's why you cannot find the corresponding deals.
 
Dominik Egert #:
No.

You are still working with tickets. Stop using tickets across positions, orders and deals.

They are all different.

There is only position_id that is all the same when identifying a deal to an order or an order to a position or a deal to a position.

That's why you cannot find the corresponding deals.

As you told I am not using ticket now but I think I didn't got your point exactly can u please explain what changes I have to make in my code it will be really helpful 
you can give reference to my previous code or take in account this new code which is returning nothing useful .

void GetAllHistoryDealInfoo()
{
    // Loop through all history deals
    HistorySelect(from_date,to_date);
    for (int i = 37; i < HistoryDealsTotal(); i++)
    {
        // Get the position identifier associated with the deal
        long position_id = HistoryDealGetInteger(i, DEAL_POSITION_ID);

        // Retrieve deal information
        ulong ticket = HistoryDealGetInteger(i,DEAL_TICKET);
        double open_price = HistoryDealGetDouble(i, DEAL_PRICE);
        datetime open_time = HistoryDealGetInteger(i, DEAL_TIME);
        double net_profit_loss = HistoryDealGetDouble(i, DEAL_PROFIT);
        double volume = HistoryDealGetDouble(i, DEAL_VOLUME);
        double stop_loss = HistoryDealGetDouble(i, DEAL_SL);
        double take_profit = HistoryDealGetDouble(i, DEAL_TP);
        string symbol = HistoryDealGetString(i ,DEAL_SYMBOL);
        ENUM_DEAL_TYPE deal_type = HistoryDealGetInteger(i, DEAL_TYPE);
        
        // Find the corresponding order using the position_id
        //ulong ticket = 1;
        if (ticket != 0)
        {
            // Retrieve order information
            double close_price = OrderGetDouble(ORDER_PRICE_CURRENT);
            datetime close_time = OrderGetInteger(ORDER_TIME_DONE);

            // Calculate duration in seconds
            int duration_seconds = (int)(close_time - open_time);

            // Print or process the retrieved data
            Print("Symbol: ", symbol);
            Print("Position ID: ", position_id);
            Print("Open Price: ", open_price);
            Print("Open Time: ", TimeToString(open_time));
            Print("Close Price: ", close_price);
            Print("Close Time: ", TimeToString(close_time));
            Print("Net Profit/Loss: ", net_profit_loss);
            Print("Volume: ", volume);
            Print("Stop Loss: ", stop_loss);
            Print("Take Profit: ", take_profit);
            Print("Duration (seconds): ", duration_seconds);
            Print("Deal Type: ", EnumToString(deal_type));
        }
        else
        {
            Print("Corresponding order not found for position ID: ", position_id);
        }
    }
}

here is the previous code 

void GetAllHistoryDealInfo()
  {
// Loop through all history deals
   Print("this is history deal info");
   
//Print("time :",TimeCurrent());
   HistorySelect(from_date,to_date);
   Print("orders :",HistoryOrdersTotal());
   Print("deals :",HistoryDealsTotal());
   for(int i = 37; i < HistoryDealsTotal(); i++)
     {
      ulong deal_ticket = HistoryDealGetTicket(i);
      ulong close_ticket = HistoryDealGetInteger(deal_ticket, DEAL_MAGIC);
      datetime close_time = 0;
      double close_price = 0.0;
      for(int j = 0; j < HistoryDealsTotal(); j++)
        {
         ulong ticket = HistoryDealGetTicket(j);
         if(ticket == close_ticket)
           {
            close_time = HistoryDealGetInteger(ticket, DEAL_TIME);
            close_price = HistoryDealGetDouble(ticket, DEAL_PRICE);
            break;
           }
        }
      // Retrieve deal information
      double open_price = HistoryDealGetDouble(deal_ticket, DEAL_PRICE);
      datetime open_time = HistoryDealGetInteger(deal_ticket, DEAL_TIME);
      double net_profit_loss = HistoryDealGetDouble(deal_ticket, DEAL_PROFIT);
      double volume = HistoryDealGetDouble(deal_ticket, DEAL_VOLUME);
      double stop_loss = HistoryDealGetDouble(deal_ticket, DEAL_SL);
      double take_profit = HistoryDealGetDouble(deal_ticket, DEAL_TP);
      // int duration = HistoryDealGetInteger(deal_ticket, DEAL_DURATION);
      int duration_seconds = (int)(close_time - open_time);
      ENUM_DEAL_TYPE deal_type = HistoryDealGetInteger(deal_ticket, DEAL_TYPE);

      // Print or process the retrieved data
      Print("Symbol: ", Symbol());
      Print("Deal Ticket: ", deal_ticket);
      Print("Open Price: ", open_price);
      Print("Open Time: ", TimeToString(open_time));
      Print("Close Price: ", close_price);
      Print("Close Time: ", TimeToString(close_time));
      Print("Net Profit/Loss: ", net_profit_loss);
      Print("Volume: ", volume);
      Print("Stop Loss: ", stop_loss);
      Print("Take Profit: ", take_profit);
      Print("Duration: ", duration_seconds);
      Print("Deal Type: ", EnumToString(deal_type));
     }
  }
// returns 
        orders :37
	deals :38
	Symbol: USDSEK
	Deal Ticket: 150064600725
	Open Price: 0.65836
	Open Time: 2024.02.22 11:46
	Close Price: 0.0
	Close Time: 1970.01.01 00:00
	Net Profit/Loss: 5.19
	Volume: 0.03
	Stop Loss: 0.0
	Take Profit: 0.0
	Deal Type: DEAL_TYPE_SELL

// where everything is in accurate even symbol
 
Search for a history deal that has DEAL_ENTRY_IN and get its time?
 
Dominik Egert #:
So, a position has at minimum two deals, one to open, and one to close. But you can have more deals than that.

Let's say you want to find the last deal that closes out the position, then you need to search for the joungest deal related to that position.

So, either you have the position_id from the position at the time it was still open, or you need to identify that deal. Latter is a bit more complex.

In first case it is simple, you store the open time and the position_id, then you select the history between open time and now. Now you select the deal by using position_id. You repeat that until you have reached the end. The last successful call has your closing time.

In the latter case, I suggest to use OnTradeTransaction, or OnTrade to get notified of changes to your positions. It will take some effort to catch what you are looking for, but it is in there.

Hope this helps.

Hi , I got you point for a position in history having one  open and one close deal . I have successfully fetched all the history records and now calculating the closing time for a position ,
But for the deal at 0th index (means the trade that executed very first ) I am getting symbol as '' empty string and type = 2 also order as 0 
else all other trades information is accurate please resolve how to get 0th deal accurately.

 
datetime from_date=0;         // from the very beginning
datetime to_date=TimeCurrent();
HistorySelect(from_date,to_date);
//--- total number in the list of deals
   int deals=HistoryDealsTotal();
  
  
   for(int i=0; i<deals; i++)
     {
      deal_ticket=               HistoryDealGetTicket(i);
      Print("deal type at 0 :", HistoryDealGetInteger(150026271446,DEAL_TYPE)," Symbol :",HistoryDealGetString(deal_ticket,DEAL_SYMBOL), "Order :",HistoryDealGetInteger(150026271446,DEAL_ORDER) );
      Print("deal type at 1 :", HistoryDealGetInteger(150026296499,DEAL_TYPE)," Symbol :",HistoryDealGetString(deal_ticket,DEAL_SYMBOL), "Order :",HistoryDealGetInteger(150026296499,DEAL_ORDER) );
     }

//output 
        deal type at 0 :2 Symbol :  Order :0
        deal type at 1 :1 Symbol :USDCNH  Order :150025688751
 
Anshul Chouhan #:

Hi , I got you point for a position in history having one  open and one close deal . I have successfully fetched all the history records and now calculating the closing time for a position ,
But for the deal at 0th index (means the trade that executed very first ) I am getting symbol as '' empty string and type = 2 also order as 0 
else all other trades information is accurate please resolve how to get 0th deal accurately.

When the function HistoryDealGetTicket returns 0, it has failed.

Value of the ulong type. If the function fails, 0 is returned.

You need to check the error code to find out what happened. Use GetLastError or _LastError to find out.


 
Dominik Egert #:
When the function HistoryDealGetTicket returns 0, it has failed.

Value of the ulong type. If the function fails, 0 is returned.

You need to check the error code to find out what happened. Use GetLastError or _LastError to find out.


No no you didn't get it , HistoryDealTicket is returning valid tickets for every deal in the history when running inside the loop what i want is 
1. the deal at 0th index have a valid ticket , trade time but do not contain *SYMBOL* it shows  symbol as empty string and also the type is 2

https://www.mql5.com/en/forum/462605/page2#comment_52533997

this thing is happening only with the 0th index data for every else data i am getting all values 

Also ,I want to know that when we fetch deals from history we get one deal for buy and another for sell so what is common between the two deals how we can differentiate between the deals that this is the opening deal  for this trade and this is the closing deal .

Means I need a property or any sign that is common in all the deals of a single trade

 
Anshul Chouhan #:

Means I need a property or any sign that is common in all the deals of a single trade

Perhaps the translation of this post will help you figure it out.

HistoryPosition - неопубликованный функционал MQL5-языка.
HistoryPosition - неопубликованный функционал MQL5-языка.
  • 2023.11.22
  • www.mql5.com
HistoryPositionsTotal Возвращает количество всех закрытых позиций в истории. HistorySelect() не влияет на результат данной функции. int HistoryPositionsTotal(); Возвращаемое значение Значение типа
 
fxsaber #:

Perhaps the translation of this post will help you figure it out.

thanks I have added it to my Experts tab but it is not working and not getting compiled  showing lots of errors 
if these errors are resolved then I can achieve what i was looking for I have attached an screenshot for your reference

 
Anshul Chouhan #:

thanks I have added it to my Experts tab but it is not working and not getting compiled  showing lots of errors 
if these errors are resolved then I can achieve what i was looking for I have attached an screenshot for your reference

The MetaEditor clearly shows which file is needed with a red picture. There's even a link to this file.

 
Anshul Chouhan #:

No no you didn't get it , HistoryDealTicket is returning valid tickets for every deal in the history when running inside the loop what i want is 
1. the deal at 0th index have a valid ticket , trade time but do not contain *SYMBOL* it shows  symbol as empty string and also the type is 2

https://www.mql5.com/en/forum/462605/page2#comment_52533997

this thing is happening only with the 0th index data for every else data i am getting all values 

Also ,I want to know that when we fetch deals from history we get one deal for buy and another for sell so what is common between the two deals how we can differentiate between the deals that this is the opening deal  for this trade and this is the closing deal .

Means I need a property or any sign that is common in all the deals of a single trade

To your first issue, I am not sure what the issue is. - I dont have your history available.

The question you are asking is maybe answered like this:

One Position is made up of at least two Orders, while an Order can be one or multiple deals. So to figure out what opened your position, and what type it is, you need to figure out the order, because they have this information. - The deals that make up the execution of that order will tell you how your order was executed.

Also notice, some brokers use deals to insert swap or other balance operations on your account.