ORDERCLOSEBY Function

 
#property strict 
void  OnStart ()
  {
   int Ticket = 0 ;
   int Opposite = 0 ;

   for ( int i = OrdersTotal () - 1 ; i> = 0 ; i--)
     {
      // --- select item / order with index "i" 
      if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ) == true )
        {
         // --- select an open position for sale 
         if ( OrderType () == OP_SELL )
             // --- assign a unique ticket number to the 
            Ticket Ticket = OrderTicket ();

         // --- select an open position to buy 
         if ( OrderType () == OP_BUY )
             // --- assign a unique number to the Opposite variable (ticket) 
            Opposite = OrderTicket ();
        }
     }

// --- close two opposite positions 
   if ( OrderCloseBy (Ticket, Opposite) == true )
       Print ( "Close position" , Ticket, "i" , Opposite, "succeeded." );
   else 
      Print ( "Failed to close positions" , Ticket, "i" , Opposite,
             ". Error nr =" , GetLastError ());
  }
 
I added that code to my EA to close an existing trade when the opposite signal occurs and also take the trade in the opposite direction. The problem is that the code only the direction of the first signal it receives i.e. if the first signal is a sell, it will only take sell signals and vice versa. 
Reason: