- Expert Advisors main event: OnTick
- Basic principles and concepts: order, deal, and position
- Types of trading operations
- Order types
- Order execution modes by price and volume
- Pending order expiration dates
- Margin calculation for a future order: OrderCalcMargin
- Estimating the profit of a trading operation: OrderCalcProfit
- MqlTradeRequest structure
- MqlTradeCheckResult structure
- Request validation: OrderCheck
- Request sending result: MqlTradeResult structure
- Sending a trade request: OrderSend and OrderSendAsync
- Buying and selling operations
- Modying Stop Loss and/or Take Profit levels of a position
- Trailing stop
- Closing a position: full and partial
- Closing opposite positions: fill and partial
- Placing a pending order
- Modifying a pending order
- Deleting a pending order
- Getting a list of active orders
- Order properties (active and historical)
- Functions for reading properties of active orders
- Selecting orders by properties
- Getting the list of positions
- Position properties
- Functions for reading position properties
- Deal properties
- Selecting orders and deals from history
- Functions for reading order properties from history
- Functions for reading deal properties from history
- Types of trading transactions
- OnTradeTransaction event
- Synchronous and asynchronous requests
- OnTrade event
- Monitoring trading environment changes
- Creating multi-symbol Expert Advisors
- Limitations and benefits of Expert Advisors
- Creating Expert Advisors in the MQL Wizard
Sending a trade request: OrderSend and OrderSendAsync
To perform trading operations, the MQL5 API provides two functions: OrderSend and OrderSendAsync. Just like OrderCheck, they perform a formal check of the request parameters passed in the form of the MqlTradeRequest structure and then, if successful, send a request to the server.
The difference between the two functions is as follows. OrderSend expects for the order to be queued for processing on the server and receives meaningful data from it into the fields of the MqlTradeResult structure which is passed as the second function parameter. OrderSendAsync immediately returns control to the calling code regardless of how the server responds. At the same time, from all fields of the MqlTradeResult structure except retcode, important information is filled only into request_id. Using this request identifier, an MQL program can receive further information about the progress of processing this request in the OnTradeTransaction event. An alternative approach is to periodically analyze the lists of orders, deals, and positions. This can also be done in a loop, setting some timeout in case of communication problems.
It's important to note that despite the "Async" suffix in the second function's name, the first function without this suffix is also not fully synchronous. The fact is that the result of order processing by the server, in particular, the execution of a deal (or, probably, several deals based on one order) and the opening of a position, generally occurs asynchronously in an external trading system. So the OrderSend function also requires delayed collection and analysis of the consequences of request execution, which MQL programs must, if necessary, implement themselves. We'll look at an example of truly synchronous sending of a request and receiving all of its results later (see MqlTradeSync.mqh).
bool OrderSend(const MqlTradeRequest &request, MqlTradeResult &result)
The function returns true in case of a successful basic check of the request structure in the terminal and a few additional checks on the server. However, this only indicates the acceptance of the order by the server and does not guarantee a successful execution of the trade operation.
The trade server can fill the field deal or order values in the returned result structure if this data is known at the time the server formats an answer to the OrderSend call. However, in the general case, the events of deal execution or placing limit orders corresponding to an order can occur after the response is sent to the MQL program in the terminal. Therefore, for any type of trade request, when receiving the execution OrderSend result, it is necessary to check the trade server return code retcode and external trading system response code retcode_external (if necessary) which are available in the returned result structure. Based on them, you should decide whether to wait for pending actions on the server or take your own actions.
Each accepted order is stored on the trade server pending processing until any of the following events that affect its life cycle occurs:
- execution when a counter request appears
- triggered when the execution price arrives
- expiration date
- cancellation by the user or MQL program
- removal by the broker (for example, in case of clearing or shortage of funds, Stop Out)
The OrderSendAsync prototype completely repeats that of OrderSend.
bool OrderSendAsync(const MqlTradeRequest &request, MqlTradeResult &result)
The function is intended for high-frequency trading, when, according to the conditions of the algorithm, it is unacceptable to waste time waiting for a response from the server. The use of OrderSendAsync does not speed up request processing by the server or request sending to the external trading system.
Attention! In the tester, the OrderSendAsync function works like OrderSend. This makes it difficult to debug the pending processing of asynchronous requests.
The function returns true upon a successful sending of the request to the MetaTrader 5 server. However, this does not mean that the request reached the server and was accepted for processing. At the same time, the response code in the receiving result structure contains the TRADE_RETCODE_PLACED (10008) value, that is, "the order has been placed".
When processing the received request, the server will send a response message to the terminal about a change in the current state of positions, orders and deals, which leads to the generation of the OnTrade event in an MQL program. There, the program can analyze the new trading environment and account history. We will look at relevant examples below.
Also, the details of the trader request execution on the server can be tracked using the OnTradeTransaction handler. At the same time, it should be considered that as a result of the execution of one trade request, the OnTradeTransaction handler will be called multiple times. For example, when sending a market buy request, it is accepted for processing by the server, a corresponding 'buy' order is created for the account, the order is executed and the trader is performed, as a result of which it is removed from the list of open orders and added to the history of orders. Then the trade is added to the history and a new position is created. For each of these events, the OnTradeTransaction function will be called.
Let's start with a simple Expert Advisor example CustomOrderSend.mq5. It allows you to set all fields of the request in the input parameters, which is similar to CustomOrderCheck.mq5, but further differs in that it sends a request to the server instead of a simple check in the terminal. Run the Expert Advisor on your demo account. After completing the experiments, don't forget to remove the Expert Advisor from the chart or close the chart so that you don't send a test request every next launch of the terminal.
The new example has several other improvements. First of all the input parameter Async is added.
input bool Async = false; |
This option allows selecting the function that will send the request to the server. By default, the parameter equals to false and the OrderSend function is used. If you set it to true, OrderSendAsync will be called.
In addition, with this example, we will begin to describe and complete a special set of functions in the header file TradeUtils.mqh, which will come in handy to simplify the coding of robots. All functions are placed in the namespace TU (from "Trade Utilities"), and first, we introduce functions for convenient output to the structure log MqlTradeRequest and MqlTradeResult.
namespace TU
|
The purpose of the functions is to provide all significant (non-empty) fields in a concise but convenient form: they are displayed in one line with a unique designation for each.
As you can see, the function uses the SymbolMetrics class for MqlTradeRequest. It facilitates the normalization of multiple prices or volumes for the same instrument. Don't forget that the normalization of prices and volumes is a prerequisite for preparing a correct trade request.
class SymbolMetrics
|
The direct normalization of values is entrusted to auxiliary functions NormalizePrice and NormalizeLot (the scheme of the latter is identical to what we saw in the file LotMarginExposure.mqh).
double NormalizePrice(const double price, const string symbol = NULL)
|
If we connect TradeUtils.mqh, the example CustomOrderSend.mq5 has the following form (the omitted code fragments '...' remained unchanged from CustomOrderCheck.mq5).
void OnTimer()
|
Due to the fact that prices and volume are now normalized, you can try to enter uneven values into the corresponding input parameters. They are often obtained in programs during calculations, and our code converts them according to the symbol specification.
With default settings, the Expert Advisor creates a request to buy the minimum lot of the current instrument by market and makes it using the OrderSend function.
OrderSend(request,result)=true / ok TRADE_ACTION_DEAL, EURUSD, ORDER_TYPE_BUY, V=0.01, ORDER_FILLING_FOK, @ 1.12462 DONE, D=1250236209, #=1267684253, V=0.01, @ 1.12462, Bid=1.12456, Ask=1.12462, Request executed, Req=1 |
As a rule, with allowed trading, this operation should be completed successfully (status DONE, comment "Request executed"). In the result structure, we immediately received the deal number D.
If we open Expert Advisor settings and replace the value of the parameter Async with true, we will send a similar request but with the OrderSendAsync function.
OrderSendAsync(request,result)=true / ok TRADE_ACTION_DEAL, EURUSD, ORDER_TYPE_BUY, V=0.01, ORDER_FILLING_FOK, @ 1.12449 PLACED, Order placed, Req=2 |
In this case, the status is PLACED, and the trade number at the time the function returns is not known. We only know the unique request ID Req=2. To get the deal and position number, you need to intercept the TRADE_TRANSACTION_REQUEST message with the same request ID in the OnTradeTransaction handler, where the filled structure will be received as a MqlTradeResult parameter.
From the user's point of view, both requests should be equally fast.
It will be possible to compare the performance of these two functions directly in the code of an MQL program using another example of an Expert Advisor (see the section on synchronous and asynchronous requests), which we will consider after studying the model of trading events.
It should be noted that trading events are sent to the OnTradeTransaction handler (if present in the code), regardless of which function is used to send requests, OrderSend or OrderSendAsync. The situation is as follows: in case of applying OrderSend some or all information about the execution of the order is immediately available in the receiving MqlTradeResult structure. However, in the general case, the result is distributed over time and volume, for example, when one order is "filled" into several deals. Then complete information can be obtained from trading events or by analyzing the history of transactions and orders.
If you try to send a deliberately incorrect request, for example, change the order type to a pending ORDER_TYPE_BUY_STOP, you will get an error message, because for such orders you should use the TRADE_ACTION_PENDING action. Furthermore, they should be located at a distance from the current price (we use the market price by default). Before this test, it is important not to forget to change the query mode back to synchronous (Async=false) to immediately see the error in the MqlTradeResult structure after ending the OrderSend call. Otherwise, OrderSendAsync would return true, but the order would still not be set, and the program could receive information about this only in OnTradeTransaction which we don't have yet.
OrderSend(request,result)=false / TRADE_SEND_FAILED(4756) TRADE_ACTION_DEAL, EURUSD, ORDER_TYPE_BUY_STOP, V=0.01, ORDER_FILLING_FOK, @ 1.12452, ORDER_TIME_GTC REQUOTE, Bid=1.12449, Ask=1.12452, Requote, Req=5 |
In this case, the error reports an invalid Requote price.
Examples of using functions to perform specific trading actions will be presented in the following sections.