- 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
Estimating the profit of a trading operation: OrderCalcProfit
One of the MQL5 API functions, OrderCalcProfit, allows you to pre-evaluate the financial result of a trading operation if the expected conditions are met. For example, using this function you can find out the amount of profit when reaching the Take Profit level, and the amount of loss when Stop Loss is triggered.
bool OrderCalcProfit(ENUM_ORDER_TYPE action, const string symbol, double volume,
double openPrice, double closePrice, double &profit)
The function calculates the profit or loss in the account currency for the current market environment based on the passed parameters.
The order type is specified in the action parameter. Only market orders ORDER_TYPE_BUY or ORDER_TYPE_SELL from the ENUM_ORDER_TYPE enumeration are allowed. The name of the financial instrument and its volume are passed in the parameters symbol and volume. The market entry and exit prices are set by the parameters openPrice and closePrice, respectively. The profit variable is passed by reference as the last parameter, and the profit value will be written in it.
The function returns an indicator of success (true) or error (false).
The formula for calculating the financial result used inside OrderCalcProfit depends on the symbol type.
Identifier |
Formula |
---|---|
SYMBOL_CALC_MODE_FOREX |
(ClosePrice - OpenPrice) * ContractSize * Lots |
SYMBOL_CALC_MODE_FOREX_NO_LEVERAGE |
(ClosePrice - OpenPrice) * ContractSize * Lots |
SYMBOL_CALC_MODE_CFD |
(ClosePrice - OpenPrice) * ContractSize * Lots |
SYMBOL_CALC_MODE_CFDINDEX |
(ClosePrice - OpenPrice) * ContractSize * Lots |
SYMBOL_CALC_MODE_CFDLEVERAGE |
(ClosePrice - OpenPrice) * ContractSize * Lots |
SYMBOL_CALC_MODE_EXCH_STOCKS |
(ClosePrice - OpenPrice) * ContractSize * Lots |
SYMBOL_CALC_MODE_EXCH_STOCKS_MOEX |
(ClosePrice - OpenPrice) * ContractSize * Lots |
SYMBOL_CALC_MODE_FUTURES |
(ClosePrice - OpenPrice) * Lots * TickPrice / TickSize |
SYMBOL_CALC_MODE_EXCH_FUTURES |
(ClosePrice - OpenPrice) * Lots * TickPrice / TickSize |
SYMBOL_CALC_MODE_EXCH_FUTURES_FORTS |
(ClosePrice - OpenPrice) * Lots * TickPrice / TickSize |
SYMBOL_CALC_MODE_EXCH_BONDS |
Lots * ContractSize * (ClosePrice * FaceValue + AccruedInterest) |
SYMBOL_CALC_MODE_EXCH_BONDS_MOEX |
Lots * ContractSize * (ClosePrice * FaceValue + AccruedInterest) |
SYMBOL_CALC_MODE_SERV_COLLATERAL |
Lots * ContractSize * MarketPrice * LiqudityRate |
The following notation is used in the formulas:
- Lots position volume in lots (contract shares)
- ContractSize contract size (one lot, SYMBOL_TRADE_CONTRACT_SIZE)
- TickPrice tick price (SYMBOL_TRADE_TICK_VALUE)
- TickSize tick size (SYMBOL_TRADE_TICK_SIZE)
- MarketPrice last known price Bid/Ask depending on the type of transaction
- OpenPrice position opening price
- ClosePrice position closing price
- FaceValue face value of the bond (SYMBOL_TRADE_FACE_VALUE)
- LiqudityRate liquidity ratio (SYMBOL_TRADE_LIQUIDITY_RATE)
- AccruedInterest accumulated coupon income (SYMBOL_TRADE_ACCRUED_INTEREST)
The OrderCalcProfit function can only be used in Expert Advisors and scripts. To calculate potential profit/loss in indicators, you need to implement an alternative method, for example, independent calculations using formulas.
To bypass the restriction on the use of the OrderCalcProfit and OrderCalcMargin functions in indicators, we have developed a set of functions that perform calculations using the formulas from this section, as well as the section Margin requirements. The functions are in the header file MarginProfitMeter.mqh, inside the common namespace MPM (from "Margin Profit Meter").
In particular, to calculate the financial result, it is important to have the value of one point of a particular instrument. In the above formulas, it indirectly participates in the difference between the opening and closing prices (ClosePrice - OpenPrice).
The function calculates the value of one price point PointValue.
namespace MPM
|
At the beginning of the function, we request all the symbol properties needed for the calculation. Then, depending on the type of symbol, we obtain profit/loss in the currency of the profit of this instrument. Please note that there are no bonds here, the formulas of which take into account the nominal price and coupon income.
double result = 0;
|
Finally, we convert the amount to the account currency, if it differs.
string account = AccountInfoString(ACCOUNT_CURRENCY);
|
The helper function Convert is used to convert amounts. It, in turn, depends on the FindExchangeRate function, which searches among all available symbols for one that contains the rate from the current currency into the account currency.
bool Convert(const string current, const string account,
|
The FindExchangeRate function looks up characters in Market Watch and returns the name of the first matching Forex symbol, if there are several of them, in the result parameter. If the quote corresponds to the direct order of currencies "current/account", the function will return +1, and if the opposite, it will be "account/current", i.e. -1.
int FindExchangeRate(const string current, const string account, string &result)
|
The full code of the functions can be found in the attached file MarginProfitMeter.mqh.
Let's check the performance of the OrderCalcProfit function and the group of functions MPM with a test script ProfitMeter.mq5: we will calculate the profit/loss estimate for virtual trades for all symbols of the Market Watch, and we will do it using two methods: built-in and ours.
In the input parameters of the script, you can select the type of operation Action (buy or sell), lot size Lot and the position holding time in bars Duration. The financial result is calculated for the quotes of the last Duration bars of the current timeframe.
#property script_show_inputs
|
In the body of the script, we connect the header files and display the header with the parameters.
#include <MQL5Book/MarginProfitMeter.mqh>
|
Then, in a loop through symbols, we perform the calculations in two ways and print the results for comparison.
for(int i = 0; i < SymbolsTotal(true); i++)
|
Try running the script for different accounts and instrument sets.
Profits/Losses for buying 1.0 lots of 13 symbols in Market Watch on last 20 bars H1
|
Ideally, the numbers in each line should match.