MT5 - Closing THE earliest open position

johnnybegoode

Trader
Jul 19, 2016
56
0
22
47
I have a list of open positions,
How do I go through them, compare and close THE earliest open position?
Thank you!

MQL5:
void CloseEarliestPosition()
{
 
 
 
}
 

johnnybegoode

Trader
Jul 19, 2016
56
0
22
47
In hedging, how does PositionSelect the 1st (Earliest) open position among all the open positions and to close it?
Do I need to compare the POSITION_TIME?
Thank you!
 

Enivid

Administrator
Staff member
Nov 30, 2008
18,532
1,355
144
Odesa
www.earnforex.com
No need. Just the earliest open position and to close it.
:)
If you need to select the earliest position for a specific currency pair, then you can use Position Select("EURUSD") to select the position and call PositionClose() method of the CTrade class to close it:

MQL5:
#include <Trade/Trade.mqh>
...
Trade = new CTrade;
...
Position Select("EURUSD"); // Or any other currency pair
ulong ticket = PositionGetInteger(POSITION_TICKET) // Get position's ticket.
Trade.PositionClose(ticket);

However, if you need to select the oldest position regardless of its currency symbol, you need to run a cycle first to find the oldest one (with the lowest ticket number):

MQL5:
#include <Trade/Trade.mqh>
...
Trade = new CTrade;
...
 
ulong ticket_min = ULONG_MAX;
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
    ulong ticket = PositionGetTicket(i);
    if (ticket < ticket_min) ticket_min = ticket;
}
Trade.PositionClose(ticket_min);