Can't execute pending orders in expert advisor

 
Basically  I am a beginner at coding but I am working at EMA price crossover EA whereas 1. if price of current symbol crosses above ema ,an alert is triggered as well a buy stop pending order 2. if price of current symbol crosses below ema ,an alert is triggered as well a sell stop pending order. 3. offset parameters of the pending orders should be adjustable... I am able to compile the code but thte strategy tester will not let me backtest it or will not execute trades... Here is the code below and thank you in advance


//+------------------------------------------------------------------+

//|                                                      EA_Sample.mq5 |
//|                        Copyright 2021, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+

#property copyright "MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

// EMA period
input int InpEMAPeriod=14; 
// Risk parameters
input double LotSize = 0.1;
input double Offset = 2; // Offset in pips

// Global variable for the last bar
datetime lastBarTime;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   lastBarTime = iTime(Symbol(), 0, 0);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   MqlRates rates[];
   ArraySetAsSeries(rates, true);
   int copied = CopyRates(Symbol(), 0, 1, 2, rates);
   
   if(copied <= 0)
   {
       Print("Error in CopyRates: ", GetLastError());
       return;
   }
   
   // Check if a new bar has formed
   if (lastBarTime != rates[0].time)
   {
       lastBarTime = rates[0].time;
       
       double price = rates[0].close;
       double offset = Offset * _Point;
       int ma_handle = iMA(Symbol(), 0, InpEMAPeriod, 0, MODE_EMA, PRICE_CLOSE);
       
       if(ma_handle == INVALID_HANDLE)
       {
           Print("Error in iMA: ", GetLastError());
           return;
       }
       
       double ema[];
       int copied_ema = CopyBuffer(ma_handle, 0, 0, 1, ema);
       
       if(copied_ema <= 0)
       {
           Print("Error in CopyBuffer: ", GetLastError());
           return;
       }
       
       MqlTradeRequest request;
       MqlTradeResult result;
       
       ZeroMemory(request);
       request.symbol = Symbol();
       request.volume = LotSize;
       request.deviation = 3;
       request.magic = 12345;
       
       if (price > ema[0])
       {
           Alert("Price crossed above EMA");
           request.type = ORDER_TYPE_BUY_STOP;
           request.price = NormalizeDouble(price + offset, _Digits);
           if(!OrderSend(request, result))
           {
               PrintFormat("OrderSend error %d",GetLastError());
           }
       }
       else if (price < ema[0])
       {
           Alert("Price crossed below EMA");
           request.type = ORDER_TYPE_SELL_STOP;
           request.price = NormalizeDouble(price - offset, _Digits);
           if(!OrderSend(request, result))
           {
               PrintFormat("OrderSend error %d",GetLastError());
           }
       }
   }
  }
//+------------------------------------------------------------------+

 
  1. Please edit your (original) post and use the CODE button (or Alt+S)! (For large amounts of code, attach it.)
          General rules and best pratices of the Forum. - General - MQL5 programming forum #25 (2019)
              Messages Editor
          Forum rules and recommendations - General - MQL5 programming forum (2023)

  2. Perhaps you should read the manual, especially the examples.
       How To Ask Questions The Smart Way. (2004)
          How To Interpret Answers.
             RTFM and STFW: How To Tell You've Seriously Screwed Up.

    They all (including iCustom) return a handle (an int). You get that in OnInit. In OnTick/OnCalculate (after the indicator has updated its buffers), you use the handle, shift and count to get the data.
              Technical Indicators - Reference on algorithmic/automated trading language for MetaTrader 5
              Timeseries and Indicators Access / CopyBuffer - Reference on algorithmic/automated trading language for MetaTrader 5
              How to start with MQL5 - General - MQL5 programming forum - Page 3 #22 (2020)
              How to start with MQL5 - MetaTrader 5 - General - MQL5 programming forum - Page 7 #61 (2020)
              MQL5 for Newbies: Guide to Using Technical Indicators in Expert Advisors - MQL5 Articles (2010)
              How to call indicators in MQL5 - MQL5 Articles (2010)

 
Relax Zone:
Basically  I am a beginner at coding but I am working at EMA price crossover EA whereas 1. if price of current symbol crosses above ema ,an alert is triggered as well a buy stop pending order 2. if price of current symbol crosses below ema ,an alert is triggered as well a sell stop pending order. 3. offset parameters of the pending orders should be adjustable... I am able to compile the code but thte strategy tester will not let me backtest it or will not execute trades... Here is the code below and thank you in advance



Check if the order type ( ORDER_TYPE_BUY_STOP and ORDER_TYPE_SELL_STOP ) is compatible with the current market conditions. For example, if the market is already above the EMA, sending a BUY_STOP order will not be valid
 Make sure that the price calculated for the pending orders ( request.price ) is valid and within the acceptable range. If the calculated price is too far from the current market price, the broker may reject the order.
Consider the current spread and slippage settings. If the spread is too large or slippage is significant, it may affect the validity of pending orders.  Improve error handling to provide more detailed information about any errors that occur during order sending or processing.

Here are some adjustments i made for you

//+------------------------------------------------------------------+
//|                                                     EA_Sample fix.mq5 |
//|                        Copyright 2021, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+

#property copyright "MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

// EMA period
input int InpEMAPeriod=14; 
// Risk parameters
input double LotSize = 0.1;
input double Offset = 20; // Offset in points

// Global variable for the last bar
datetime lastBarTime;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    lastBarTime = TimeCurrent();
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    MqlRates rates[];
    ArraySetAsSeries(rates, true);
    int copied = CopyRates(Symbol(), 0, 0, 1, rates);
    
    if(copied <= 0)
    {
        Print("Error in CopyRates: ", GetLastError());
        return;
    }
    
    if (lastBarTime != rates[0].time)
    {
        lastBarTime = rates[0].time;
        
        double price = rates[0].close;
        double offset = Offset * _Point;
        int ma_handle = iMA(Symbol(), 0, InpEMAPeriod, 0, MODE_EMA, PRICE_CLOSE);
        
        if(ma_handle == INVALID_HANDLE)
        {
            Print("Error in iMA: ", GetLastError());
            return;
        }
        
        double ema[];
        int copied_ema = CopyBuffer(ma_handle, 0, 0, 1, ema);
        
        if(copied_ema <= 0)
        {
            Print("Error in CopyBuffer: ", GetLastError());
            return;
        }
        
        MqlTradeRequest request;
        MqlTradeResult result;
        
        ZeroMemory(request);
        request.symbol = Symbol();
        request.volume = LotSize;
        request.deviation = 3;
        request.magic = 12345;
        
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        double spread = ask - bid;
        
        if (price > ema[0])
        {
            if (Offset * _Point < spread)
            {
                Print("Offset too small compared to spread, adjustment recommended");
            }
            Alert("Price crossed above EMA");
            request.type = ORDER_TYPE_BUY_STOP;
            request.price = NormalizeDouble(bid + offset, _Digits);
            if(!OrderSend(request, result))
            {
                PrintFormat("OrderSend error %d",GetLastError());
            }
        }
        else if (price < ema[0])
        {
            if (Offset * _Point < spread)
            {
                Print("Offset too small compared to spread, adjustment recommended");
            }
            Alert("Price crossed below EMA");
            request.type = ORDER_TYPE_SELL_STOP;
            request.price = NormalizeDouble(ask - offset, _Digits);
            if(!OrderSend(request, result))
            {
                PrintFormat("OrderSend error %d",GetLastError());
            }
        }
    }
}
 
Nardus Van Staden #:
Here are some adjustments i made for you

Are these all the adjustments you wanted to add? How good do you think this code is?

 
Vladislav Boyko #:

Are these all the adjustments you wanted to add? How good do you think this code is?

It was a rhetorical question, I don’t even know why I asked. Probably because I wanted to draw your attention to this.

Forum on trading, automated trading systems and testing trading strategies

Can't execute pending orders in expert advisor

Nardus Van Staden, 2024.04.11 02:24

Here are some adjustments i made for you

//+------------------------------------------------------------------+
//|                                                     EA_Sample fix.mq5 |
//|                        Copyright 2021, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+

#property copyright "MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

// EMA period
input int InpEMAPeriod=14; 
// Risk parameters
input double LotSize = 0.1;
input double Offset = 20; // Offset in points

