My first EA MA Crossing

 

Hey Guys, 

 i have some programming knowledge so i thought i'd try to code my first own EA, i have an OrderClose Error 138 (yes i do know what it means) Issue tho in the part that i commented out, i just dont seem to find the Error though. Maybe someone of you guys will see it in a heartbeat so i thought i'd post it here.

 Its just a simple MA Crossing right now but i will develop it further later on when it works without any errors.

 

I was also trying to add a time filter so it does only trade from Start of London Session to the End of New York session but that also doesnt really work yet.

 

If you happen to find anything else that i should be doing different, feel free to let me know how i could do it better!

 

Here is my complete code:

 

extern int MA_short = 25;
extern int MA_medium = 60;
extern int MA_long = 100;
extern double MaxRisk = 0.03;
extern double TP = 160;
extern double SL = 40;
extern double PipValue = 0.10;
extern double Slippage = 10;
extern double MagicNumber = 12345;

extern int StartHour=6;
extern int EndHour=16;

bool TimeToTrade, NewCandleStart, LongSignal, ShortSignal;
datetime NewCandle;
int LongOrder, ShortOrder;
double Lots;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//---
     NewCandle = Time[0];  
//---
   return(INIT_SUCCEEDED);
  }
  
int start()
   {
   
      double MyPoint=Point;
        
      if(DayOfWeek() > 0 && DayOfWeek() < 6)
      {
         
         if(Digits==3 || Digits==5){ MyPoint=Point*10; }
         
         // Check if its the right time to trade
         
         if((TimeHour(TimeCurrent()))>=StartHour&&(TimeHour(TimeCurrent())<EndHour))
         {
            TimeToTrade = true;
         }
         else if((TimeHour(TimeCurrent())==EndHour))
         {          
            TimeToTrade = false;
         }
         
         
         if(TimeToTrade == true)
         {
            if(NewCandle != Time[0])
            {
               NewCandleStart = true;
               NewCandle = Time[0];
            }
            else
            {
               NewCandleStart = false;
            }
            
            // Indikatoren
            
            double MAlong = iMA(Symbol(), 0, MA_long, 0, MODE_EMA, PRICE_CLOSE, 1);
            double MAmedium = iMA(Symbol(), 0, MA_medium, 0, MODE_EMA, PRICE_CLOSE, 1);
            double MAshort = iMA(Symbol(), 0, MA_short, 0, MODE_EMA, PRICE_CLOSE, 1);
            
            double MAlongBefore = iMA(Symbol(), 0, MA_long, 0, MODE_EMA, PRICE_CLOSE, 2);
            double MAmediumBefore = iMA(Symbol(), 0, MA_medium, 0, MODE_EMA, PRICE_CLOSE, 2);
            double MAshortBefore = iMA(Symbol(), 0, MA_short, 0, MODE_EMA, PRICE_CLOSE, 2);
            
            Lots = (AccountEquity() * MaxRisk) / (SL * PipValue);
            
            // Order Signals
            
            if(NewCandleStart == true)
            {
               // Long Signal
               
               if(MAshort > MAlong && MAshortBefore <= MAlongBefore)
               {
                  LongSignal = true;
               }
               else
               {
                  LongSignal = false;
               }
               
                // Short Signal
                
               if(MAshort < MAlong && MAshortBefore >= MAlongBefore)
               {
                  ShortSignal = true;
               }
               else
               {
                  ShortSignal = false;
               } 
            }
            else
            {
               LongSignal = false;
               ShortSignal = false;
            }    
            
            // Long Order
            
            if(LongSignal == true)
            {
               // Close Short Order if exists
               
               if(ShortOrder > 0)
               {
                  if(OrderSelect(ShortOrder, SELECT_BY_TICKET) == true)
                  {
                     bool CloseShortOrder = OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, Blue); 
                     
                     if(CloseShortOrder == true)
                     {
                        ShortOrder = 0;
                     }
                  }
               }
            
               while(LongOrder <= 0)
               {
                  LongOrder = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, 0, 0, "LongOrder", MagicNumber, 0, Green);
               }
            }
            
            // Short Order
            
            if(ShortSignal == true)
            {
               if(LongOrder > 0)
               {
                  if(OrderSelect(LongOrder, SELECT_BY_TICKET) == true)
                  {
                     bool CloseLongOrder = OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, Blue); 
                     
                     if(CloseLongOrder == true)
                     {
                        LongOrder = 0;
                     }
                  }
               }

               while(ShortOrder <= 0)
               {
                  ShortOrder = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, 0, 0, "ShortOrder", MagicNumber, 0, Red);
               }
            }
            
            // Set StopLoss LongOrder
            
            if(OrderSelect(LongOrder, SELECT_BY_TICKET) == true)
            {
               if(OrderCloseTime() == 0 && OrderStopLoss() == 0)
               {
                  double StopLoss = NormalizeDouble(Ask-SL*MyPoint, Digits);
                  
                  bool EditLongSL = OrderModify(OrderTicket(), OrderOpenPrice(), StopLoss, OrderTakeProfit(), 0, Yellow);
               }
            }
            
            // Set StopLoss ShortOrder
            
            if(OrderSelect(ShortOrder, SELECT_BY_TICKET) == true)
            {
               if(OrderCloseTime() == 0 && OrderStopLoss() == 0)
               {
                  double StopLoss = NormalizeDouble(Bid+SL*MyPoint, Digits);
                  
                  bool EditShortSL = OrderModify(OrderTicket(), OrderOpenPrice(), StopLoss, OrderTakeProfit(), 0, Yellow);
               }
            }
            
            // Set TakeProfit Long Order
            
            if(OrderSelect(LongOrder, SELECT_BY_TICKET) == true)
            {
               if(OrderCloseTime() == 0 && OrderTakeProfit() == 0)
               {
                  double TakeProfit = NormalizeDouble(Ask+TP*MyPoint, Digits);
                  
                  bool EditLongTP = OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), TakeProfit, 0, Orange);
               }
            }
            
            // Set TakeProfit Short Order
            
            if(OrderSelect(ShortOrder, SELECT_BY_TICKET) == true)
            {
               if(OrderCloseTime() == 0 && OrderTakeProfit() == 0)
               {
                  double TakeProfit = NormalizeDouble(Bid-TP*MyPoint, Digits);
                  
                  bool EditShortTP = OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), TakeProfit, 0, Orange);
               }
            }      
         }
         /*else
         {
            // Close open Orders when Endhour is reached.            
            if(LongOrder > 0)
            {
               if(OrderSelect(LongOrder, SELECT_BY_TICKET) == true)
               {
                  bool CloseWrongTimeLongOrder = OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, CLR_NONE);
                  
                  if(CloseWrongTimeLongOrder == true)
                  {
                  
                     LongOrder = 0;
                     Print("Longorder closed @ ", TimeHour(TimeCurrent()));
                     
                  }
               }
            }
            
            if(ShortOrder > 0)
            {
               if(OrderSelect(ShortOrder, SELECT_BY_TICKET) == true)
               {
               
                  bool CloseWrongTimeShortOrder = OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, CLR_NONE);
                  
                  if(CloseWrongTimeShortOrder == true)
                  {
                     
                     ShortOrder = 0;
                     Print("Shortorder closed @ ", TimeHour(TimeCurrent()));
                  
                  }
               }
            }          
         }   */
      
         if(OrderSelect(LongOrder, SELECT_BY_TICKET) == true)
         {
            if(OrderTicket() > 0 && OrderCloseTime() > 0)
            {
               LongOrder = 0;
            }
         }
         
         if(OrderSelect(ShortOrder, SELECT_BY_TICKET) == true)
         {
            if(OrderTicket() > 0 && OrderCloseTime() > 0)
            {
               ShortOrder = 0;
            }
         }
      
      }
      
      return(0);
   }
 

Ratio_O:

 

I was also trying to add a time filter so it does only trade from Start of London Session to the End of New York session but that also doesnt really work yet.

To trade in between certain hours I just use this:

if((Hour()>=StartTimeMA && Hour()<=FinishTimeMA))  //Preferred trading hours
      {

      }
 

Hey, thanks for your reply. 

  The bigger problem is the OrderClose Error 138 and as you can see in my code, i have already done something like what you suggested, i just changed it from Hour() to TimeHour(TimeCurrent()) for testing purposes, it doesn't work in both versions though.

 
  1. Your code
    Simplified
    if(MAshort > MAlong && MAshortBefore <= MAlongBefore)
    {
       LongSignal = true;
    }
    else
    {
       LongSignal = false;
    }
    LongSignal = (MAshort > MAlong && MAshortBefore <= MAlongBefore);
    

  2. if(OrderSelect(LongOrder, SELECT_BY_TICKET) == true)
    You would never write if( (2+2 == 4) == true) would you? if(2+2 == 4) is sufficient. So Don't write if(bool == true), just use if(bool) or if(!bool). Code becomes self documenting when you use meaningful variable names, like bool isLongEnabled. Long_Entry sounds like a trigger price or a ticket number and "if long entry" is an incomplete sentence.
  3.  if(OrderTicket() > 0 && OrderCloseTime() > 0)
    ticket numbers can never be negative. redundant test.
  4.  if(LongOrder > 0){
       if(OrderSelect(LongOrder, SELECT_BY_TICKET) == true){
         bool CloseWrongTimeLongOrder = OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, CLR_NONE);
    You open a buy at the Ask and close at the Bid. You open a sell at the Bid and close at the Ask. You can be direction independent by using OrderClosePrice().
 
WHRoeder:
  1. Your code
    Simplified

  2. You would never write if( (2+2 == 4) == true) would you? if(2+2 == 4) is sufficient. So Don't write if(bool == true), just use if(bool) or if(!bool). Code becomes self documenting when you use meaningful variable names, like bool isLongEnabled. Long_Entry sounds like a trigger price or a ticket number and "if long entry" is an incomplete sentence.
  3. ticket numbers can never be negative. redundant test.
  4. You open a buy at the Ask and close at the Bid. You open a sell at the Bid and close at the Ask. You can be direction independent by using OrderClosePrice().
Hey, thank you very much for your reply, i will implement your suggested changes and let you know how it worked out!
 
WHRoederYou can be direction independent by using OrderClosePrice().

Could you maybe give me an example like you did it for the simplified if code? Other than that it is working perfectly now.

This is the updated code:

extern int MA_short = 25;
extern int MA_medium = 60;
extern int MA_long = 100;
extern double MaxRisk = 0.03;
extern double TP = 80;
extern double SL = 20;
extern double PipValue = 0.10;
extern double Slippage = 10;
extern double MagicNumber = 12345;

extern int StartHour=10;
extern int EndHour=23;

bool TimeToTrade, NewCandleStart, LongSignal, ShortSignal;
datetime NewCandle;
int LongOrder, ShortOrder;
double Lots;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//---
     NewCandle = Time[0];  
//---
   return(INIT_SUCCEEDED);
  }
  
int start()
   {
   
      double MyPoint=Point;
        
      if(DayOfWeek() > 0 && DayOfWeek() < 6)
      {
         
         if(Digits==3 || Digits==5){ MyPoint=Point*10; }
         
         // Check if its the right time to trade
         
         if((TimeHour(TimeCurrent()))>=StartHour&&(TimeHour(TimeCurrent())<EndHour))
         {
            TimeToTrade = true;
         }
         else if((TimeHour(TimeCurrent())==EndHour))
         {          
            TimeToTrade = false;
         }
         
         
         if(TimeToTrade)
         {
            if(NewCandle != Time[0])
            {
               NewCandleStart = true;
               NewCandle = Time[0];
            }
            else
            {
               NewCandleStart = false;
            }
            
            // Indikatoren
            
            double MAlong = iMA(Symbol(), 0, MA_long, 0, MODE_EMA, PRICE_CLOSE, 1);
            double MAmedium = iMA(Symbol(), 0, MA_medium, 0, MODE_EMA, PRICE_CLOSE, 1);
            double MAshort = iMA(Symbol(), 0, MA_short, 0, MODE_EMA, PRICE_CLOSE, 1);
            
            double MAlongBefore = iMA(Symbol(), 0, MA_long, 0, MODE_EMA, PRICE_CLOSE, 2);
            double MAmediumBefore = iMA(Symbol(), 0, MA_medium, 0, MODE_EMA, PRICE_CLOSE, 2);
            double MAshortBefore = iMA(Symbol(), 0, MA_short, 0, MODE_EMA, PRICE_CLOSE, 2);
            
            Lots = (AccountEquity() * MaxRisk) / (SL * PipValue);
            
            // Order Signals
            
            if(NewCandleStart)
            {
               // Long Signal
               
               LongSignal = (MAshort > MAlong && MAshortBefore <= MAlongBefore);
               
                // Short Signal
                
               ShortSignal = (MAshort < MAlong && MAshortBefore >= MAlongBefore);    
            }
            else
            {
               LongSignal = false;
               ShortSignal = false;
            }    
            
            // Long Order
            
            if(LongSignal)
            {
               // Close Short Order if exists
               
               if(ShortOrder > 0)
               {
                  if(OrderSelect(ShortOrder, SELECT_BY_TICKET))
                  {
                     bool CloseShortOrder = OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, Blue); 
                     
                     if(CloseShortOrder)
                     {
                        ShortOrder = 0;
                     }
                  }
               }
            
               while(LongOrder <= 0)
               {
                  LongOrder = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, 0, 0, "LongOrder", MagicNumber, 0, Green);
               }
            }
            
            // Short Order
            
            if(ShortSignal)
            {
               if(LongOrder > 0)
               {
                  if(OrderSelect(LongOrder, SELECT_BY_TICKET))
                  {
                     bool CloseLongOrder = OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, Blue); 
                     
                     if(CloseLongOrder)
                     {
                        LongOrder = 0;
                     }
                  }
               }

               while(ShortOrder <= 0)
               {
                  ShortOrder = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, 0, 0, "ShortOrder", MagicNumber, 0, Red);
               }
            }
            
            // Set StopLoss LongOrder
            
            if(OrderSelect(LongOrder, SELECT_BY_TICKET))
            {
               if(OrderCloseTime() == 0 && OrderStopLoss() == 0)
               {
                  double StopLoss = NormalizeDouble(Ask-SL*MyPoint, Digits);
                  
                  bool EditLongSL = OrderModify(OrderTicket(), OrderOpenPrice(), StopLoss, OrderTakeProfit(), 0, Yellow);
               }
            }
            
            // Set StopLoss ShortOrder
            
            if(OrderSelect(ShortOrder, SELECT_BY_TICKET))
            {
               if(OrderCloseTime() == 0 && OrderStopLoss() == 0)
               {
                  double StopLoss = NormalizeDouble(Bid+SL*MyPoint, Digits);
                  
                  bool EditShortSL = OrderModify(OrderTicket(), OrderOpenPrice(), StopLoss, OrderTakeProfit(), 0, Yellow);
               }
            }
            
            // Set TakeProfit Long Order
            
            if(OrderSelect(LongOrder, SELECT_BY_TICKET))
            {
               if(OrderCloseTime() == 0 && OrderTakeProfit() == 0)
               {
                  double TakeProfit = NormalizeDouble(Ask+TP*MyPoint, Digits);
                  
                  bool EditLongTP = OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), TakeProfit, 0, Orange);
               }
            }
            
            // Set TakeProfit Short Order
            
            if(OrderSelect(ShortOrder, SELECT_BY_TICKET))
            {
               if(OrderCloseTime() == 0 && OrderTakeProfit() == 0)
               {
                  double TakeProfit = NormalizeDouble(Bid-TP*MyPoint, Digits);
                  
                  bool EditShortTP = OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), TakeProfit, 0, Orange);
               }
            }      
         }
         else
         {
            if(LongOrder > 0)
            {
               if(OrderSelect(LongOrder, SELECT_BY_TICKET))
               {
                  bool CloseWrongTimeLongOrder = OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, CLR_NONE);
                  
                  if(CloseWrongTimeLongOrder)
                  {
                  
                     LongOrder = 0;
                     Print("Longorder closed @ ", TimeHour(TimeCurrent()));
                     
                  }
               }
            }
            
            if(ShortOrder > 0)
            {
               if(OrderSelect(ShortOrder, SELECT_BY_TICKET))
               {
               
                  bool CloseWrongTimeShortOrder = OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, CLR_NONE);
                  
                  if(CloseWrongTimeShortOrder)
                  {
                     
                     ShortOrder = 0;
                     Print("Shortorder closed @ ", TimeHour(TimeCurrent()));
                  
                  }
               }
            }          
         }   
      
         if(OrderSelect(LongOrder, SELECT_BY_TICKET))
         {
            if(OrderCloseTime() > 0)
            {
               LongOrder = 0;
            }
         }
         
         if(OrderSelect(ShortOrder, SELECT_BY_TICKET))
         {
            if(OrderCloseTime() > 0)
            {
               ShortOrder = 0;
            }
         }
      
      }
      
      return(0);
   }

 

Are there any other things you would suggest me to do differently? 

 
Ratio_O: Could you maybe give me an example like you did it for the simplified if code?

bool CloseWrongTimeLongOrder = OrderClose(OrderTicket(), OrderLots(), Bid,               Slippage, CLR_NONE);
bool CloseWrongTimeLongOrder = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), Slippage, CLR_NONE);
 
Any idea how i can prevent it from opening a trade at 22:55 when it gets automatically closed at 23:00?