//+------------------------------------------------------------------+
//|                                            Close and Reverse.mq4 |
//|                                      Copyright © 2006, Eli Hayun |
//|                                          http://www.elihayun.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2006, Eli Hayun"
#property link      "http://www.elihayun.com"

#property show_inputs

extern bool MirrorAllOrders = false;
extern bool MirrorAllLots = false;
extern int ReverseOrders = 1;
extern double ReverseLots = 1.0;

//+------------------------------------------------------------------+
//| Close the running orders and open to an opposite direction                                    |
//+------------------------------------------------------------------+
int start()
  {
//----
      string curr = Symbol();
      int ot = OrdersTotal();
      int ords[200], ordType[200], ordTicket[200]; double ordLots[200];
      string ordComments[200];
      int ix=0;
      for (int i=0; i<ot; i++)
      {
         int o = OrderSelect(i, SELECT_BY_POS);
         if (OrderSymbol() == Symbol())
            if ((OrderType() == OP_BUY) || (OrderType() == OP_SELL))
            {
               ords[ix] = o; ordType[ix] = OrderType(); 
               ordLots[ix] = OrderLots(); ordTicket[ix] = OrderTicket();
               ordComments[ix] = OrderComment();
               ix++;
            }
      }
      
      for (i=0; i<ix; i++)
      {
         
         double ask = MarketInfo(Symbol(), MODE_ASK);
         double bid = MarketInfo(Symbol(), MODE_BID);
         double prc = 0;
         
         if (ordType[i] == OP_BUY) prc = bid; else prc=ask;
         OrderSelect(ords[i], SELECT_BY_POS);
         Print("Closing Order # ",ords[i]);
         OrderClose(ordTicket[i], ordLots[i],prc,5);
         Print("Error ",GetLastError());
      }
      int lot = ReverseLots;
      int cnt = ReverseOrders;
      if(MirrorAllOrders) cnt = ix;
      for (i=0; i<cnt; i++)
      {
          ask = MarketInfo(Symbol(), MODE_ASK);
          bid = MarketInfo(Symbol(), MODE_BID);
          prc = 0;
         if(MirrorAllLots) lot = ordLots[i];
         int op = ordType[i]; if (op == OP_BUY) { op = OP_SELL; prc = bid;} else { op = OP_BUY; prc=ask;}
         OrderSend(Symbol(), op, lot, prc,5,0,0,ordComments[i]+"[Rev]"); 
      }
//----
   return(0);
  }
//+------------------------------------------------------------------+