Can't execute pending orders in expert advisor - page 2

 
Nardus Van Staden #:

Are you a coder?

I'm learning still but i do code in both mql4 and 5. I do see other problems in the code however, but nothing u did wrong, its coming from the original code. I just think people are a bit too narly with one another, the sun shines over all of us, and we shouldn't bad mouth one another, but rather lead by example. If someone else sees a wrong  and knows how to correct it, they shouldn't keep quiet, they should show how its done. But only if they know how. Your explanation about the highlighted part is correct and well structured, there will always be people that don't agree with everything you do, they have their ways, and you have yours. I compiled the code, and it has no errors or warnings  i executed the code and seems to work just fine. I'm however not sure about what it will do in future, but that is not my doing. The code could have been written better, but that will be done by the author in time as they learn. 
 
Nardus Van Staden #:

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

Thank you very much sir! I will definitely work on improving my coding , this was basically my first code, from a trade idea I would like to try.. Thanks again :)

 
Nardus Van Staden #:

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

When I try to use the strategy tester, the EA is not able to open trades, it gives erros such as 

"2024.04.11 11:53:22.335 2024.01.04 13:45:00   OrderSend error 4756

2024.04.11 11:53:22.374 2024.01.04 13:50:00   Alert: Price crossed below EMA

2024.04.11 11:53:22.374 2024.01.04 13:50:00   failed prices for EURUSD 0.1 [Invalid request]

2024.04.11 11:53:22.374 2024.01.04 13:50:00   OrderSend error 4756

2024.04.11 11:53:22.410 2024.01.04 13:55:00   Alert: Price crossed below EMA

2024.04.11 11:53:22.410 2024.01.04 13:55:00   failed prices for EURUSD 0.1 [Invalid request]

2024.04.11 11:53:22.410 2024.01.04 13:55:00   OrderSend error 4756

2024.04.11 11:53:22.490 2024.01.04 14:00:00   Alert: Price crossed below EMA

2024.04.11 11:53:22.490 2024.01.04 14:00:00   failed prices for EURUSD 0.1 [Invalid request]

2024.04.11 11:53:22.490 2024.01.04 14:00:00   OrderSend error 4756"


I don't understand where the problem still is


 
Relax Zone #:

When I try to use the strategy tester, the EA is not able to open trades, it gives erros such as 

"2024.04.11 11:53:22.335 2024.01.04 13:45:00   OrderSend error 4756

2024.04.11 11:53:22.374 2024.01.04 13:50:00   Alert: Price crossed below EMA

2024.04.11 11:53:22.374 2024.01.04 13:50:00   failed prices for EURUSD 0.1 [Invalid request]

2024.04.11 11:53:22.374 2024.01.04 13:50:00   OrderSend error 4756

2024.04.11 11:53:22.410 2024.01.04 13:55:00   Alert: Price crossed below EMA

2024.04.11 11:53:22.410 2024.01.04 13:55:00   failed prices for EURUSD 0.1 [Invalid request]

2024.04.11 11:53:22.410 2024.01.04 13:55:00   OrderSend error 4756

2024.04.11 11:53:22.490 2024.01.04 14:00:00   Alert: Price crossed below EMA

2024.04.11 11:53:22.490 2024.01.04 14:00:00   failed prices for EURUSD 0.1 [Invalid request

2024.04.11 11:53:22.490 2024.01.04 14:00:00   OrderSend error 4756"


I don't understand where the problem still is


Yes, you are right, even though it compiles without errors, you will still encounter such errors as there are multiple fixes that needs to be done in your code. This would take way more time to fix. I would suggest that you work through it, as its the best way to learn. look at the (request.price), (request.deviation), NormalizeDouble, SymbolInfoDouble, and your arrays[]

 
Nardus Van Staden #:

Yes, you are right, even though it compiles without errors, you will still encounter such errors as there are multiple fixes that needs to be done in your code. This would take way more time to fix. I would suggest that you work through it, as its the best way to learn. look at the (request.price), (request.deviation), NormalizeDouble, SymbolInfoDouble, and your arrays[]

Hello again, after working through the the code I was able to make it execute trades. The only pronlem is that it's not opening only one trade per bar close, but it's opening multiple orders after the condition has been met. Here is the updated code: 

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

//|                                                     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.01;

input double Offset = 20; // Offset in points


// Global variable for the last bar

datetime lastBarTime;



datetime openTimeBuy = 0;

datetime openTimeSell =0;

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

//| 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.action   =TRADE_ACTION_PENDING;                             // type of trade operation

        request.symbol = Symbol();

        request.volume = LotSize;

        request.deviation = 2;

        request.magic = 12345;

        double point=SymbolInfoDouble(_Symbol,SYMBOL_POINT);                // value of point

        int digits=SymbolInfoInteger(_Symbol,SYMBOL_DIGITS);                // number of decimal places (precision)                                                   

        

        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;

            price        =SymbolInfoDouble(Symbol(),SYMBOL_ASK)+Offset*point; // price for opening 

            request.price=NormalizeDouble(price,digits);                      // normalized opening price;

            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;

            price        =SymbolInfoDouble(Symbol(),SYMBOL_BID)-Offset*point; // price for opening 

            request.price=NormalizeDouble(price,digits);                      // normalized opening price

            if(!OrderSend(request, result))

            {

                PrintFormat("OrderSend error %d",GetLastError());

            }

        }

    }

}
Discover new MetaTrader 5 opportunities with MQL5 community and services
Discover new MetaTrader 5 opportunities with MQL5 community and services
  • 2024.04.11
  • www.mql5.com
MQL5: language of trade strategies built-in the MetaTrader 5 Trading Platform, allows writing your own trading robots, technical indicators, scripts and libraries of functions
 
Relax Zone #:

Hello again, after working through the the code I was able to make it execute trades. The only pronlem is that it's not opening only one trade per bar close, but it's opening multiple orders after the condition has been met. Here is the updated code: 

When you post code please use the Code button (Alt+S) !

Improperly formatted code removed by moderator. Please EDIT your post and use the CODE button (Alt-S) when inserting code.

Code button in editor

Hover your mouse over your post and select "edit" ... 

Reason: