In the MQL5 language, to get the current TP of an open position (hedging mode), I use
if (PositionSelectByTicket(positionId)) {
return PositionGetDouble(POSITION_TP);
}
Once the position is closed, I search for the corresponding ENTRY_IN deal, and query the corresponding order for the TP:
if (HistorySelectByPosition(positionId)) {
for (int i = HistoryDealsTotal()-1; i >= 0; i--) {
ulong dealId = HistoryDealGetTicket(i);
if (HistoryDealGetInteger(dealId, DEAL_POSITION_ID) != positionId) continue;
if ((ENUM_DEAL_ENTRY)HistoryDealGetInteger(dealId, DEAL_ENTRY) != DEAL_ENTRY_IN) continue;
ulong orderId = HistoryDealGetInteger(dealId, DEAL_ORDER);
if (HistoryOrderSelect(orderId)) {
return HistoryOrderGetDouble(orderId, ORDER_TP);
}
}
}
However, this only works if the TP was set directly while opening the position. If the TP was set later, this does not work. I examined all deals and orders corresponding to the positionId
, but was not able to find the TP anywhere.
What is a robust method to obtain the TP of a closed position?
Via the MQL5 forum I got the following suggestion from @fxsaber: the DEAL_TP property of the DEAL_ENTRY_OUT deal contains the last TP set. That indeed works!
if (HistorySelectByPosition(positionId)) {
for (int i = HistoryDealsTotal()-1; i >= 0; i--) {
ulong dealId = HistoryDealGetTicket(i);
if (HistoryDealGetInteger(dealId, DEAL_POSITION_ID) != positionId) continue;
if ((ENUM_DEAL_ENTRY)HistoryDealGetInteger(dealId, DEAL_ENTRY) != DEAL_ENTRY_OUT) continue;
return HistoryDealGetDouble(dealId, DEAL_TP);
}
}