HTH - Stupid code bug in MQL5 EA fixed after hours :)

 

I just want to share this, in case others struggle with OrderSend(request, result) ... like I did today. 
Wrote a little EA that helps setting limit, stop and market orders by calculating lot sizes on given stop level. 
Everything worked fine besides the market orders ORDER_TYPE_BUY, ORDER_TYPE_SELL.
Debugging of the result object didn't help either "invalid request", return code 10013. 

Well, I could see that for myself, that the request obviously was invalid :) 

I checked all parameters, sl, tp, open price, trade action, order type, deviation ... 

Funny thing, when using the one-click trading button in MT5 and providing the exact same values for lot size, entry price, sl and tp, the order was successful.

here is the basic code: 

      // for long position      
      openPrice = NormalizeDouble(SymbolInfoDouble(Symbol(),SYMBOL_ASK), Digits());
      orderType = ORDER_TYPE_BUY;
      action = TRADE_ACTION_DEAL;
      
      // for shorts
      openPrice = NormalizeDouble(SymbolInfoDouble(Symbol(),SYMBOL_BID), Digits());
      orderType = ORDER_TYPE_SELL;
      action = TRADE_ACTION_DEAL;

    // sl, tp caluclation here
     // ...
    // 
    ulong ticket;
    MqlTradeRequest request; // this was the issue
    MqlTradeResult result;       // and this was the issue
    request.action = action;
    request.type = orderType;
    request.symbol = Symbol();
    request.volume = lotSize;
    request.type_filling = ORDER_FILLING_IOC; // tried ORDER_FILLING_FOK as well 
    request.price = openPrice;
    request.sl = sl;
    request.tp = tp;
    if (orderType == ORDER_TYPE_BUY || orderType == ORDER_TYPE_SELL) {
      request.deviation = 200; // tried 0 as well
    } else {
      request.deviation = 0; 
    }
    if (!OrderSend(request, result)) {
      Print("Error sending order: ", GetLastError(), 
        "   retcode:  ", result.retcode, 
        "   retcode_external:  ", result.retcode_external, 
        "   comment:  ", result.comment
        ); 
      return;
    } else {
      ticket = result.order;
    } 

... always same error with market orders only, as described above.

This was the fix: (unbelievable)

// default initialization for both objects did the trick
MqlTradeRequest request = {};
MqlTradeResult result = {};

HTH

 
Christian Anton Schluessel:


i remember threads demonstrating this exact same issue. i thought the devs would have fixed this by now.
 
Michael Charles Schefe #:
i remember threads demonstrating this exact same issue. i thought the devs would have fixed this by now.

well, normally a good programming practice is to initialize your variables/objects, so the bug was well deserved :)

I would assume that internally uninialized fields in the structs lead to exceptions when executing the request. 
That might as well be the reason why the return code, respectively comment is so vague. 
Would be something like a NullpointerException in Java 

 
Christian Anton Schluessel #:

well, normally a good programming practice is to initialize your variables/objects, so the bug was well deserved :)

I would assume that internally uninialized fields in the structs lead to exceptions when executing the request. 
That might as well be the reason why the return code, respectively comment is so vague. 
Would be something like a NullpointerException in Java 

agreed. here's a closely related issue. you may be interested in the comment in this thread following the one above also.

Forum on trading, automated trading systems and testing trading strategies

can not open market order on MT5 demo account

phi nuts, 2013.01.21 13:55

Forgot nulling the structure ;(

     MqlTradeRequest request   = {0}; // nulling MqlTradeRequest structure
     MqlTradeResult result     = {0}; // nulling MqlTradeResult structure
     MqlTradeCheckResult check = {0}; // nulling MqlTradeCheckResult structure

If you like , you also may add deviation, since AlpariUK is using fractional pips.

     request.price  = latest_price.bid;       //--- get the bid price (did Wahoo, achidayat, and tuoitrecuoi tell you so ?)
     request.sl           = 0;                   // sl ==>> we add sl later or using limit pending order as sl           
     request.tp           = 0;                   // tp ==>> we add tp later or using stop pending order as tp 
     request.deviation    = 10;                  // change the slippage from 2 to 10

 

Why not use the Trade library? This code is fully abstracted in the framework.

If you read through Trade.mqh, all of this code is done already.


It is as simple as this to create a sell order:

#include <Trade\Trade.mqh>

datetime lastTradeTime = 0;

void OnTick(){  

   datetime barOpenTime = iTime(_Symbol, 0, 0);

    if(trade.Sell(lot_size, _Symbol, entry_price, sl, tp))
      {
          lastTradeTime = barOpenTime;

          Print("Sell order placed: Ticket=", trade.ResultDeal(), " Lot=", lot_size, " SL=", sl, " TP=", tp);
       }
     else
       {
          Print("Sell order failed: Error=", trade.ResultRetcode());
       }

}


There's no need to rewrite the request structure, and there's clean logic inside Trade.mqh to automatically source the correct filling type for the underlying broker.

 
Michael Charles Schefe #:

agreed. here's a closely related issue. you may be interested in the comment in this thread following the one above also.


MqlTradeRequest request   = {0};

I actually tried that approach, because I had seen it in other posts but that threw this compiler error:

cannot convert 0 to enum 'ENUM_TRADE_REQUEST_ACTIONS'   CSTradeMakerV3.mq5      687     30

 so I removed the initialization in total again :) 
Seems you have to provide all default values and with their correct types.

 
Conor Mcnamara #:
Trade.mqh

yeah, man, this is definitely the correct approach :) 

I''m not that experienced with mql5 and thus not fully aware of the API. 

Just for completeness and for others that might read here. 
The object declaration is missing in your example: 

#include <Trade\Trade.mqh>
CTrade trade;  // declare the object

thanks anyway ... I will update my code
 

 
Christian Anton Schluessel #:

yeah, man, this is definitely the correct approach :) 

I''m not that experienced with mql5 and thus not fully aware of the API. 

Just for completeness and for others that might read here. 
The object declaration is missing in your example: 

thanks anyway ... I will update my code
 

here's also a simple fully working EA example someone else published

Code Base

Simple EMA Cross EA with SL/TP and Magic Number

Edgar Alexis Benitez, 2026.06.19 01:20

A simple Expert Advisor based on the crossover of two EMAs (fast and slow), with configurable Stop Loss, Take Profit, lot size, and Magic Number.

 
Conor Mcnamara #:

here's also a simple fully working EA example someone else published


Thanks, but pointing me towards the API already solved my issues. Anyways, this should be the only accepted way as it eliminates the problems a lot of people seem to have with filling type and deviation when using MqlTradeRequest. At least what I could see from the many posts I've read.