Complete MQL5 guide & code

MQL5 OrderSend Guide: MqlTradeRequest, Return Codes & Execution Code

Complete guide to the MQL5 OrderSend function. Learn how to configure MqlTradeRequest and MqlTradeResult structures, manage filling policies, inspect return codes, and distinguish a checked request, accepted order and completed deal.

What this MQL5 guide covers

OrderSend is the fundamental MetaTrader 5 API function for executing market deals, placing pending orders, and modifying stops.

Initialize request structures explicitly, using an empty initializer or ZeroMemory, before setting the fields required by the action.

Choose filling policy using both symbol flags and execution mode; a valid filling choice does not validate all other order fields.

Inspect result.retcode in context: DONE means the request completed, PLACED means an order was placed, and DONE_PARTIAL means only part was completed. Reconcile actual deals and positions.

OrderSend Function Signature and Struct Parameters

Unlike MetaTrader 4 where OrderSend accepted a long list of positional arguments, MQL5 uses structured parameters: bool OrderSend(const MqlTradeRequest &request, MqlTradeResult &result).

Required fields vary with the action and execution mode. A stop modification has a different contract from opening a position.

MqlTradeRequest FieldTypeDescription
actionENUM_TRADE_REQUEST_ACTIONSTrade action: TRADE_ACTION_DEAL (market), TRADE_ACTION_PENDING, TRADE_ACTION_SLTP
magiculongUser-assigned request identifier; not a guarantee of isolated position ownership
symbolstringFinancial instrument name (e.g. "EURUSD", "XAUUSD")
volumedoubleTrade volume in lots (must adhere to volume min, max, and step)
pricedoubleRequested open price (Ask for Buy, Bid for Sell, or pending price)
sl / tpdoubleStop loss and take profit absolute price levels
deviationulongRequested price deviation in points; applicability depends on execution mode
typeENUM_ORDER_TYPEORDER_TYPE_BUY, ORDER_TYPE_SELL, BUY_LIMIT, SELL_STOP, etc.
type_fillingENUM_ORDER_TYPE_FILLINGExecution filling policy (FOK, IOC, or RETURN)

Filling Policies: Avoiding Immediate Rejection

A frequent source of OrderSend failures in MQL5 is specifying an unsupported type_filling. Brokers configure allowed filling modes per symbol (SymbolInfoInteger(_Symbol, SYMBOL_FILLING_MODE)).

  • ORDER_FILLING_FOK (Fill or Kill): Order must be executed in full immediately, or cancelled.
  • ORDER_FILLING_IOC (Immediate or Cancel): Fill available volume immediately; cancel unfilled balance.
  • ORDER_FILLING_RETURN: Keep unfilled volume for further processing. It is disallowed for market-execution deals; pending orders use RETURN regardless of the symbol execution mode.

Handling MqlTradeResult Return Codes

A true return value from OrderSend indicates that the request was processed by the trade server, but does not guarantee execution. You must verify result.retcode.

Retcode ConstantCodeMeaning and Action
TRADE_RETCODE_DONE10009Request completed; inspect action-specific result fields and actual account state
TRADE_RETCODE_PLACED10008Order placed; this alone does not confirm a completed fill
TRADE_RETCODE_REQUOTE10004Requoted; reassess the new quote and request before a bounded retry
TRADE_RETCODE_INVALID_STOPS10016Invalid stops; inspect direction, distances, tick alignment and broker rules
TRADE_RETCODE_NO_MONEY10019Insufficient margin on account to open requested volume

Implementation details & mechanics

Core implementation pattern

The script below defaults to logging only. Explicitly enable a demo-account test to request one market buy with SL and TP. It selects a filling policy, calls OrderCheck, then sends the request and distinguishes completed, partial and placed states. It is a request example, not a trading strategy or pending-order engine.

Error handling & safety rules

For a stop modification, supply the action, position ticket, symbol and intended SL/TP, preserving levels you do not want to remove. Closing uses an opposite deal tied to the position ticket: sell at bid for a long, buy at ask for a short, subject to execution mode. The script does not manage subsequent exits or pending states; inspect the demo account after running it.

MQL5 Code Implementation

//+------------------------------------------------------------------+
//|                                               OrderSendGuide.mq5 |
//|                             Copyright 2026, Pineify Guides Series |
//|                                              https://pineify.app |
//+------------------------------------------------------------------+
#property copyright "Pineify Guides Series"
#property link      "https://pineify.app/mql5/ordersend-guide"
#property version   "1.00"
#property script_show_inputs

//--- Input parameters
input bool EnableDemoOrder=false; // Default only logs; no request sent.
input double InpLotSize          = 0.10;   // Lot Size
input int    InpStopLossPoints   = 200;    // Stop Loss in points
input int    InpTakeProfitPoints = 400;    // Take Profit in points
input ulong  InpSlippagePoints   = 20;     // Slippage in points
input ulong  InpMagicNumber      = 770011; // EA Magic Number

