//+------------------------------------------------------------------+
//|                                                TestMultipair.mq4 |
//|                             	                 Paul Hampton-Smith |
//+------------------------------------------------------------------+

// This EA is a TEST ONLY to highlight an MT4 flaw when backtesting multipair EAs.
// If you backtest it against GBPUSD 1H it appears to be insanely profitable on build 198 of MT4,
// but this is because MT4 supplies the future Close[0] of EURUSD throughout each 1H bar rather than the
// Bid price at that instant of time.

int start()
{
	static datetime prevtime=0;
   
//---- Продолжим работу только если новый БАР
	if(prevtime == Time[0]) return(0);
	prevtime = Time[0];

	// the simplest buy/sell crieria I could think of to highlight the issue: 
	// buy GBP if the current EUR 1H bar is up
	bool bBuy = iClose("EURUSD",PERIOD_H1,0) > iOpen("EURUSD",PERIOD_H1,0);
	// sell GBP if the current EUR 1H bar is down
	bool bSell = iClose("EURUSD",PERIOD_H1,0) < iOpen("EURUSD",PERIOD_H1,0);

	if (OpenOrders() > 0)
	{
		if (bBuy) CloseOrders(OP_SELL);
		if (bSell) CloseOrders(OP_BUY);
	}

	if (OpenOrders() == 0)
	{
		if (bBuy) OrderSend(Symbol(), OP_BUY, 0.2, Ask, 2, 0, 0);
		if (bSell) OrderSend(Symbol(), OP_SELL, 0.2, Bid, 2, 0, 0);
	}
}

int OpenOrders()
{
   int nCount = 0;
   for ( int nPosition=0 ; nPosition<OrdersTotal() ; nPosition++ )
   {
      OrderSelect(nPosition, SELECT_BY_POS, MODE_TRADES);
      if ( OrderSymbol()==Symbol() && ( OrderType() == OP_BUY || OrderType() == OP_SELL ))
      {
         nCount++;
      }
   }
   return(nCount);
}

void CloseOrders(int type)
{
   for ( int nPosition=0 ; nPosition<OrdersTotal() ; )
   {
      OrderSelect(nPosition, SELECT_BY_POS, MODE_TRADES);
      if (OrderSymbol()==Symbol() && OrderType() == type)
      {
      	switch(OrderType())
      	{
      	case OP_BUY: OrderClose(OrderTicket(), OrderLots(), Bid, 2, Purple); break;
      	case OP_SELL: OrderClose(OrderTicket(), OrderLots(), Ask, 25, Purple); break;
      	}
      }
      else
      {
         nPosition++;
         //---- wait for 10 seconds
      }
      Sleep(10000);
   }
}