// Global variable for the last bar
datetime lastBarTime;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    lastBarTime = TimeCurrent();
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    MqlRates rates[];
    ArraySetAsSeries(rates, true);
    int copied = CopyRates(Symbol(), 0, 0, 1, rates);
    
    if(copied <= 0)
    {
        Print("Error in CopyRates: ", GetLastError());
        return;
    }
    
    if (lastBarTime != rates[0].time)
    {
        lastBarTime = rates[0].time;
        
        double price = rates[0].close;
        double offset = Offset * _Point;
        int ma_handle = iMA(Symbol(), 0, InpEMAPeriod, 0, MODE_EMA, PRICE_CLOSE);
        
        if(ma_handle == INVALID_HANDLE)
        {
            Print("Error in iMA: ", GetLastError());
            return;
        }
        
        double ema[];
        int copied_ema = CopyBuffer(ma_handle, 0, 0, 1, ema);
        
        if(copied_ema <= 0)
        {
            Print("Error in CopyBuffer: ", GetLastError());
            return;
        }
        
        MqlTradeRequest request;
        MqlTradeResult result;
        
        ZeroMemory(request);
        request.symbol = Symbol();
        request.volume = LotSize;
        request.deviation = 3;
        request.magic = 12345;
        
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        double spread = ask - bid;
        
        if (price > ema[0])
        {
            if (Offset * _Point < spread)
            {
                Print("Offset too small compared to spread, adjustment recommended");
            }
            Alert("Price crossed above EMA");
            request.type = ORDER_TYPE_BUY_STOP;
            request.price = NormalizeDouble(bid + offset, _Digits);
            if(!OrderSend(request, result))
            {
                PrintFormat("OrderSend error %d",GetLastError());
            }
        }
        else if (price < ema[0])
        {
            if (Offset * _Point < spread)
            {
                Print("Offset too small compared to spread, adjustment recommended");
            }
            Alert("Price crossed below EMA");
            request.type = ORDER_TYPE_SELL_STOP;
            request.price = NormalizeDouble(ask - offset, _Digits);
            if(!OrderSend(request, result))
            {
                PrintFormat("OrderSend error %d",GetLastError());
            }
        }
    }
}
        

I don't program in MQL5, but even I know that this is very bad.

 
Vladislav Boyko #:

It was a rhetorical question, I don’t even know why I asked. Probably because I wanted to draw your attention to this.

I don't program in MQL5, but even I know that this is very bad.

I don't think people should do all the work for everyone, i see no problem with his code. Have you compiled it to check for errors? Did you test its functionality before saying someone else's code is bad? Why don't you correct it then, hence you don't even code in mql5. I think we all are lucky that people out there are willing to help others. I suggest you learn mql5, and then correct others if they are wrong. 
 
Vladislav Boyko #:

It was a rhetorical question, I don’t even know why I asked. Probably because I wanted to draw your attention to this.

I don't program in MQL5, but even I know that this is very bad.

The highlighted code checks if ma_handle equals INVALID_HANDLE to determine if there was an error in calculating the moving average. If ma_handle is INVALID_HANDLE , it prints an error message using Print() and returns from the function. The error message printed using Print() includes the result of GetLastError() , which is intended to provide additional information about the error. what is the problem? Did you say you dont code in MQL5? But wants to correct a mistake? that makes nooo sense at all, even i know thats bad. There are other adjustments i can make to make the code much better, of course, but what is learnt from it? Nothing is without mistakes at first. Do you expect me to write everything over from scratch?
 
Peter005 #:
I don't think people should do all the work for everyone, i see no problem with his code. Have you compiled it to check for errors? Did you test its functionality before saying someone else's code is bad? Why don't you correct it then, hence you don't even code in mql5. I think we all are lucky that people out there are willing to help others. I suggest you learn mql5, and then correct others if they are wrong. 

No, he has not, he must be a troll or something

 
Nardus Van Staden #:
he must be a troll or something

Yes, you're right, it was something like a little trolling, sorry, I couldn't resist. I won't ask you questions anymore

 
Vladislav Boyko #:

Yes, you're right, it was something like a little trolling, sorry, I couldn't resist. I won't ask you questions anymore

Clearly, you state you dont code in mql5 but want to correct me, please, the floor is yours, write the code the correct way as you see fit. I gave you the explanation on how the section you highlighted works, the same section you claim is bad, and you are not a mql5 coder? so......do it better. Its not like i dont realise there are many things that can be done better with the code. Please compile it,and test it, come back and write it all over again, the correct way.  

 
Peter005 #:
I don't think people should do all the work for everyone, i see no problem with his code. Have you compiled it to check for errors? Did you test its functionality before saying someone else's code is bad? Why don't you correct it then, hence you don't even code in mql5. I think we all are lucky that people out there are willing to help others. I suggest you learn mql5, and then correct others if they are wrong. 

Are you a coder?

Reason: