Why won't `trade.PositionClose(PositionGetSymbol(0)` close positions?

 

I have tried multiple approaches to this, based on the documentation and on information I've found in this forum, and I can't get anything to work.

Simple version:

void CloseAllPositions() {
    CTrade trade;
    while (PositionsTotal() > 0) {
        trade.PositionClose(PositionGetSymbol(0));
    }
}


Same thing but with a bunch of Print statements to try to track down the issues:

void CloseAllPositions() {
    Print("Entered CloseAllPositions(). PositionsTotal = ", PositionsTotal());
    CTrade trade;
    while (PositionsTotal() > 0) {
        Print("About to close position. PositionsTotal = ", PositionsTotal());
        Print(PositionGetSymbol(0));
        Print(PositionGetTicket(0));
        Print(trade.PositionClose(PositionGetSymbol(0)));
        Print(trade.ResultRetcode(), trade.ResultRetcodeDescription());
        Print("Closed position. PositionsTotal = ", PositionsTotal());
    }
    Print("Exiting CloseAllPositions(). PositionsTotal = ", PositionsTotal());
}


The Symbol printed out by the Print(PositionGetSymbol(0)) line is correct. The error message simply says "10006 Request rejected" and no positions ever close.

I understand closing positions is complex in MQL5, but this is the Standard Library function.  It's pretty hard to get it wrong...?  What could possibly be causing this to reject?

Thanks in advance for any help.

Documentation on MQL5: Standard Library
Documentation on MQL5: Standard Library
  • www.mql5.com
Standard Library - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
trade.PositionClose probably has a boolean return value you could print that and look what it says
 
Use the debugger and step into the function. Find out why.
 
David _Detnator_:

I have tried multiple approaches to this, based on the documentation and on information I've found in this forum, and I can't get anything to work.

Simple version:


Same thing but with a bunch of Print statements to try to track down the issues:


The Symbol printed out by the Print(PositionGetSymbol(0)) line is correct. The error message simply says "10006 Request rejected" and no positions ever close.

I understand closing positions is complex in MQL5, but this is the Standard Library function.  It's pretty hard to get it wrong...?  What could possibly be causing this to reject?

Thanks in advance for any help.

Probably because closing a position takes time, and PositionTotal() is not updated synchronously, so you are trying to close a position which is already closed ?
Reason: