Русский 中文 Español Deutsch 日本語 Português
MetaTrader 5 features hedging position accounting system

MetaTrader 5 features hedging position accounting system

MetaTrader 5Trading | 21 March 2016, 13:11
81 383 23
MetaQuotes
MetaQuotes

The MetaTrader 5 platform was originally designed for trading within the netting position accounting system. The netting system allows having only one position per financial instrument meaning that all further operations at that instrument lead only to closing, reversal or changing the volume of the already existing position. In order to expand possibilities of retail Forex traders, we have added the second accounting system — hedging. Now, it is possible to have multiple positions per symbol, including oppositely directed ones. This paves the way to implementing trading strategies based on the so-called "locking" — if the price moves against a trader, they can open a position in the opposite direction.

Since the new system is similar to the one used in MetaTrader 4, it will be familiar to traders. At the same time, traders will be able to enjoy all the advantages of the fifth platform version — filling orders using multiple deals (including partial fills), multicurrency and multithreaded tester with support for MQL5 Cloud Network, and much more.

Now, you can use one account to trade the markets that adhere to the netting system and allow having only one position per instrument, and use another account in the same platform to trade Forex and apply hedging.

This article describes the netting and hedging systems in details, as well as sheds light on the changes related to the implementation of the second accounting system.


Position accounting depends on a trading account

A position accounting system is set at an account level and displayed in the terminal window header and the Journal:

Position accounting system on the current account

To open a demo account with hedging, enable the appropriate option:

Opening the demo account with hedging

To open a real account with hedging, contact your broker.


Netting system

With this system, you can have only one common position for a symbol at the same time:

  • If there is an open position for a symbol, executing a deal in the same direction increases the volume of this position.
  • If a deal is executed in the opposite direction, the volume of the existing position can be decreased, the position can be closed (when the deal volume is equal to the position volume) or reversed (if the volume of the opposite deal is greater than the current position).

It does not matter, what has caused the opposite deal — an executed market order or a triggered pending order.

The below example shows execution of two EURUSD Buy deals 0.5 lots each:

Netting

Execution of both deals resulted in one common position of 1 lot.


Hedging system

With this system, you can have multiple open positions of one and the same symbol, including opposite positions.

If you have an open position for a symbol, and execute a new deal (or a pending order triggers), a new position is additionally opened. Your current position does not change.

The below example shows execution of two EURUSD Buy deals 0.5 lots each:

Hedging

Execution of these deals resulted in opening two separate positions.


Impact of the system selected

Depending on the position accounting system, some of the platform functions may have different behavior:

  • Stop Loss and Take Profit inheritance rules change.
  • To close a position in the netting system, you should perform an opposite trading operation for the same symbol and the same volume. To close a position in the hedging system, explicitly select the "Close Position" command in the context menu of the position.
  • A position cannot be reversed in the hedging system. In this case, the current position is closed and a new one with the remaining volume is opened.
  • In the hedging system, a new condition for margin calculation is available — Hedged margin.


New trade operation type - Close By

The new trade operation type has been added for hedging accounts — closing a position by an opposite one. This operation allows closing two oppositely directed positions at a single symbol. If the opposite positions have different numbers of lots, only one order of the two remains open. Its volume will be equal to the difference of lots of the closed positions, while the position direction and open price will match (by volume) the greater of the closed positions.

Compared with a single closure of the two positions, the closing by an opposite position allows traders to save one spread:

  • In case of a single closing, traders have to pay a spread twice: when closing a buy position at a lower price (Bid) and closing a sell position at a higher one (Ask).
  • When using an opposite position, an open price of the second position is used to close the first one, while an open price of the first position is used to close the second one.

Closing the position by the opposite one

In the latter case, a "close by" order is placed. Tickets of closed positions are specified in its comment. A pair of opposite positions is closed by two "out by" deals. Total profit/loss resulting from closing the both positions is specified only in one deal.

"Close by" operation in History


Margin calculation in the hedging system of position accounting

If the hedging position accounting system is used, the margin is calculated using the same formulas and principles as described above. However, there are some additional features for multiple positions of the same symbol.

Positions/orders open in the same direction

Their volumes are summed up and the weighted average open price is calculated for them. The resulting values are used for calculating margin by the formula corresponding to the symbol type.