//+------------------------------------------------------------------+
//| Helper: Determine supported filling mode for current symbol      |
//+------------------------------------------------------------------+
bool GetSymbolFillingMode(const string symbol,ENUM_ORDER_TYPE_FILLING &mode)
  {
   long execution=SymbolInfoInteger(symbol,SYMBOL_TRADE_EXEMODE);
   long flags=SymbolInfoInteger(symbol,SYMBOL_FILLING_MODE);
   if(execution==SYMBOL_TRADE_EXECUTION_INSTANT || execution==SYMBOL_TRADE_EXECUTION_REQUEST
      || (flags&SYMBOL_FILLING_FOK)!=0) { mode=ORDER_FILLING_FOK; return true; }
   if((flags&SYMBOL_FILLING_IOC)!=0) { mode=ORDER_FILLING_IOC; return true; }
   if(execution!=SYMBOL_TRADE_EXECUTION_MARKET) { mode=ORDER_FILLING_RETURN; return true; }
   return false;
  }

//+------------------------------------------------------------------+
//| Helper: Send Market Buy Order with Low-Level OrderSend          |
//+------------------------------------------------------------------+
bool SendMarketBuy(double lots, int slPoints, int tpPoints)
  {
   MqlTradeRequest request;
   MqlTradeResult  result;

   // 1. Always zero out request struct to avoid garbage values
   ZeroMemory(request);
   ZeroMemory(result);

   double point  = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
   int digits    = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
   double ask    = SymbolInfoDouble(_Symbol, SYMBOL_ASK);

   // 2. Populate trade request
   request.action       = TRADE_ACTION_DEAL;
   request.symbol       = _Symbol;
   request.volume       = lots;
   request.type         = ORDER_TYPE_BUY;
   request.price        = ask;
   request.deviation    = InpSlippagePoints;
   request.magic        = InpMagicNumber;
   if(!GetSymbolFillingMode(_Symbol,request.type_filling)) return false;
   request.comment      = "Pineify OrderSend";

   if(slPoints > 0)
      request.sl = NormalizeDouble(ask - (slPoints * point), digits);
   if(tpPoints > 0)
      request.tp = NormalizeDouble(ask + (tpPoints * point), digits);

   MqlTradeCheckResult check={};
   if(!OrderCheck(request,check))
     { Print("OrderCheck failed: ",check.retcode," ",check.comment); return false; }
   // Passing preflight does not guarantee subsequent execution.
   // 3. Send trade request to server
   if(!OrderSend(request, result))
     {
      PrintFormat("OrderSend critically failed! Retcode: %u, Error: %d",
                  result.retcode, GetLastError());
      return false;
     }

   // 4. Verify execution retcode
   if(result.retcode == TRADE_RETCODE_DONE)
     {
      PrintFormat("OrderSend SUCCESS! Order Ticket: %I64u, Deal: %I64u, Price: %.*f, Vol: %.2f",
                  result.order, result.deal, digits, result.price, result.volume);
      return true;
     }

   if(result.retcode==TRADE_RETCODE_PLACED || result.retcode==TRADE_RETCODE_DONE_PARTIAL)
     {
      Print("Accepted/partial state requires reconciliation; do not blindly resend. Order=",result.order," retcode=",result.retcode);
      return false;
     }
   PrintFormat("OrderSend not completed. Retcode: %u (%s)",
               result.retcode, result.comment);
   return false;
  }

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   if(!EnableDemoOrder) { Print("Demo sending disabled; inspect the request example first."); return; }
   if(AccountInfoInteger(ACCOUNT_TRADE_MODE)!=ACCOUNT_TRADE_MODE_DEMO)
     { Print("Only a demo account is accepted by this example."); return; }
   if(InpLotSize<=0 || InpStopLossPoints<=0 || InpTakeProfitPoints<=0 || InpMagicNumber==0)
     { Print("Invalid inputs"); return; }
   if(PositionSelect(_Symbol)) { Print("Existing symbol position; demo request skipped."); return; }
   Print("Initiating one demo OrderSend request on ", _Symbol);
   SendMarketBuy(InpLotSize, InpStopLossPoints, InpTakeProfitPoints);
  }

Copy this code into MetaEditor, save it in your MQL5 folder (Experts, Scripts, or Include), and compile with F7.

Generate custom MQL5 code with Pineify AI

Describe the trade execution, indicator calculations, risk management, or data processing logic you need. Pineify generates editable MQL5 source code. Review its logic, request a syntax check, and compile and test the final file in MetaEditor.

Frequently Asked Questions

Related MQL5 pages

Technical references

Risk and testing note

These educational examples require independent compilation and testing. A compile pass or an illustrative setting does not establish execution correctness or profitability. Any reported performance must be supported by reproducible data and test settings; past results do not predict future returns. Trading involves significant risk of loss. This content is not financial advice.