Trade server return code
10045 TRADE_ RETCODE_ FIFO_ CLOSE
FIFO rule: positions must be closed oldest first
What it means
The account only allows positions on a symbol to be closed in the order they were opened, first in, first out (ACCOUNT_FIFO_CLOSE is true). Closing a newer position while an older one on the same symbol is open is refused. On accounts that are not hedging accounts the property is always false.
Common causes
- Closing the position with the largest profit in a basket first.
- A partial take profit that closes the last-added position of a grid.
- A manual or other EA's older position on the same symbol, which must be closed before yours.
A real scenario
A basket EA on an account with the FIFO rule closes its positions from the newest to the oldest, as the loop over PositionsTotal() runs backwards. The first close is the newest position and fails with 10045. Sorting by open time and closing oldest first worked, and the EA now stops with a message when the oldest position on the symbol is not its own.
How to fix it
- Read
ACCOUNT_FIFO_CLOSEat start. - When it is true, close positions on a symbol in order of
POSITION_TIME_MSC, oldest first. - If the oldest position on the symbol is not your EA's, do not close someone else's trade: stop and report it.
Fixed MQL5 code
#include <Trade/Trade.mqh>
CTrade trade;
input long InpMagic = 20261130;
// Close this EA's positions on a symbol, oldest first (required on FIFO accounts, harmless elsewhere).
bool CloseOldestFirst(const string symbol)
{
bool fifo = (bool)AccountInfoInteger(ACCOUNT_FIFO_CLOSE);
for(int guard = 0; guard < 500; guard++)
{
ulong oldest = 0;
long oldestMsc = 0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0 || PositionGetString(POSITION_SYMBOL) != symbol)
continue;
if(!fifo && PositionGetInteger(POSITION_MAGIC) != InpMagic)
continue; // without FIFO only our own positions matter
long opened = PositionGetInteger(POSITION_TIME_MSC);
if(oldest == 0 || opened < oldestMsc)
{
oldest = ticket;
oldestMsc = opened;
}
}
if(oldest == 0)
return true; // nothing left to close
if(!PositionSelectByTicket(oldest) || PositionGetInteger(POSITION_MAGIC) != InpMagic)
{
Print("FIFO: the oldest position on this symbol is not this EA's; close it first");
return false;
}
if(!trade.PositionClose(oldest))
return false;
}
return false;
}
A focused example for MetaTrader 5: adapt names, magic number and limits to your EA, and test it on a demo account first.
Related codes
- 10046Hedge ProhibitedTRADE_RETCODE_HEDGE_PROHIBITEDHedge prohibited: no opposite positions on one symbol
- 4753Position Not FoundERR_TRADE_POSITION_NOT_FOUNDPosition not found: the ticket points at a position that is gone
Sources
Get your EA fixed
Still failing with 10045? Send us the EA and the journal lines: we find the cause in the code and fix it. Or check it yourself first with the EA Doctor.