how can Orders, Positions and Deals be linked together? - page 2

 
How can I retrieve this number through report history?
 
Kaden407 #:
How can I retrieve this number through report history?
"HistorySelectByPosition() creates in a mql5 program a list of orders and a list of deals with a specified position identifier for further reference to the elements of the list using the appropriate functions. To know the size of the list of deals, use function HistoryDealsTotal(), the size of the list of orders in the history can be obtained using HistoryOrdersTotal(). To run through elements of the orders list, use HistoryOrderGetTicket(), for elements of the deals list - HistoryDealGetTicket()."
Documentation on MQL5: HistorySelectByPosition / Trade Functions
Documentation on MQL5: HistorySelectByPosition / Trade Functions
  • www.mql5.com
Retrieves the history of deals and orders having the specified position identifier. Parameters position_id [in]  Position identifier that is...
 
Ryan L Johnson #:
"HistorySelectByPosition() creates in a mql5 program a list of orders and a list of deals with a specified position identifier for further reference to the elements of the list using the appropriate functions. To know the size of the list of deals, use function HistoryDealsTotal(), the size of the list of orders in the history can be obtained using HistoryOrdersTotal(). To run through elements of the orders list, use HistoryOrderGetTicket(), for elements of the deals list - HistoryDealGetTicket()."
Thank you!!
 

To answer Kaden407's question: DEAL_POSITION_ID is the link you need. Every deal — including each partial close — carries the DEAL_POSITION_ID property, which equals the POSITION_IDENTIFIER of the position it belongs to. This survives across multiple partial closes and correctly differentiates two overlapping positions on the same symbol, because each position has its own unique identifier.

HistorySelect(startTime, endTime);
for(int i = 0; i < HistoryDealsTotal(); i++)
{
   ulong ticket  = HistoryDealGetTicket(i);
   ulong posId   = (ulong)HistoryDealGetInteger(ticket, DEAL_POSITION_ID);
   ENUM_DEAL_ENTRY entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(ticket, DEAL_ENTRY);
   // DEAL_ENTRY_IN  = opening deal
   // DEAL_ENTRY_OUT = partial or full close
   // Group by posId to collect every close for a given position
}

To reconstruct a full position lifecycle: select all deals sharing the same DEAL_POSITION_ID, separate them by DEAL_ENTRY (IN vs OUT), and sum the OUT deals to get total realized P&L including all partials. Symbol and magic number are secondary filters — DEAL_POSITION_ID is the authoritative tie between every open, partial close, and final close that touched the same position.