Binance EA Connection Library MT4 Documentation

17 March 2024, 09:32
Rajesh Kumar Nait
0
144

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

After you purchase product and install on MT4, a file Library_Binance.ex4 will be downloaded under Scripts/Market folder, You may copy and paste this file under Libraries Folder.

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, Please note : Symbols creation or History is not available in MT4 version


    Script Demo :

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

    //+------------------------------------------------------------------+
    //|                                                         test.mq4 |
    //|                                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 strict
    
    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.ex4"
    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_);
    #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)
    
    
    //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);
    
    
    }
    //+------------------------------------------------------------------+
    

    FAQs :


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

    Also make sure Symbol step size in Symbol settings is correct


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

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

    Here is the demo function

    //+------------------------------------------------------------------+
    //| Script program start function                                    |
    //+------------------------------------------------------------------+
    
    
       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);
           }
       }
    
    

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


    Share it with friends: