Closing of several open positions

 
I have a program that is allowed to open several positions at a time. From time to time I want to close all open positions.

I use the following loop. It works, but the problem is that it takes several ticks to close them all. Shouldn't this loop in this example go through all open positions and close them all at the next incoming tick?

Help much appreciated.


//core of expert advisor:
int start()
{
static double Slippage=5;
static double ClosingProfit=999999; //just a high value to close everything in this example
int cnt, total;


//CLOSE POSITIONS
total=OrdersTotal();
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()==OP_BUY && // check for opened buy position
OrderSymbol()==Symbol()) // check for symbol
{
if(OrderProfit() < ClosingProfit)
{
OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Violet); // close position
}
}
}

total=OrdersTotal();
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()==OP_SELL && // check for opened sell position
OrderSymbol()==Symbol()) // check for symbol
{
if(OrderProfit() < ClosingProfit)
{
OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Violet); // close position
}
}
}

return(0);
}
// the end.
 
try the following:


    bool ok;

   ....

    ok= OrderClose(....);
    if (!ok)  {
        ErrorMessage("Close failed");
    }


....



//+------------------------------------------------------------------+
void ErrorMessage(string text)
{
   int err=GetLastError();
   Print("***********************************************************");
   Print("* ", text);
   Print("* ", ErrorDescription(err), " (", err, ")");
   Print("***********************************************************");

}




Output will be in the Experts tab of the terminal (real time trading) or Journal tab of the backtester.


Markus

 
thank you for the idea.

i am not sure why, but I have problems with that function you defined and the compiler won't accept it - can the void statement be anywhere in the program?

I did this instead:

{
ok=OrderClose(....); // close position
if (!ok) {Print("Close failed",": ",GetLastError());}
}

I hope this would do the same? I don't get any message from this.

The program closes the positions eventually, but in several packages, sometimes over 2-3 minutes.
 
your loop must be backward (!!!) - from end to start. i've told about it
for(cnt=OrdersTotal()-1; cnt>=0; cnt--)
 
Ah, sorry ... the function requires an

#include <stdlib.mqh>


somewhere near the top of the program.



Markus
 
your loop must be backward (!!!) - from end to start. i've told about it
for(cnt=OrdersTotal()-1; cnt>=0; cnt--)


Thank you !! works like a charm...
Reason: