Monday 22 August 2011

MQL4 Trailing Stop and Exit

The standard MT4 Platform is usually supplied with an example Expert Advisor called "Moving Average.mq4" Within this script is a function called CheckForClose() This function can be expaned upon to deal with trailing stops &/or exits. This particlar code block uses the Magic number parameter to select the correct order. Just call the function TrailingStops() from within the start loop.
 #define MAGIC 20110725  
 // or get this from  
 // extern int EA_Unique_No = 444888;  
 extern int TrailingStop = 400; // as in 40 pips for 5 Digit broker

 //+------------------------------------------------------------------+  
 //| Check for Exits / Trailing Stops                |  
 //+------------------------------------------------------------------+  
 void TrailingStop()  
 {  
   //---- go trading only for first tiks of new bar  
   if(Volume[0]>1) return;  
   //----  
   for(int i=0;i<OrdersTotal();i++)  
   {  
    if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)    break;  
    if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;  
    //---- check order type  
    if(OrderType()==OP_BUY)  
    {  
      // orig  
      //if(Open[1]>ma && Close[1]<ma) OrderClose(OrderTicket(),OrderLots(),Bid,3,White);  
      //break;  
      // Check for trailing stop  
      if(TrailingStop > 0)  
      {  
       if(Bid-OrderOpenPrice() > Point*TrailingStop)  
       {  
         if(OrderStopLoss() < Bid-Point*TrailingStop)  
         {  
          OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);  
          return(0);  
         }  
       }  
      }  
    } // /if buy  
    if(OrderType()==OP_SELL)  
    {  
      // Check for trailing stop  
      if(TrailingStop > 0)  
      {  
       if((OrderOpenPrice()-Ask) > (Point*TrailingStop))  
       {  
         if((OrderStopLoss() > (Ask+Point*TrailingStop)) || (OrderStopLoss()==0))  
         {  
          OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);  
          return(0);  
         }  
       }  
      }       
    }  
   }  
   //----  
 }  

No comments:

Post a Comment