Adapting your MQL5 EA for trading on Binance

30 July 2023, 19:38
Andrey Khatimlianskii
0
476

If you have already completed the Configuring MetaTrader 5 and Binance account, set up  Quotes streaming and Trade Manager Utility, you can start adapting your EA code for trading on the Binance exchange.

This option is suitable if you have a trading advisor with source code, and you want to trade with it on the Binance exchange. You will need minimal programming knowledge, or the help of the person who wrote your EA for you.

Remember that you also have the option to copy trades from a demo account or trade with the free CommunityPower EA.


Switching to MT4Orders

Company NewsThe BinanceTradeConnector library, intended for communication with Trade Manager, was designed to be connected to Expert Advisors written in MT4 style (using MT4Orders library from fxsaber). In my opinion, it is convenient and allows you to handle many nuances related to trading in MT5.

If your Expert Advisor is written in pure MQL5 or uses a standard library for sending trade orders, before connecting it to BinanceTradeConnector, adapt it to MT4Orders. It is not difficult just replace all trading functions with good old OrderXXX functions from MQL4.

Converted Expert Advisor should trade exactly the same as before. Be sure to verify this with a tester and a demo account.


Downloading library files

When your Expert Advisor is ready, download the BinanceTradeConnector.zip archive and extract it to the MQL5 directory of the terminal where you are developing (File  Open Data Folder).


Connecting to EA

After saving the libraries, open your EA file and add the necessary code.

1. At the very beginning, before the input-parameters block, add an override of the OrderCalcMargin function and include the necessary libraries (MT4Orders should already be connected):

// Redefining of margin calculation
#define OrderCalcMargin BinanceTradeManager.GetMargin

#include <fxsaber\MT4Orders.mqh> // https://www.mql5.com/ru/code/16006
#include <Binance\BinanceTradeConnector.mqh>


2. At the very beginning of the OnInit function, initialize the library:

int OnInit()
{
        if ( !BinanceConnector.Init() )
                return(INIT_FAILED);

        // your OnInit code here

Note that any initialization error (e.g. if Trade Manager is not running) will cause the EA to be removed from the chart.
You can change this behavior, but then take care that the library is initialized before use.


3. At the end of the OnDeinit function, add a library deinitialization line:

void OnDeinit(const int reason)
{
        // your OnDeinit code here
        ...

        BinanceConnector.Deinit( reason );
}


4. At the beginning of the OnTick function, call the method to update the market information:

void OnTick()
{
        BinanceConnector.Tick();

        // your OnTick code here
        ...


5. Wherever lot size is calculated to open or close a trade, add a call to BinanceConnector.CorrectLotSize() to normalize for the current instrument price:

        double lot = your_lot_calc_function();          // Your lot calculation func
        lot = BinanceConnector.CorrectLotSize( lot );   // Correction by current min allowed lot
        OrderSend( _Symbol, OP_BUY, lot, Ask, 100, 0.0, 0.0, "crypro", 12345 );

If the EA uses pending orders, use the function overload with the order price:

        double op = Ask - 100*_Point;
        double lot = BinanceConnector.CorrectLotSize( _Symbol, InputFixedLot, op );
        OrderSend( _Symbol, OP_BUYLIMIT, lot, op, 100, 0.0, 0.0, "crypro", 12345 );


6. At the end of the OnTick function, add a call to the CheckForChanges method to synchronize the trading environment with the exchange:

        // your OnTick code here
        ...

        BinanceConnector.CheckForChanges();
}


7. If your EA has a GUI (panel, buttons), or other events that can lead to trade operations (mouse click, timer, line movement, or any other), add a call to the CheckForChanges method right after the handler of this event. For example, this is how the code of the OnChartEvent function of my EA looks like, which allows opening positions using buttons on the chart:

// For EAs with GUI that can initiate trade command
void OnChartEvent ( const int id, const long &lparam, const double &dparam, const string &sparam )
{
        GUI.ChartEvent( id, lparam, dparam, sparam );
        BinanceConnector.CheckForChanges();
}

The rule is simple: after any OrderSend you should call CheckForChanges as soon as possible, this will give the command to synchronize with the exchange.

Congratulations! This completes the work with the code!


Internal structure and constraints

By connecting BinanceTradeConnector.mqh to the Expert Advisor, you virtualize the entire trading environment using the Virtual library from fxsaber. That is, the Expert Advisor starts trading virtually.

Whenever there is a change in the trading environment, it is sent to the Trade Manager, which in turn summarizes all the data received and synchronizes it with the trading environment of your Binance account. This allows you to trade multiple EAs on the same instrument, including multidirectional trades, pending orders and SL/TPs. In addition, it allows you to plug in the library with a few lines of code without changing the existing EA code.


But this is where the main limitation of the library comes from mono-currency and isolation from other Expert Advisors. You cannot trade several coins at once from one EA (OrderSend for a "non-native" instrument will not work properly), nor can you see positions and orders of other EAs trading on your account.

I hope to overcome both of these limitations in the future, but I am not ready to give a timeline at the moment.


The next important limitation is the non synchronization of SL and TP, they are sent as market orders when triggered.


The next shortcoming is the limited information on account state.

At the moment, each Expert Advisor can see its own Balance only (and therefore margin, free margin, and other account information). Take this into account if you have a small amount of funds on your account - if one Expert Advisor trades profitably and the other is unprofitable, their balance does not change in total, but the unprofitable one may run out of funds to open new positions. Or the lot will be different if it is calculated based on the balance or free margin.

Use the Custom account balance parameter to set any starting virtual balance for each Expert Advisor. Synchronization of account information between Expert Advisors is planned for the near future.


Using virtual trading adds another inconvenience: if you close a chart with an Expert Advisor that has open trades, they will remain open. TradeManager will take them into account during synchronization, and even if you close them on the exchange site, TradeManager will instantly restore them.

This is not a problem if your EA has its own GUI that allows you to close trades manually, but not every EA has such a GUI. Besides, the virtual environment is saved with binding to a unique chart Id, so if you accidentally close the chart and try to run the Expert Advisor on a new chart, it will not see the previous virtual environment (even if you give it the same Magic number).

If you find yourself in this situation:

  • stop Trade Manager (or close the terminal),
  • open File - Data Folder, go to "\MQL5\Files\BinanceTradeManager\",
  • delete the file corresponding to the appropriate virtual environment (e.g. "ETHBUSD.bnf_128968168864101582.virt", you will have to determine "appropriate" empirically 😜),
  • then start Trade Manager again, it will "forget" the deleted virtual environment, and immediately close the forgotten position.

Of course, you can always just stop Trade Manager and close a position manually. But this option is suitable only if you do not plan to continue using Trade Manager.

If you know of any other specifics that I forgot to mention, email me about it and I'll update the article.


Detailed MetaTrader 5 to Binance connection guide you can find here.
Do not hesitate to ask any questions you have personally, or in the official support group.


Share it with friends: