How to close all open orders based on Magic number

michaelb
95
michaelb  

The following function will close ALL Open positions--

void closeAllPositions()
{
while(OrdersTotal()>0)
{
OrderSelect(0,SELECT_BY_POS);
if(OrderType()==OP_BUY)
OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),999,CLR_NONE);
if(OrderType()==OP_SELL)
OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),999,CLR_NONE);
}
return(0);
}

I need a function that will close ONLY the open positions that match a specific Magic number.

Thank you for your help.

Gordon Gekko
628
Gordon Gekko  
michaelB:

The following function will close ALL Open positions--

...

Here you are:

int CloseOrders(int Magic)
{
  int total  = OrdersTotal();
  
  for (int cnt = total-1 ; cnt >= 0 ; cnt--)
  {
    OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
    if (OrderMagicNumber() == Magic)
    {
      if (OrderType()==OP_BUY)
      {
        OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),3);
      }
      
      if (OrderType()==OP_SELL)
      {
        OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),3);
      }
    }
  }
  return(0);
}

You have to call this function.

Example:

Magic number is 1234.

CloseOrders(1234);

Generally:

CloseOrders(Magic);
Cheers
michaelb
95
michaelb  
ggekko wrote >>

Here you are:

You have to call this function.

Example:

Magic number is 1234.

Generally:

Cheers

ggekko-

another simple and clean solution.

Thank you.