//+------------------------------------------------------------------+
//|                                                  MACD Sample.mq4 |
//|                      Copyright © 2005, MetaQuotes Software Corp. |
//|                                       http://www.metaquotes.net/ |
//+------------------------------------------------------------------+

extern int SystemMagicNumber = 100;
extern int StopLoss = 100;
extern int TakeProfit = 100;
extern double Lots = 0.1;

int start() 
{
  int cnt, total;
  double ma5, ma30;
  double mStop, mTake;

  ma5 = iMA(NULL,0,5, 0,MODE_EMA, PRICE_CLOSE, 0);
  ma30 = iMA(NULL,0,30, 0,MODE_EMA, PRICE_CLOSE, 0);
  total=OrdersTotal();
  if(total<1)
  { 
     if( ma5 < ma30 ) 
     {
        if (StopLoss > 0) mStop = Bid+StopLoss* Point; else mStop = 0;
        if (TakeProfit > 0) mTake = Bid- TakeProfit* Point; else mTake = 0; 
        OrderSend(Symbol( ),OP_SELL, Lots,Bid, 3 * Point,mStop,mTake,"", SystemMagicNumber,0,Red);     
        return(0); 
     } 
    
     if( ma5 > ma30) 
     { 
        if (StopLoss > 0) mStop = Ask - StopLoss* Point; else mStop = 0;
        if (TakeProfit > 0) mTake = Ask + TakeProfit* Point; else mTake = 0; 
        OrderSend(Symbol( ),OP_BUY, Lots,Ask, 3 * Point,mStop,mTake,"", SystemMagicNumber,0,Blue) ; 
        return(0); 
     }
     return(0);
   }
   
   for(cnt=total - 1;cnt >= 0;cnt--)
   {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if ( OrderSymbol()==Symbol() && OrderMagicNumber() == SystemMagicNumber)  // check for symbol and magic number
      {
          if (OrderType() ==OP_SELL) 
          {          
             if (ma5>ma30) 
             { 
                OrderClose(OrderTicket(), OrderLots(),Ask,3* Point, Red) ;       
               
             } 
          } 
    
          if (OrderType() ==OP_BUY) 
          { 
            if (ma5<ma30) 
            { 
              OrderClose(OrderTicket(), OrderLots(),Bid,3* Point, Blue) ; 
            }      
               
          } 
      }
   }
} 
    

