Close all positions

 

All,

How to close all opened positions in MQL5. Need your sample please

 
riyo:

All,

How to close all opened positions in MQL5. Need your sample please

 

See https://www.mql5.com/en/forum/902 

 

 
phampton:

 

See https://www.mql5.com/en/forum/902 

 

Thank Phampton,

It looks that it is for single position only. How to close all positions from the last position to the first position. Sorry for this dummy question. I just learn this MQL5 language

 
riyo:

Thank Phampton,

It looks that it is for single position only. How to close all positions from the last position to the first position. Sorry for this dummy question. I just learn this MQL5 language

 

Try it - it should close every position until PositionsTotal()==0.
 
phampton:
Try it - it should close every position until PositionsTotal()==0.

Sorry, I've just tested it, and found that the loop is a fraction too quick for PositionsTotal() to pick up the change.  It works with a Sleep(1000) added, but it seems safer to re-write to be a conventional loop

#include <trade/trade.mqh>

void OnStart()
  {
   CTrade trade;
   int i=PositionsTotal()-1;
   while (i>=0)
     {
      if (trade.PositionClose(PositionGetSymbol(i))) i--;
     }
  }

 

 
Paul:

Sorry, I've just tested it, and found that the loop is a fraction too quick for PositionsTotal() to pick up the change.  It works with a Sleep(1000) added, but it seems safer to re-write to be a conventional loop

 

Does the code above works?

Where to add the Sleep(1000)?

How to rewrite it to a conventional loop?

 

Mql5 not Mql4

void CloseAll()

{

   for (int i=PositionsTotal()-1;i>=0; i--) 

   { 

      {                 

         if(!trade.PositionClose(PositionGetSymbol(i))) 

         {

      //--- failure message

      Print(PositionGetSymbol(i), "PositionClose() method failed. Return code=",trade.ResultRetcode(),

            ". Code description: ",trade.ResultRetcodeDescription());

         }

           

         else

         {

      Print(PositionGetSymbol(i), "PositionClose() method executed successfully. Return code=",trade.ResultRetcode(),

            " (",trade.ResultRetcodeDescription(),")");

         }

      }

   }

     

} 
 
Chee Chua:I do need  to close some position at the same time, is this script works on mt5?
 
         do{
               if(PositionSelect(_Symbol)){
                  utick=PositionGetInteger(POSITION_TICKET);
                  trade.PositionClose(utick);
               }
         }

         while(PositionsTotal() != 0);


This would work.

Reason: