Sleep function and Closing all trades

 

Hi everyone,

How to close all positions instantly, without using the Sleep function as in the following code pls ?

bool CloseAllPositions(){
   int total = PositionsTotal();
   for (int i = total - 1 ; i >= 0; i--){
      ulong positionTicket = PositionGetTicket(i);
      PositionSelectByTicket(positionTicket);
      trade.PositionClose(positionTicket);

      Sleep(100);

   }
   return true;   
}


Best Reguards,
ZeroCafeine.

 
ZeroCafeine:Hi everyone, How to close all positions instantly, without using the Sleep function as in the following code pls ?Best Reguards, ZeroCafeine.

You can't instantly close a position! It takes time. The instruction goes out to the trade server and then it takes some time for it to be carried out.

You should not be using "sleep" anyway. Your code logic should be such that it tracks the state of things or be more event driven.

 
Hello

Successful completion of the PositionClose(...) method does not always mean successful execution of the trade operation. It is necessary to check the result of trade request (trade server return code) using 
ResultRetcode()

And otherwise are you okay?
 

tks you @ Fernando Carreiro


I completely understand your reasoning, but do you have an example of code?


on this code example:

bool ClosePositions(){
   int total = PositionsTotal();
   for (int i = total - 1 ; i >= 0; i--){
      if(total != PositionsTotal()){ total = PositionsTotal(); i = total; continue;}
      ulong positionTicket = PositionGetTicket(i);
      if(positionTicket <= 0) { Print(__FUNCTION__, " : Failed to get Ticket"); return  false; }
      if(!PositionSelectByTicket(positionTicket)) { Print(__FUNCTION__, " : Failed to Select Position By Ticket"); return false; }

      long magic;
      if(!PositionGetInteger(POSITION_MAGIC, magic)) { Print(__FUNCTION__, " : Failed to Get Position Magic Number"); return false; }

      if(magic == 0){
         trade.PositionClose(positionTicket);

         //---
         //Sleep(100);

         if(trade.ResultRetcode() != TRADE_RETCODE_DONE){
            Print(__FUNCTION__, " : Error Closing Poition Ticket : ", (string)positionTicket,
               " Result : ", (string)trade.ResultRetcode(), " : ", trade.CheckResultRetcodeDescription()
            );
            return false;
         }
      }
   }
   // Voila
   return true;   
}

I call the function with a keyboard shortcut :

if(lparam == KEY_J) { 
   ClosePositions();
   Print("ClosePositions CALLED"); 
}


sometimes when I call the function 2 or 3 positions only are closed out of 10, and then I get an error message , how can I find out where this error comes from?

2023.10.26 14:39:13.671 Trades '42276998': failed market buy 0.1 [SP500] [Position doesn't exist]


Fernando Carreiro
Fernando Carreiro
  • 2023.10.01
  • www.mql5.com
Trader's profile
Reason: