This function will close All open trades for a particual MagicNumber of EA.

Code:
void CloseAll()
{
  int total = OrdersTotal();
  for(int i=total-1;i>=0;i--)
  {
    OrderSelect(i, SELECT_BY_POS);
    int type = OrderType();
    
    if (OrderSymbol()==Symbol() && (OrderMagicNumber() == MagicNumber))  
    {
      //-- Close open BUYs
      if (type == OP_BUY) OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),Slippage,CornflowerBlue);
      //-- Close open SELLS
      if (type == OP_SELL) OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),Slippage,CornflowerBlue);
    }
  }
  return;
}