My First EA - So Close!

 

After studying up on MQL4 for a few weeks, I decided to create my first EA. The principle is to look for a pin bar (hammer) to form within the trend (prices vs 20EMA) and buy on the open of a new bar with 2 pips to TP for each pip to SL. After some initial hiccups, I finally got the EA to compile...unfortunately it doesn't show any trades conducted in strategy tester.


Are there obvious issues with this code? I'm sure I'm missing something basic but another set of eyes can usually spot things better!


Thanks!


//+------------------------------------------------------------------+
//|                                 Price Action Pin Bar Trading.mq4 |
//|                      Copyright © 2011, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2011"
#property link      " "

//--- input parameters
extern int MA_Period=20;                                 // Period for MA
extern double Pct_Risk=1;                                // Risk % per trade
int
   New_Bar,                                              // Whether it is the first tick of a new bar
   Time_0,                                               // New bar beginning time
   Total;                                                // Amount of orders in window
string Symb;                                             // Symbol abbreviation
bool Work=true;                                          // EA will work

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
   return(0);
  }
  
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
   return(0);
  }
  
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
    double MA_value, Long_SL, Long_TP, Short_SL, Short_TP;           // variables for current MA value, SLs and TPs 
    
//----------------------------------------------------------------- Preliminary processing
   if(Bars < MA_Period)                       // Not enough bars
     {
      Alert("Not enough bars in the window. EA does not work.");
      return;                                   // Exit start()
     }
   if(Work==false)                              // Critical error
     {
      Alert("Critical error. EA does not work.");
      return;                                   // Exit start()
     }
     
//-------------- Orders Accounting   
   Symb=Symbol();                               // Security name
   Total=0;                                     // Amount of orders
   for(int i=1; i>=OrdersTotal(); i++)          // Loop through orders
     {
      if (OrderSelect(i-1,SELECT_BY_POS)==true) // If there is the next one
        {                                       // Analyzing orders:
         if (OrderSymbol()!=Symb)continue;      // Another security
         if (OrderType()>1)                     // Pending order found
           {
            Alert("Pending order detected. EA does not work.");
            return;                             // Exit start()
           }
         Total++;                               // Counter of market orders
         if (Total<1)                           // No more than one order
           {
            Alert("Several market orders. EA does not work.");
            return;                             // Exit start()
           }
         }
       }
      
//----------------------------------------------------------------------------- New bar? ------
   New_Bar=0;                                            // First zero out
   if (Time_0 != Time[0])                                // If the bar beginning time changed...
      {
      New_Bar= 1;                                        // Then there is a new bar
      Time_0 = Time[0];                                  // Remember the new bar beginning time
      } 
      
//----------------------------------------------------------------------------- Determining SL and TP------ 
      Long_SL=Open[0]-Low[1]+5*Point;                        // SL set 5 pips below pin bar low
      Long_TP=2*Long_SL;                                     // 2:1 RRR
      Short_SL=High[1]-Open[0]+5*Point;                      // SL set 5 pips above pin bar high
      Short_TP=2*Short_SL;                                   // 2:1 RRR
   
//----------------------------------------------------------------------------- Trade Entry ------   
       MA_value = iMA(NULL,0,MA_Period,0,MODE_EMA,PRICE_CLOSE,0);           //To determine current MA value
            
      if (PinBar()== 1 && New_Bar==1 && Open[0]>MA_value)                   // Buy Parameters: new bar, pin bar, and Price>20EMA
         {                  
         RefreshRates();                                                    // Refresh Market Info
         OrderSend(Symb,OP_BUY,Lots(),Ask,2,Long_SL,Long_TP);               // Send order with custom parameters for SL,TP and Lots
         }
      if (PinBar()== 2 && New_Bar==1 && Open[0]<MA_value)                   // Sell Parameters: new bar, pin barm and Price<20EMA
         {
         RefreshRates();                                                    // Refresh Market Info
         OrderSend(Symb,OP_SELL,Lots(),Bid,2,Short_SL,Short_TP);            // Send order with custom parameters for SL,TP and Lots
         }


   return(0);                                                              // Exit start()
  }
//+------------------------------------------------------------------+

//---- To determine if most recent bar is a pin bar.  0=no 1= bullish 2=bearish
  int PinBar()
      {
      double k = (High[1]-Low[1])/3;                                       // split range into 3rds
         if((Open[1]>(Low[1]+2*k))&&(Close[1]>(Low[1]+2*k)))               // if both open and close in top 3rd...
            {return(1);}                                                   // return bullish pin bar =1
         if((Open[1]<(High[1]-2*k))&&(Close[1]<(High[1]-2*k)))             // if both open and close in bottom 3rd...
            {return(2);}                                                   // return bearish pin bar =2
         else return(0);                                                   // else not a pin bar
      }
      
// ------------------------------------------------- To determine Lot Size
   double Lots()
      {
      double Lot = NormalizeDouble( AccountEquity()*Pct_Risk/100/1000, 1);  // Calculate the amount of lots  
      if (Lot<0.1)Lot = 0.1;                                                // For testing on const. min. lots
         return(Lot);
      }
 
  1.          Total++;                               // Counter of market orders
             if (Total<1)                           // No more than one order
               {
                Alert("Several market orders. EA does not work.");
                return;                             // Exit start()
               }
    
    The IF must be outside the FOR loop and you want (Total>1)
  2.    for(int i=1; i>=OrdersTotal(); i++)          // Loop through orders
         {
          if (OrderSelect(i-1,SELECT_BY_POS)==true) // If there is the next one
            {                                       // Analyzing orders:
             if (OrderSymbol()!=Symb)continue;
    I>=OrdersTotal means an infinite loop. You must count down for modify/close/delete in the presense of multiple orders (multiple charts) No check for magic number makes it incompatible with any other EA including itself on another chart. if(true==true) is redundant.
        for(pos = OrdersTotal()-1; pos >= 0 ; pos--) if (
            OrderSelect(pos, SELECT_BY_POS)                 // Only my orders w/
        &&  OrderMagicNumber()  == magic.number             // my magic number
        &&  OrderSymbol()       == Symbol() ){              // and my pair.
    

  3. New_Bar=0;
    You're using an int as a bool. Replace with bool New_Bar=false;
  4. Long_SL=Open[0]-Low[1]+5*Point;                        // SL set 5 pips below pin bar low
    5 points below the low is Low[1]-5*Point
  5. EA's must adjust for 4/5 digit brokers. The minimum SL is usually 3 pips (broker dependent.) On a 5 digit broker 5*point is 1/2 pip. Must modify TP, SL, AND slippage.
    //++++ These are adjusted for 5 digit brokers.
    int     pips2points;    // slippage  3 pips    3=points    30=points
    double  pips2dbl;       // Stoploss 15 pips    0.0015      0.00150
    int     Digits.pips;    // DoubleToStr(dbl/pips2dbl, Digits.pips)
    int     init(){
        if (Digits == 5 || Digits == 3){    // Adjust for five (5) digit brokers.
                    pips2dbl    = Point*10; pips2points = 10;   Digits.pips = 1;
        } else {    pips2dbl    = Point;    pips2points =  1;   Digits.pips = 0; }
        // OrderSend(... Slippage.Pips * pips2points, Bid - StopLossPips * pips2dbl
    
    On ECN brokers you must open the order and then set stops.
  6. OrderSend(Symb,OP_SELL,Lots(),Bid,2,Short_SL,Short_TP)
    Always test return codes
    int ticket=OrderSend(...
    if (ticket<0) Alert("OrderSend failed: ",GetLastError());

  7. double Lot = NormalizeDouble( AccountEquity()*Pct_Risk/100/1000, 1);  // Calculate the amount of lots  
    if (Lot<0.1)Lot = 0.1;  
    Assumes minlot is 0.1 and lotstep is also 0.1.
        double  minLot  = MarketInfo(Symbol(), MODE_MINLOT),
                lotStep = MarketInfo(Symbol(), MODE_LOTSTEP),
                size    = AccountEquity()*Pct_Risk/100/1000,
                Lot     = MathFloor(size/lotStep)*lotStep;
        if (Lot < minLot)  Lot = minLot;
    

Reason: