Binance EA Connection Library Documentation for MT5

23 December 2023, 18:42
Rajesh Kumar Nait
0
368

Product URL  : https://www.mql5.com/en/market/product/110442

URL:


Spot:

  • For testnet API is : testnet.binance.vision
  • For LIVE MODE API is: api.binance.com


  • Futures:

  • For testnet API is testnet.binancefuture.com
  • For LIVE MODE API is: fapi.binance.com

  • Tutorial 1 : Trading Operations


    Script Demo :

    Note : Once you purchased the Library, It will be found under Scripts/Market Folder, Copy the file "Library_Binance.ex5" and paste it under Libraries Folder then Go to MT5 IDE and Create a New script and copy paste the sample script and uncomment any line to test api calls.

    ///+------------------------------------------------------------------+
    //|                                              Library_Binance.mq5 |
    //|                                Copyright 2024, Rajesh Kumar Nait |
    //|                  https://www.mql5.com/en/users/rajeshnait/seller |
    //+------------------------------------------------------------------+
    #property copyright "Copyright 2024, Rajesh Kumar Nait"
    #property link      "https://www.mql5.com/en/users/rajeshnait/seller"
    #property version   "1.00"
    #property description "Uncomment code as required"
    
    
    
    
    
    
    
    
    
    struct BinanceConfig {
       string            api_url;
       string            api_key;
       string            api_secret;
       string            api_suffix;
       string            symbol_prefix;
       bool              debug;
       bool              spot_mode;
    };
    
    
    #import "..\Libraries\Library_Binance.ex5"
    void Binance_Init(BinanceConfig &config);
    //+------------------------------------------------------------------+
    //| Limit Orders                                                     |
    //+------------------------------------------------------------------+
    
    //+------------------------------------------------------------------+
    //|                                                                  |
    //+------------------------------------------------------------------+
    string orderLimit(string symbol, string side, double quantity, double price, string timeInForce_, string recvWindow_,  string reduceOnly_);
    string modifyorderLimit(string symbol, long oid, string side, double quantity, double price, string recWindow_);
    
    //+------------------------------------------------------------------+
    //| Market Orders                                                    |
    //+------------------------------------------------------------------+
    
    //+------------------------------------------------------------------+
    //|                                                                  |
    //+------------------------------------------------------------------+
    string orderMarket(string symbol, string side, double quantity, string recWindow_,  string reduceOnly_);
    string orderStopMarket(string symbol,string side,double quantity,double stopPrice, string workingtype, string recWindow_, string reduceOnly_, string priceProtect_);
    string orderTakeProfitMarket(string symbol,string side,double quantity,double stopPrice, string workingtype, string recWindow_,  string reduceOnly_, string priceProtect_);
    string orderStopLimit(string symbol,string side,double quantity,double stopPrice,double price, string workingtype, string recWindow_, string reduceOnly_, string priceProtect_);
    string orderTakeProfitLimit(string symbol,string side,double quantity,double stopPrice,double price, string workingtype, string recWindow_,  string reduceOnly_, string priceProtect_);
    
    //+------------------------------------------------------------------+
    //| Hedge Mode (for futures)                                         |
    //+------------------------------------------------------------------+
    
    //+------------------------------------------------------------------+
    //|                                                                  |
    //+------------------------------------------------------------------+
    string orderLimit_hedge(string symbol, string side, string positionSide, double quantity, double price, string timeInForce_, string recvWindow_);
    string orderMarket_hedge(string symbol, string side, string positionSide, double quantity, string recWindow_);
    string orderStopMarket_hedge(string symbol,string side, string positionSide, double quantity,double stopPrice, string workingtype, string recWindow_, string priceProtect_);
    string orderTakeProfitMarket_hedge(string symbol,string side, string positionSide, double quantity,double stopPrice, string workingtype, string recWindow_,  string priceProtect_);
    string orderStopLimit_hedge(string symbol,string side, string positionSide, double quantity, double stopPrice,double price, string workingtype, string recWindow_, string priceProtect_);
    string orderTakeProfitLimit_hedge(string symbol,string side, string positionSide, double quantity, double stopPrice, double price, string workingtype, string recWindow_, string priceProtect_);
    
    //+------------------------------------------------------------------+
    //| Cancel Order                                                     |
    //+------------------------------------------------------------------+
    
    //+------------------------------------------------------------------+
    //|                                                                  |
    //+------------------------------------------------------------------+
    string CancelOrder(string symbol, long orderId, string recWindow_);
    string CancelAllOpenOrder(string symbol, string recWindow_);
    
    
    //+------------------------------------------------------------------+
    //| Order queries                                                    |
    //+------------------------------------------------------------------+
    
    //+------------------------------------------------------------------+
    //|                                                                  |
    //+------------------------------------------------------------------+
    string QueryPositionMode(string recWindow_);
    string QueryMultiAssetMode(string recWindow_);
    string QueryOrderwithID(string symbol, long orderid, string recWindow_);
    string CurrentOpenOrder(string symbol,long orderid, string recWindow_);
    string CurrentAllOpenOrders(string symbol,string recWindow_);
    
    //+------------------------------------------------------------------+
    //| Balance and Account Info                                         |
    //+------------------------------------------------------------------+
    
    //+------------------------------------------------------------------+
    //|                                                                  |
    //+------------------------------------------------------------------+
    string GetFuturesBalance(string recWindow_);
    string GetAccount_Futures(string recWindow_);
    string GetAccount_Spot(string recWindow_);
    //+------------------------------------------------------------------+
    //| Change Leverage and Margin (Futures)                             |
    //+------------------------------------------------------------------+
    string changeLeverage(string symbol,int leverage, string recWindow_);
    string changeMargin(string symbol,string marginType, string recWindow_);
    
    //+------------------------------------------------------------------+
    //| Position Info (Futures)                                          |
    //+------------------------------------------------------------------+
    string positionRisk(string symbol, string recWindow_);
    
    //+------------------------------------------------------------------+
    //| Create Symbols                                                   |
    //+------------------------------------------------------------------+
    void CreateSymbols_Binance_Futures();
    void CreateSymbols_Binance_Spot();
    
    //+------------------------------------------------------------------+
    //| Update Historical Data from API                                  |
    //+------------------------------------------------------------------+
    void RunUpdate_Spot(string symbol, datetime StartDateTime);
    void RunUpdate_Futures(string symbol, datetime StartDateTime);
    #import
    
    
    bool Binance_debug = true; // Debug will print messages in expert tab for troubleshooting
    //+------------------------------------------------------------------+
    //| Config Spot                                                      |
    //+------------------------------------------------------------------+
    
    bool Spot_Mode = false; // Spot Mode? True : Spot, False : Futures
    string Binance_Key     = ""; //Binance Spot's API key
    string Binance_Secret  = ""; //Binance Spot's API secret
    string Binance_URL  = "https://api.binance.com"; // API URL
    string Binance_suffix = "/api/v3/"; // API Suffix (Do not edit)
    string Binance_SymbolPrefix = "bs_"; // Symbol Prefix for Spot
    
    //+------------------------------------------------------------------+
    //| Config Futures                                                   |
    //+------------------------------------------------------------------+
    
    //bool   Binance_debug   = true;
    //string Binance_Key     = ""; //Binance Future's API key
    //string Binance_Secret  = ""; //Binance Future's API secret
    //string Binance_URL     = "https://fapi.binance.com"; // For Testing : https://testnet.binancefuture.com For Real Mode : https://fapi.binance.com
    //string Binance_suffix  = "/fapi/v1/"; // API Suffix (Do not edit)
    //string Binance_SymbolPrefix = "a_"; /.Symbol Prefix for Futures
    
    //+------------------------------------------------------------------+
    //|  Other Config                                                    |
    //+------------------------------------------------------------------+
    //+---------------------------------------------------------------------+
    //| Please Note                                                         |
    //| reduceonly,priceprotect and working_type not effective for SPOT API |                                                               |
    //+---------------------------------------------------------------------+
    
    string timeInForce="GTC";   // Used for LIMIT ORDER, // Values can be GTC, IOC, FOK, GTX or GTD, default = GTC
    string reduceOnly="true";   // reduceOnly (Only for Futures)
    string priceProtect="true"; // Used with STOP/STOP_MARKET or TAKE_PROFIT/TAKE_PROFIT_MARKET (Only for Futures)
    string recvWindow="2000";   // Used for All type of requests
    string working_Type = "CONTRACT_PRICE"; // "CONTRACT_PRICE" or "MARK_PRICE" (Only for Futures)
    
    //+------------------------------------------------------------------+
    //| Symbols and Chart                                                |
    //+------------------------------------------------------------------+
    
    datetime MaxDate= D'2023-12-20 00:00:00';//Max Datetime for History
    
    string sym;
    //Init API
    BinanceConfig config;
    
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnStart() {
    //---
    
       config.api_url = Binance_URL;
       config.api_key = Binance_Key;
       config.api_secret = Binance_Secret;
       config.api_suffix = Binance_suffix;
       config.symbol_prefix = Binance_SymbolPrefix;
       config.debug = Binance_debug;
       config.spot_mode = Spot_Mode;
    
       Binance_Init(config);
    
    //Add your codes here
    
    //+------------------------------------------------------------------+
    //| Get info of MODES                                                |
    //+------------------------------------------------------------------+
    
    // 1. Get Current Position Mode : Receive Window, Futures API, Futures Secret, API URL, API Suffix
    //QueryPositionMode(recvWindow);
    
    // 2. Get Multi Asset Mode : Receive Window, Futures API, Futures Secret, API URL, API Suffix
    //QueryMultiAssetMode(recvWindow);
    
    //+------------------------------------------------------------------+
    //| ORDER PLACEMENT                                                  |
    //+------------------------------------------------------------------+
    
    //+------------------------------------------------------------------+
    //| LIMIT ORDERS                                                     |
    //+------------------------------------------------------------------+
    
    //1. Send Limit Order : Symbol,Side,Size,Price,Time in Force,Receive Window,Reduce Only
    //  orderLimit(sym,"BUY",0.1,43550.0,timeInForce,recvWindow,reduceOnly);
    
    //2. Modify Limit Order : Symbol,Order ID of Order to be modified,Side,Size,Modification Price,Receive Window,Reduce Only
    //modifyorderLimit(sym,3576120549,"BUY",0.1,43450.1,recvWindow,reduceOnly);
    
    //3. Send Stop Limit Order : Symbol,Side,Size,Stop Price,Trigger Price,Working Type,Receive Window, Reduce Only, Price Protect
    //orderStopLimit(sym,"BUY",0.1,43970.0,43972.0,working_Type,recvWindow,reduceOnly,priceProtect);
    
    
    //4. Send Take Profit Limit Order : Symbol,Side,Size,Take Profit Price,Trigger Price,Working Type,Receive Window, Reduce Only, Price Protect
    //orderTakeProfitLimit(sym,"BUY",0.1,43600.0,43602.5,working_Type,recvWindow,reduceOnly,priceProtect);
    
    
    //+------------------------------------------------------------------+
    //| MARKET ORDERS                                                    |
    //+------------------------------------------------------------------+
    
    //1. Send Market Order : Symbol,Side,Size,Receive Window,Reduce Only
    //orderMarket(sym,"BUY",0.1,recvWindow,reduceOnly);
    
    //2. Send Stop Market Order : Symbol, Side,Size, Stop Price, Working Type, Receive Window, Reduce Only, Price Protect
    //orderStopMarket(sym,"BUY",0.1,43838.1,working_Type,recvWindow,reduceOnly,priceProtect);
    
    //2. Send Take Profit Market Order : Symbol,Side,Size,Take Profit Price,Working Type,,Receive Window, Reduce Only, Price Protect
    //orderTakeProfitMarket(sym,"BUY",0.1,42838.1,working_Type,recvWindow,reduceOnly,priceProtect);
    
    //+------------------------------------------------------------------+
    //| Hedge mode : LIMIT ORDERS  LONG or SHORT                        |
    //+------------------------------------------------------------------+
    
    //1. Send Limit Order : Symbol,Side,PositionSide,Size,Price,Time in Force,Receive Window
    //orderLimit_hedge(sym,"BUY","LONG",0.1,71250.0,timeInForce,recvWindow);
    
    //2. Send Stop Limit Order : Symbol,Side,PositionSide,Size,Stop Price,Trigger Price,Working Type,Receive Window, Price Protect
    //orderStopLimit_hedge(sym,"BUY","LONG",0.1,43970.0,43972.0,working_Type,recvWindow,priceProtect);
    
    //3. Send Take Profit Limit Order : Symbol,Side,PositionSide,Size,Take Profit Price,Trigger Price,Working Type,Receive Window, Price Protect
    //orderTakeProfitLimit_hedge(sym,"BUY","LONG",0.1,43600.0,43602.5,working_Type,recvWindow,priceProtect);
    
    
    //+------------------------------------------------------------------+
    //| Hedge mode : MARKET ORDERS  LONG or SHORT                        |
    //+------------------------------------------------------------------+
    
    //1. Send Market Order : Symbol,Side,PositionSide,Size,Receive Window
    //orderMarket_hedge(sym,"SELL","SHORT",0.1,recvWindow);
    
    //2. Send Stop Market Order : Symbol, Side,PositionSide, Size, Stop Price, Working Type, Receive Window, Price Protect
    //orderStopMarket_hedge(sym,"SELL","SHORT",0.1,43838.1,working_Type,recvWindow,priceProtect);
    
    //2. Send Take Profit Market Order : Symbol,Side,PositionSide,Size,Take Profit Price,Working Type,,Receive Window,Price Protect
    //orderTakeProfitMarket_hedge(sym,"SELL","SHORT",0.1,42838.1,working_Type,recvWindow,priceProtect);
    
    
    //+------------------------------------------------------------------+
    //| CANCEL ORDERS                                                    |
    //+------------------------------------------------------------------+
    
    //1. Cancel All Open Orders : Orders which are placed but not executed : Symbol,Receive Window
    // CancelAllOpenOrder(sym,recvWindow);
    
    //2. Cancel any single Open Order with Order ID : Symbol, Order ID, Receive Window
    //CancelOrder(sym,3576120549,recvWindow);
    
    //+------------------------------------------------------------------+
    //|  ACCOUNT INFO                                                    |
    //+------------------------------------------------------------------+
    
    //1 : Query Account Info : Receive Window
    //GetAccount_Futures(recvWindow);
    
    //2 : Query Fututres Balance : Receive Window
    //GetFuturesBalance(recvWindow);
    
    //3 : Query Account Info : Receive Window
    //GetAccount_Spot(recvWindow);
    
    
    //+------------------------------------------------------------------+
    //| QUERY ORDERS                                                     |
    //+------------------------------------------------------------------+
    
    
    //1. Query Order with ID : Symbol, Order ID, Receive Window
    // QueryOrderwithID(sym,3575360312,recvWindow);
    
    //2. Query Current Open Order :  Symbol, Receive Window
    //CurrentOpenOrder(sym,3576155883,recvWindow);
    
    //3. Query Current All Open Orders :  Symbol, Receive Window
    //CurrentAllOpenOrders(sym,recvWindow);
    
    
    //+------------------------------------------------------------------+
    //| CHANGE                                                           |
    //+------------------------------------------------------------------+
    
    //1. Change Leverage :  Symbol, Leverage, Receive Window
    //changeLeverage(sym,125,recvWindow);
    //2. Change Margin :  Symbol, Margin Type CROSSED or ISOLATED, Receive Window
    //changeMargin(sym,"CROSSED",recvWindow);
    
    
    //+------------------------------------------------------------------+
    //| POSITION INFO                                                    |
    //+------------------------------------------------------------------+
    
    //1. Position info
    //positionRisk(sym,recvWindow);
    
    //+------------------------------------------------------------------+
    //| CHARTS                                                           |
    //+------------------------------------------------------------------+
    
    //1. Create Symbols (MUST RUN ONLY ONCE) :
    // CreateSymbols_Binance_Spot();
    //CreateSymbols_Binance_Futures();
    
    //2. Run History Updater SPOT : Symbol, Max Date for History
    //RunUpdate_Spot(sym, MaxDate);
    
    //3. Run History Updater FUTURES : Symbol, Max Date for History
    // RunUpdate_Futures(sym, MaxDate);
    
    }
    
    //+------------------------------------------------------------------+
    //|                                                                  |
    //+------------------------------------------------------------------+
    string RemovePrefixFromSymbol() { // example of removal 2 digit symbol prefix, adjust as needed
    //---
       sym = _Symbol;
       string prefix = "a_"; // in case of spot its bs_ else a_ for Futures (Change as required)
       int length = 2; // length of prefix is 2 in case of Futures and 3 in case of Spot (Change as required)
       string resultString;
    
       if(StringSubstr(sym, 0, length) == prefix) {
          resultString = StringSubstr(sym, length);
          return resultString;
       } else {
          resultString = sym;
          return NULL;
       }
    
    // Output the result for testing
    //Print("Result String: ", resultString);
    
       return NULL;
    
    }
    //+------------------------------------------------------------------+
    


    FAQs :


    1. How to remove symbol prefix from my symbol when sending order to binance? if symbol prefix is a_BTCUSDT, when sending order via API you should send "BTCUSDT" only

    here is the script tutorial to remove prefix from your symbol

    void OnStart() {
    //---
       string sym = _Symbol;
       string prefix = "bs_"; // in case of spot its bs_
       int length = 3; // length of prefix is 3 character
       string resultString;
    
    // Check if the original string starts with "a_"
       if (StringSubstr(sym, 0, length) == prefix) {
          // Remove the "a_" prefix
          resultString = StringSubstr(sym, length);
       } else {
          // If the string doesn't start with "a_", keep the original string
          resultString = sym;
       }
    
    // Output the result
       Print("Original Symbol: ", sym);
       Print("Result String: ", resultString);
    }


    2. How do i run chart to be updated every few seconds via API?

    Binance recommends to update chart via Websocket which is available on product Crypto Charting because API is not for real time chart and running it too frequently may result in temporary IP ban by Binance, but if you wish not to use it and update history via API

    here is how you can do it by adding this on your EA.

    #property copyright "Copyright 2024, MetaQuotes Ltd."
    #property link      "https://www.mql5.com"
    #property version   "1.00"
    
    int updatetime = 60;// Chart Update time in seconds
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit() {
    //--- create timer
       EventSetTimer(1);
    //---
       return(INIT_SUCCEEDED);
    }
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    void OnDeinit(const int reason) {
    //--- destroy timer
       EventKillTimer();
    
    }
    
    //+------------------------------------------------------------------+
    //| Timer function                                                   |
    //+------------------------------------------------------------------+
    void OnTimer() {
    //---
       while(!IsStopped()) {
          datetime now = TimeGMT();
          static datetime UpdateTime = now;
          if(UpdateTime==now) {
             datetime mydate = iTime("f_ETHUSDT",PERIOD_M1,2);
    
             //3. Run History Updater FUTURES : Symbol, Symbol Prefix, API URL, API Suffix, Max Date for History
             RunUpdate_Futures("ETHUSDT", "f_", FAPI, apisuffix, mydate);
    
             Print("Update Done");
             UpdateTime=now + updatetime; // wait for next 60 seconds before next update of 1 minute bar
          }
       }
    }
    //+------------------------------------------------------------------+
    

    3. My orders are not being sent due to invalid volume error, Whats wrong?

    Can you verify if your symbol volume step is correct, for e.g. for exchange Binance Futures, Symbol Volume step is called qunatityPrecision and can be verified for each symbol in this URL

    You need to check and verify 4 of these section and you can manually edit it correctly from Symbols option in MT5

    Minimal Maximal Volume - If your EA checks for these, make sure they are correct

    Volume Step : In Binance Futures this is called "qunatityPrecision" and can be verified for each symbol at following URL

    Volume Limit: Your order should be less than allowed Volume.

    Digits : Binance API may show some incorrect digits info of symbols in API URL of ExchangeInfo. For example SOLUSDT having 3 digits but API mentions 4 digit, so sending order details with wrong info may get order rejected, So make sure you verify symbol digits using Binance app, if you open SOLUSDT in Binance app you will always see price in correct digit which is 3 for SOLUSDT.

    I keep updating correct digits symbols file here which can be imported and may save you some time with editing digits, but you still need to verify it.

    Here is attached GIF to guide you how to edit Symbol Volume step and other info on Custom symbol. You may lose historical data while editing some elements on chart e.g. Digits, as mentioned on MQL5 documentation on Custom Symbols, if you edit symbol in some cases, so you may be required to load data again and everything will be okay.

    ----------------------------------------------------------------------------------------------------------

    4. I am getting wrong Lot size calculation while calculating lot size for my EA, I use Google to calculate USD rates. What I am doing wrong?

    You should calculate Lot size as per Binance rules only. Here are links to Binance Leveraged Margin Table which mentions Maintenance Margin as per your position size. You should deduct Maintenance margin from your position size. Also you must be interested in Liquidation Calculation logic to be implemented in your EA

    Example : First go to Binance App and select leverage you wish e.g. 125x

    then lets suppose your account balance is $33.69 and BTCUSDT price is 59169.3

    then check how much qty you can buy, in this case as per price in screenshot you can see I can buy 0.071 max qty

    so make sure your calculation is either 0.071 or below then your EA will be placing order without any issue.


    ------------------------------------------------------------------------------------------

    5. How do i check my USDT balance using EA Connector library?

    Here is the script demo function. Note: It will require you to download and add file "JAson.mqh" in include folder which you can find on codebase

    #include<JAson.mqh>
    CJAVal jv_(NULL, jtUNDEF);   
    string s = GetFuturesBalance(recvWindow);
       jv_.Deserialize(s);
    
       for(int i=0; i<jv_.Size(); i++) {
    
          string asset = jv_[i]["asset"].ToStr();
          double bal = jv_[i]["balance"].ToDbl();
    
    
          if(asset=="USDT"){ // if you want to check balance for USDT asset
             double balance = NormalizeDouble(bal,2);
             Print("Balance ",balance);
           }
       }
    
    

    5. API function returns empty string in Spot Mode.

    Please check you are using correct functions for Spot mode in Binance

    List of functions supported in Spot
    orderLimit
    orderStopLimit
    orderTakeProfitLimit
    orderMarket
    orderStopMarket
    orderTakeProfitMarket

    CancelOrder
    CancelAllOpenOrder

    QueryOrderwithID
    CurrentAllOpenOrders
    GetAccount_Spot

    Files:
    Share it with friends: