MetaTrader 5 build 1325: Hedging option and testing on real ticks

We have added the second accounting system — hedging, which expands the possibilities of retail Forex traders

22 April 2016


  1. We have added the second accounting system — hedging, which expands the possibilities of retail Forex traders. 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.

    Opening a hedge account and viewing position accounting type
    A position accounting system is set at an account level and displayed in the terminal window header and the Journal:

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

    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:

    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 position.

    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:

    Execution of these deals resulted in opening two separate positions.

    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.

    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.

  2. In addition to hedging support, the new platform version provides wider opportunities for migrating accounts from MetaTrader 4. Now, brokers can automatically transfer accounts to MetaTrader 5, including all operations: open and pending orders, and complete trading history.

    A welcome dialog appears when first connecting to the account migrated from MetaTrader 4. Data transmission is securely encrypted during migration. To get started, specify the password of your account that you used in MetaTrader 4, and then set a new password.

    Once connected, you will be able to continue using your account, just as if it has been opened in MetaTrader 5. The complete history of all trades from MetaTrader 4 is automatically added to the new account.

    The tickets of orders and positions (including history orders) are not preserved during import, because one history record from MetaTrader 4 can be imported as up to 4 history operations in MetaTrader 5. New tickets are assigned to all trading records.

    The account numbers can be preserved or replaced depending on how the broker imports them.

  3. Added the Chat. Now, you can communicate with your friends and colleagues. The chat displays all personal messages from your MQL5 account. To start communicating, log in to your account directly from the chat window or via the platform settings: Tools -> Options -> Community.

  4. Simplified demo account creation dialog, added ability to create hedge accounts. You do not have to fill the large form any more. Simply specify basic data and select trading parameters: account type, deposit, leverage, and hedging ability.

  5. Added automatic allocation of a demo account for quick start. If the platform has no accounts yet, a demo account on the first available trade server is allocated during the launch. After successful opening, connection to the account is established immediately.

  6. Now, each position has a ticket — a unique number. It usually matches the ticket of an order used to open the position except when the ticket is changed as a result of service operations on the server, for example, when charging swaps with position re-opening. A ticket is assigned automatically to all available positions after the terminal update.

  7. Fixed setting Stop Loss and Take Profit levels when placing a market order leading to a position reversal. Until recently, no appropriate levels were set for a new position.
  8. Fixed displaying prices with four and more decimal places on the one-click trading panel elements.
  9. Fixed displaying news in the print preview window.
  10. Fixed tick chart display.
  11. Fixed opening the Market Depth after the terminal emergency shutdown.
  12. Added a check if market orders are allowed when displaying one-click trading panel control elements.
  13. Optimized profit and margin calculation in case of a large number of open orders and positions.
  14. Added translation of the user interface into Malay.
  15. Fully revised the user manual. New design, interactive screenshots and embedded videos — learn trading in MetaTrader 5 with maximum convenience:

  16. Fixed display of graphical objects in the "Chart on foreground" mode.


  1. Added ability to test trading robots and technical indicators in real tick history.

    Testing and optimization on real ticks are as close to real conditions as possible. Instead of generated ticks based on minute data, it is possible to use real ticks accumulated by a broker. These are ticks from exchanges and liquidity providers.

    To start testing or optimization in real ticks, select the appropriate mode in the strategy tester:

    Tick data has greater size compared to minute one. Downloading it may take quite a long time during the first test. Downloaded tick data is stored by months in TKC files in \bases\[trade server name]\ticks\[symbol name]\.

    Testing on real ticks
    When testing on real ticks, a spread may change within a minute bar, whereas when generating ticks within a minute, a spread fixed in the appropriate bar is used.

    If the Market Depth is displayed for a symbol, the bars are built strictly according to the last executed trade price (Last). Otherwise, the tester first attempts to build the bars by Last prices, and in case of their absence, uses Bid ones. OnTick event is triggered on all ticks regardless of whether the Last price is present or not.

    Please note that trading operations are always performed by Bid and Ask prices even if the chart is built by Last prices. For example, if an Expert Advisor using only bar open prices for trading (i.e., the built-in Moving Average) receives a signal at Last price, it performs a trade at another price (Bid or Ask depending on the direction). If "Every tick" mode is used, the bars are built by Bid prices, while trades are performed by Bid and Ask ones. The Ask price is calculated as Bid + fixed spread of a corresponding minute bar.

    If a symbol history has a minute bar with no tick data for it, the tester generates ticks in the "Every tick" mode. This allows testing the EA on a certain period in case a broker's tick data is insufficient. If a symbol history has no minute bar but the appropriate tick data for the minute is present, these ticks are ignored. The minute data is considered more reliable.

    Testing on real ticks in the MQL5 Cloud Network
    Testing on real ticks is available not only on local and remote agents, but also through the MQL5 Cloud Network. Optimization of a strategy that could take months, can be completed in a few hours using the computing power of thousands of computers.

    To test a strategy using the MQL5 Cloud Network, enable the use of cloud agents:

    Tests on real ticks using the MQL5 Cloud Network can consume a lot of data. This can significantly affect the payment for the use of the network power.
  2. Fixed an error that hindered the calculation of commission on several trading symbol types.
  3. Fixed filling Expert field for trading orders resulting from SL/TP activation according to the Expert field of the corresponding position. Previously, it was not filled.
  4. Fixed switching to usual and forward optimization results' tabs.
  5. Fixed calculation and display of the "Envelopes" indicator.
  6. Optimized visual testing.
  7. Optimized profit and margin calculation in case of a large number of open orders and positions.
  8. Optimized trading operations during high-frequency trading.
  9. Now, history synchronization is not performed if a request for non-critical symbol's properties (not requiring the current quotes) has been made. For example, SYMBOL_SELECT, SYMBOL_DIGITS, SYMBOL_SPREAD_FLOAT, SYMBOL_TRADE_CALC_MODE, SYMBOL_TRADE_MODE, SYMBOL_TRADE_STOPS_LEVEL, SYMBOL_TRADE_FREEZE_LEVEL, SYMBOL_TRADE_EXEMODE, etc. Previously, the non-critical symbol history was synchronized at any request for its property.
  10. Fixed calculation of swaps as a percentage per annum.


  1. The format of the executable EX5 files has changed to implement the new features of the MQL5 language and the new hedging option in MetaTrader 5. All EX5 applications compiled in previous builds of MetaEditor will work properly after the update, i.e. the upward compatibility is fully preserved.

    EX5 programs compiled in build 1325 and above will not run in old terminal builds - backward compatibility is not supported.

  2. Added support for abstract classes and pure virtual functions.

    Abstract classes are used for creating generic entities that you expect to use for creating more specific derived classes. An abstract class can only be used as the base class for some other class, that is why it is impossible to create an object of the abstract class type.

    A class which contains at least one pure virtual function in it is abstract. Therefore, classes derived from the abstract class must implement all its pure virtual functions, otherwise they will also be abstract classes.

    A virtual function is declared as "pure" by using the pure-specifier syntax. Consider the example of the CAnimal class, which is only created to provide common functions – the objects of the CAnimal type are too general for practical use. Thus, CAnimal is a good example for an abstract class:
    class CAnimal
                          CAnimal();     // Constructor
       virtual void       Sound() = 0;   // A pure virtual function
       double             m_legs_count;  // How many feet the animal has
    Here Sound() is a pure virtual function, because it is declared with the specifier of the pure virtual function PURE (=0).

    Pure virtual functions are only the virtual functions for which the PURE specifier is set: (=NULL) or (=0). Example of abstract class declaration and use:
    class CAnimal
       virtual void       Sound()=NULL;   // PURE method, should be overridden in the derived class, CAnimal is now abstract and cannot be created
    //--- Derived from an abstract class
    class CCat : public CAnimal
      virtual void        Sound() { Print("Myau"); } // PURE is overridden, CCat is not abstract and can be created
    //--- examples of wrong use
    new CAnimal;         // Error of 'CAnimal' - the compiler returns the "cannot instantiate abstract class" error
    CAnimal some_animal; // Error of 'CAnimal' - the compiler returns the "cannot instantiate abstract class" error
    //--- examples of correct use
    new CCat;  // no error - the CCat class is not abstract
    CCat cat;  // no error - the CCat class is not abstract
    Restrictions on abstract classes
    If the constructor for an abstract class calls a pure virtual function (either directly or indirectly), the result is undefined.
    //| An abstract base class                                           |
    class CAnimal
       //--- a pure virtual function
       virtual void      Sound(void)=NULL;
       //--- function
       void              CallSound(void) { Sound(); }
       //--- constructor
         //--- an explicit call of the virtual method
         //--- an implicit call (using a third function)
         //--- a constructor and/or destructor always calls its own functions,
         //--- even if they are virtual and overridden by a called function in a derived class
         //--- if the called function is purely virtual
         //--- the call causes the "pure virtual function call" critical execution error
    However, constructors and destructors for abstract classes can call other member functions.

  3. Added support for pointers to functions to simplify the arrangement of event models.

    To declare a pointer to a function, specify the "pointer to a function" type, for example:
    typedef int (*TFunc)(int,int);
    Now, TFunc is a type, and it is possible to declare the variable pointer to the function:
    TFunc func_ptr;
    The func_ptr variable may store the function address to declare it later:
    int sub(int x,int y) { return(x-y); }
    int add(int x,int y) { return(x+y); }
    int neg(int x)       { return(~x);  }
    func_ptr=neg;           // error: neg is not of  int (int,int) type
    Print(func_ptr(10));    // error: there should be two parameters
    Pointers to functions can be stored and passed as parameters. You cannot get a pointer to a non-static class method.

  4. MqlTradeRequest features two new fields:

    • position — position ticket. Fill it when changing and closing a position for its clear identification while trading in hedging mode. In the netting system, filling the field does not affect anything since positions are identified by a symbol name.
    • 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). The ticket is used only in the hedging system.

  5. Added TRADE_ACTION_CLOSE_BY value to the ENUM_TRADE_REQUEST_ACTIONS enumeration of trading operation types — close a position by an opposite one. The ticket is used only in the hedging system.

  6. Added trading operation tickets to the enumerations of the appropriate order, deal, and position properties:

    • Added ORDER_TICKET property to ENUM_ORDER_PROPERTY_INTEGER — order ticket. Unique number assigned to each order.
    • Added DEAL_TICKET property to ENUM_DEAL_PROPERTY_INTEGER — deal ticket. Unique number assigned to each deal.
    • Added POSITION_TICKET property to ENUM_POSITION_PROPERTY_INTEGER — position ticket. Unique number assigned to each newly opened position. It usually matches the ticket of an order used to open the position except when the ticket is changed as a result of service operations on the server, for example, when charging swaps with position re-opening. To find an order used to open a position, apply the POSITION_IDENTIFIER property. POSITION_TICKET value corresponds to MqlTradeRequest::position.

  7. Added ORDER_TYPE_CLOSE_BY value to the ENUM_ORDER_TYPE order type enumeration — close by order.
  8. Added ORDER_POSITION_BY_ID value to the ENUM_ORDER_PROPERTY_INTEGER order property enumeration — opposite position identifier for ORDER_TYPE_CLOSE_BY type orders.
  9. Added DEAL_ENTRY_OUT_BY value to the ENUM_DEAL_ENTRY deal direction enumeration — a deal is performed as a result of a close by operation.
  10. 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).

  11. Added PositionGetTicket function — return a position ticket by an index in the list of open positions and automatically select that position for further work using the PositionGetDouble, PositionGetInteger, and PositionGetString functions.
    ulong  PositionGetTicket(
       int  index      // index in the list of positions

  12. Added PositionSelectByTicket function — select an open position for further work by a specified ticket.
    bool  PositionSelectByTicket(
       ulong   ticket     // position ticket

  13. Added SYMBOL_MARGIN_HEDGED value to the ENUM_SYMBOL_INFO_DOUBLE trade symbol property enumeration — size of a contract or margin for one lot of hedged positions (oppositely directed positions at one symbol).

    • If the initial margin (SYMBOL_MARGIN_INITIAL) is specified for a symbol, the hedged margin is specified as an absolute value (in monetary terms).
    • If the initial margin is not set (equal to 0), a contract size to be used in the margin calculation is specified in SYMBOL_MARGIN_HEDGED. The margin is calculated using the equation that corresponds to a trade symbol type (SYMBOL_TRADE_CALC_MODE).

    Margin calculation for hedged positions is described in details in the MetaTrader 5 trading platform Help.

  14. Added ACCOUNT_MARGIN_MODE value to the ENUM_ACCOUNT_INFO_INTEGER account property enumeration — mode of margin calculation for the current trading account:

    • 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 hedged margin size (SYMBOL_MARGIN_HEDGED) is also considered.

  15. Added TERMINAL_SCREEN_DPI value to the ENUM_TERMINAL_INFO_INTEGER client terminal property enumeration — data display resolution is measured in dots per inch (DPI). Knowledge of this parameter allows specifying the size of graphical objects, so that they look the same on monitors with different resolution.

  16. Added TERMINAL_PING_LAST value to the ENUM_TERMINAL_INFO_INTEGER client terminal properties — the last known value of a ping to a trade server in microseconds. One second comprises of one million microseconds.

  17. Fixed return of the SendFTP function call result. Previously, FALSE was returned after a successful sending instead of TRUE.
  18. MQL5: Fixed an error in StringConcatenate function that occasionally caused "Access violation" execution error.
  19. Fixed a few errors occurred when working with template functions.
  20. Added ability to display lines exceeding 4000 characters for Print, Alert, and Comment functions.
  21. Fixed an error in ArrayCompare function that occurred when comparing an array to itself but with different initial position shift from the beginning.
  22. Added support for hedging to Standard Library:

    Added methods:

    • SelectByMagic — select position by a magic number and symbol for further work.
    • SelectByTicket — select position by a ticket for further work.

    Added methods:

    • RequestPosition — receive a position ticket.
    • RequestPositionBy — receive an opposite position ticket.
    • PositionCloseBy — close a position with the specified ticket by an opposite position.
    • SetMarginMode — set margin calculation mode according to the current account settings.

    Added overloading for the methods:

    • PositionClose — close position by ticket.
    • PositionModify — modify position by ticket.

    Changed the methods:

    • MarginMode — receive margin calculation mode. Until recently, the method worked similarly to the new StopoutMode method.
    • MarginDescription — receive margin calculation mode as a string. Until recently, the method worked similarly to the new StopoutModeDescription method.

    Added methods:

    • StopoutMode — receive minimum margin level specification mode.
    • StopoutModeDescription — receive minimum margin level specification mode as a string.

    Added methods:

    • SelectPosition — select a position for further work.

  23. Added a few improvements to the Standard Library.
  24. Fixed unloading of DLLs.
  25. Added support for template class constructors.


  1. Fixed a few trading signals showcase display errors.


  1. Fixed search of words by files in "Match Whole Word Only" mode.
  2. Added moving to a file by double-clicking on the necessary file's compilation result line.
  3. Fixed display of some control elements in Windows XP.
Updated documentation.