For pending orders (if the margin ratio is non-zero), margin is calculated separately.

Opposite positions/orders

Oppositely directed open positions of the same symbol are considered hedged or covered. Two margin calculation methods are possible for such positions. The calculation method is determined by the broker.

Hedged margin calculation settings in the contract specification


Basic calculation
Using the larger leg
Used if "calculate using larger leg" is not specified in the "Hedged margin" field of contract specification.

The calculation consists of several steps:
  • For uncovered volume
  • For covered volume (if hedged margin size is specified)
  • For pending orders
The resulting margin value is calculated as the sum of margins calculated at each step.

Calculation for uncovered volume
  • Calculation of the total volume of all positions and market orders for each of the legs — buy and sell.
  • Calculation of the weighted average position and market order open price for each leg: (open price of position or order 1 * volume of position or order 1 + ... + open price of position or order N * volume of position or order N) / (volume of position or order 1 + ... + volume of position or order N).
  • Calculation of uncovered volume (smaller leg volume is subtracted from the larger one).
  • The calculated volume and weighted average price are used then to calculate margin by the appropriate formula corresponding to the symbol type.
  • The weighted average value of the ratio and rate is used when taking into account the margin ratio and converting margin currency to deposit currency.

Calculation for covered volume
Used if the "Hedged margin" value is specified in a contract specification. In this case margin is charged for hedged, as well as uncovered volume.

If the initial margin is specified for a symbol, the hedged margin is specified as an absolute value (in monetary terms).

If the initial margin is not specified (equal to 0), the contract size is specified in the "Hedged" field. The margin is calculated by the appropriate formula in accordance with the type of the financial instrument, using the specified contract size. For example, we have two positions Buy EURUSD 1 lot and Sell EURUSD 1 lot, the contract size is 100,000. If the value of 100,000 is specified in the "Hedged field", the margin for the two positions will be calculated as per 1 lot. If you specify 0, no margin is charged for the hedged (covered) volume.

Per each hedged lot of a position, the margin is charged in accordance with the value specified in the "Hedged Margin" field in the contract specification:
  • Calculation of hedged volume for all open positions and market orders (uncovered volume is subtracted from the larger leg).
  • Calculation of the weighted average position and market order open price: (open price of position or order 1 * volume of position or order 1 + ... + open price of position or order N * volume of position or order N) / (volume of position or order 1 + ... + volume of position or order N).
  • The calculated volume, weighted average price and the hedged margin value are used then to calculate margin by the appropriate formula corresponding to the symbol type.
  • The weighted average value of the ratio and rate is used when taking into account the margin ratio and converting margin currency to deposit currency.

Calculation for pending orders
  • Calculation of margin for each pending order type separately (Buy Limit, Sell Limit, etc.).
  • The weighted average value of the ratio and rate for each pending order type is used when taking into account the margin ratio and converting margin currency to deposit currency.
Used if "calculate using larger leg" is specified in the "Hedged margin" field of contract specification.
  • Calculation of margin for shorter and longer legs for all open positions and market orders.
  • Calculation of margin for each pending order type separately (Buy Limit, Sell Limit, etc.).
  • Summing up a longer leg margin: long positions and market orders + long pending orders.
  • Summing up a shorter leg margin: short positions and market orders + short pending orders.
  • The largest one of all calculated values is used as the final margin value.


Changes in MQL5

Now, each position has its unique ticket. It usually corresponds to the ticket of an order used to open the position. A ticket is assigned automatically to all available positions after the terminal update.

When modifying or closing a position in the hedging system, make sure to specify its ticket (MqlTradeRequest::ticket). You can specify a ticket in the netting system as well, however positions are identified by a symbol name.


MqlTradeRequest

MqlTradeRequest features two new fields:

  • position — position ticket. Fill it when changing and closing a position for its clear identification. It usually matches the ticket of an order used to open the position.
  • position_by — opposite position ticket. It is used when closing a position by an opposite one (opened at the same symbol but in the opposite direction).
struct MqlTradeRequest
  {
   ENUM_TRADE_REQUEST_ACTIONS    action;           // Performed action type
   ulong                         magic;            // Expert Advisor magic number
   ulong                         order;            // Order ticket
   string                        symbol;           // Symbol name
   double                        volume;           // Requested deal volume in lots
   double                        price;            // Price 
   double                        stoplimit;        // Stop Limit order level
   double                        sl;               // Stop Loss order level
   double                        tp;               // Take Profit order level
   ulong                         deviation;        // Maximum allowable deviation from the requested price
   ENUM_ORDER_TYPE               type;             // Order type
   ENUM_ORDER_TYPE_FILLING       type_filling;     // Order filling type
   ENUM_ORDER_TYPE_TIME          type_time;        // Order time type
   datetime                      expiration;       // Order expiration date (for ORDER_TIME_SPECIFIED type orders)
   string                        comment;          // Order comment
   ulong                         position;         // Position ticket
   ulong                         position_by;      // Opposite position ticket
  };

MqlTradeTransaction

MqlTradeTransaction also features the two similar fields:

  • position — ticket of a position affected by transaction. It is filled for transactions related to handling market orders (TRADE_TRANSACTION_ORDER_* except TRADE_TRANSACTION_ORDER_ADD, where a position ticket is not assigned yet) and order history (TRADE_TRANSACTION_HISTORY_*).
  • position_by — opposite position ticket. It is used when closing a position by an opposite one (opened at the same symbol but in the opposite direction). It is filled only for orders closing a position by an opposite one (close by) and deals closing by an opposite one (out by).
struct MqlTradeTransaction
  {
   ulong                         deal;             // Deal ticket
   ulong                         order;            // Order ticket
   string                        symbol;           // Symbol name
   ENUM_TRADE_TRANSACTION_TYPE   type;             // Transaction type
   ENUM_ORDER_TYPE               order_type;       // Order type
   ENUM_ORDER_STATE              order_state;      // Order state
   ENUM_DEAL_TYPE                deal_type;        // Deal type
   ENUM_ORDER_TYPE_TIME          time_type;        // Order time type
   datetime                      time_expiration;  // Order expiration date
   double                        price;            // Price 
   double                        price_trigger;    // Stop limit order trigger price
   double                        price_sl;         // Stop Loss level
   double                        price_tp;         // Take Profit level
   double                        volume;           // Volume in lots
   ulong                         position;         // Position tickets
   ulong                         position_by;      // Opposite position tickets
  };


PositionGetTicket

The new PositionGetTicket function returns a position ticket by an index in the list of open positions and automatically selects that position for further work using the PositionGetDouble, PositionGetInteger, and PositionGetString functions.

ulong  PositionGetTicket(
   int  index      // index in the list of positions
   );


PositionSelectByTicket

The new PositionSelectByTicket function selects an open position for further work by a specified ticket.

bool  PositionSelectByTicket(
   ulong   ticket     // position ticket
   );


PositionSelect

PositionSelect selects a position by a symbol name for further work using the PositionGetDouble, PositionGetInteger, and PositionGetString functions. In the hedging system (where there can be multiple positions at a single symbol), the function selects a position with the lowest ticket.


ACCOUNT_MARGIN_MODE

The new property ACCOUNT_MARGIN_MODE allows receiving the mode of margin calculation and position accounting on a trading account:

Identifier
Description
ACCOUNT_MARGIN_MODE_RETAIL_NETTING
Used for the over-the-counter market when accounting positions in the netting mode (one position per symbol). Margin calculation is based on a symbol type (SYMBOL_TRADE_CALC_MODE).
ACCOUNT_MARGIN_MODE_EXCHANGE
Used on the exchange markets. Margin calculation is based on the discounts specified in symbol settings. Discounts are set by the broker, however they cannot be lower than the exchange set values.
ACCOUNT_MARGIN_MODE_RETAIL_HEDGING
Used for the over-the-counter market with independent position accounting (hedging, there can be multiple positions at a single symbol). Margin calculation is based on a symbol type (SYMBOL_TRADE_CALC_MODE). The presence of multiple positions at a single symbol is considered.


SYMBOL_MARGIN_HEDGED

The new property SYMBOL_MARGIN_HEDGED allows receiving the value of a hedged margin by a trading symbol. Margin calculation in the hedging system of position accounting has been described above.


New trading constants

Due to the addition of the new Close By operation type, the new trading properties have appeared as well:

  • TRADE_ACTION_CLOSE_BY — new trading operation type — close a position by an opposite one.
  • ORDER_TYPE_CLOSE_BY — new order type — close a position by an opposite one.
  • ORDER_POSITION_BY_ID — new order propertiy — ticket of an opposite position used for closing the current one.
  • DEAL_ENTRY_OUT_BY — new deal type — close a position by an opposite one.


Extra bonus — hedging and MQL5 Cloud Network

Now, you can use MetaTrader 5 to trade both stock markets and the popular retail Forex with hedging. Developers of the automated systems applying hedging have received another important advantage. Apart from the multithreaded tester, the entire computing capacity of the MQL5 Cloud Network is at their disposal now.

Update your platform and try the new features!

Translated from Russian by MetaQuotes Ltd.
Original article: https://www.mql5.com/ru/articles/2299

Last comments | Go to discussion (23)
Alain Verleyen
Alain Verleyen | 16 Apr 2016 at 13:45
Rodrigo Silva Cosme:
I see one great advantage when trading different time frames. On the netting system it was necessary to keep virtual positions on each time frame, virtual stop loss and take profit orders, etc. That was a lot of work. I could be long on EURUSD on H1, short on H8 and long on D1 all with different stop loss levels and there was no easy way to handle that with the netting system. With the possibility of closing different positions on the same currency that problem is solved and trading on the way I described on the same currency is a lot easier.
Of course, that's a lot easier.
Shaharudin Ahmad
Shaharudin Ahmad | 29 Apr 2016 at 13:54

hi,

i prefer original mt5. 

Rodolfo Machado
Rodolfo Machado | 9 May 2016 at 23:50
Diogo Seca:
There's something I must not be grasping here. I don't see any overall benefit when it comes to hedging this way.
I mean, as I see it, the reason MQL5 never allowed hedging like this in the first place was because hedging a position by opening an opposite position is the same thing as simply closing the first one.

Why would a user prefer the "hedging system" to the "netting system"?

The only reason I could see for this implementation is more compatibility with brokers, somehow. Any insights here?
I'm also waiting for a broker with real accounts for MT5 Hedging...
[Deleted] | 16 Mar 2017 at 02:59

In other words, while the MT5 is advertised to have more features than MT4, it (in fact) restricts the traders' options.

This is how I see it and it wasn't really necesary for the traders as most of them are happy with MT4. It's like others have said, MT4 is for the traders, MT5 is for the brokers :)

QuickPip
QuickPip | 26 Mar 2020 at 17:07
Carl Schreiber:

What about the commission?

If I have two open positions, one buy, one sell, and close the 'sell' by the 'buy' I have paid twice the commission. But I would have paid only once the commission if I just close the buy, isn't it?

But what if a broker isn't asking for a commission but has increased the spread? Don't I pay the spread twice as well?

What about Carl's concern about paying the commission twice? Any answers from MetaQuotes, any experiences, please?
Graphical Interfaces II: Setting Up the Event Handlers of the Library (Chapter 3) Graphical Interfaces II: Setting Up the Event Handlers of the Library (Chapter 3)
The previous articles contain the implementation of the classes for creating constituent parts of the main menu. Now, it is time to take a close look at the event handlers in the principle base classes and in the classes of the created controls. We will also pay special attention to managing the state of the chart depending on the location of the mouse cursor.
Universal Expert Advisor: the Event Model and Trading Strategy Prototype (Part 2) Universal Expert Advisor: the Event Model and Trading Strategy Prototype (Part 2)
This article continues the series of publications on a universal Expert Advisor model. This part describes in detail the original event model based on centralized data processing, and considers the structure of the CStrategy base class of the engine.
Universal Expert Advisor: Custom Strategies and Auxiliary Trade Classes (Part 3) Universal Expert Advisor: Custom Strategies and Auxiliary Trade Classes (Part 3)
In this article, we will continue analyzing the algorithms of the CStrategy trading engine. The third part of the series contains the detailed analysis of examples of how to develop specific trading strategies using this approach. Special attention is paid to auxiliary algorithms — Expert Advisor logging system and data access using a conventional indexer (Close[1], Open[0] etc.)
Area method Area method
The "area method" trading system works based on unusual interpretation of the RSI oscillator readings. The indicator that visualizes the area method, and the Expert Advisor that trades using this system are detailed here. The article is also supplemented with detailed findings of testing the Expert Advisor for various symbols, time frames and values of the area.