← All EA examples
1017 / MQL5 / USDⓈ-M FUTURES

How can MQL5 query Binance USD-M futures account balances V3?

Call ufFuturesAccountBalanceV3 to retrieve account asset balances. This example traverses the assets for balance, cross wallet balance, unrealized PnL, available balance and maximum withdrawal amount, then prints the asset, balance and available balance for nonempty asset records.

What do you need to use this example?

  • Install and configure MT5 Binance and API credentials. Make mt5binance.mqh, JAson.mqh and the account permissions required by this example available.
  • Enable futures balance access for the API key. No trading symbol is passed, so results are account assets rather than chart-symbol-specific balances.

How does the source execute?

  1. On each tick, call ufFuturesAccountBalanceV3 with handles, recvWindow and the response buffer.
  2. Convert and parse the returned array, reading accountAlias, asset, balance and related fields.
  3. For records with a nonempty asset name, print balance and availableBalance. Other fields are read into local variables.

Requests run on every OnTick without an effective one-shot guard. Frequency follows ticks received by the chart.

Parameters and execution behavior

ParameterSource value or behavior
Main interfaceufFuturesAccountBalanceV3
ScopeAssets returned for the account
VersionV3
Balance fieldsbalance / crossWalletBalance / availableBalance
Other fieldscrossUnPnl / maxWithdrawAmount / updateTime
Request timing windowrecvWindow = 3000 ms
Execution triggerRequests run on every OnTick without an effective one-shot guard. Frequency follows ticks received by the chart.

Related guides and examples

Full MQL5 source code

//+------------------------------------------------------------------+
//|币安U本位期货查看账户余额binanceUSDMarginFutureQueryAccountBalance.mq5|
//|                                  Copyright 2024, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

//import MQL binance API 引入币安MQL接口的头文件
// 按资产读取 V3 合约账户余额和可用金额。
// Read V3 Futures account balances and available amounts by asset.
// 引入币安 MQL 接口声明,调用方式以本文件现有接口签名为准。
// Include the Binance MQL API declarations and use the API signatures present in this file.
#include <mt5binance.mqh>

//import mql5.com open source json library to deserialize binance reponse json https://www.mql5.com/en/code/13663
//引入mql5.com上的开源json library反序列化币安返回的json数据  https://www.mql5.com/zh/code/13663
// 使用 JAson.mqh 的 CJAVal 解析同步响应和异步事件 JSON。
// Use CJAVal from JAson.mqh to parse synchronous responses and asynchronous event JSON.
#include <JAson.mqh>

string symbol=Symbol();

//setup Timing security https://developers.binance.com/docs/derivatives/usds-margined-futures/general-info#timing-security
//设置时间同步安全 https://developers.binance.com/docs/zh-CN/derivatives/usds-margined-futures/general-info#%E6%97%B6%E9%97%B4%E5%90%8C%E6%AD%A5%E5%AE%89%E5%85%A8
// 请求时间窗口为 3000 毫秒,币安按请求时间戳与服务器时间检查请求时效。
// The request timing window is 3000 milliseconds. Binance validates request timing against its server time.
long recvWindow=3000;

//币安MQL接口使用的curl handles
// 保存币安请求使用的 curl 句柄,供接口调用复用。
// Store curl handles for reuse by Binance API calls.
int handles[];

//binance reponse 币安返回数据
// 同步响应缓冲区,API 调用将返回数据写入此字符数组。
// Synchronous response buffer populated by API calls.
static char resultChar[];

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
// EA 加载时由 MT5 调用,执行本例所需的初始化。
// MT5 calls this handler when the EA is loaded to perform initialization required by this example.
int OnInit()
  {
   // 初始化配置中已设置的币安 API 凭据,供后续签名请求使用。
   // Initialize the configured Binance API credentials for subsequent signed requests.
   initBinanceAPIKey();
   // 初始化 curl 全局状态,后续分配句柄数组并创建请求句柄。
   // Initialize global curl state before allocating the handle array and creating request handles.
   curlGlobalInit();
   ArrayResize(handles, 1);
   curlInit(handles);

   // 为返回 JSON 分配缓冲区,响应长度需要在分配容量内。
   // Allocate a response buffer large enough to hold the returned JSON.
   ArrayResize(resultChar, 10000);
   
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
// EA 卸载或重新初始化前调用,reason 为卸载原因;清理操作以函数体为准。
// Called before EA removal or reinitialization. reason identifies the cause, and the function body defines the cleanup performed.
void OnDeinit(const int reason)
  {
//---
   // 释放本例创建的 curl 请求句柄。
   // Release the curl request handles created by this example.
   curlCleanUp(handles);

   printf("curlCleanUp");
  }


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
// 每次收到行情都会执行函数体中的请求流程,本函数未使用一次性运行判断。
// Each tick executes the request sequence in this handler, which has no one-shot execution guard.
void OnTick()
  {

//Get futures account balance V3  查看账户余额V3
   // 查询 U 本位合约 V3 账户余额,返回数组按资产分别列出余额及可用金额。
   // Query USDⓈ-M Futures V3 account balances, returning balance and available-amount information for each asset.
   // 此处使用 handles 发起请求,并通过最后一个引用参数 resultChar 接收同步响应。
   // Use handles for the request and receive the synchronous response through the final reference parameter resultChar.
   ufFuturesAccountBalanceV3(handles, recvWindow, resultChar);
   // 按 UTF-8 将同步响应字符数组转换为 MQL 字符串。
   // Convert the synchronous response character array to an MQL string using UTF-8.
   string result=CharArrayToString(resultChar, 0, -1, CP_UTF8);

   CJAVal jBalances;
   // 解析 JSON 供后续按字段名读取;本例此处未检查解析函数的返回值。
   // Deserialize JSON for subsequent field access. This example does not check the parser return value here.
   jBalances.Deserialize(result);

   // 读取 code 错误码字段;成功响应的字段结构由各接口决定,后续按本例条件处理。
   // Read the code error field. Successful response structures depend on the endpoint and are handled by the conditions below.
   string code=jBalances["code"].ToStr();

   if(jBalances.Size()>0)
     {
      // 逐项遍历返回数组,读取每条记录。
      // Iterate through the returned array and read each record.
      for(int i=0; i<jBalances.Size(); i++)
        {
         CJAVal jBalance=jBalances[i];

         // 读取 accountAlias 字段,表示账户唯一识别码,使用 ToStr 转换。
         // Read accountAlias for unique account alias using ToStr.
         string accountAlias=jBalance["accountAlias"].ToStr();//unique account code 账户唯一识别码
         // 读取 asset 字段,表示资产名称,使用 ToStr 转换。
         // Read asset for asset name using ToStr.
         string asset=jBalance["asset"].ToStr();//asset name 资产
         // 读取 balance 字段,表示钱包余额,使用 ToStr 转换。
         // Read balance for wallet balance using ToStr.
         string balance=jBalance["balance"].ToStr();//wallet balance 总余额
         // 读取 marginAvailable 字段,表示是否可用作联合保证金,使用 ToStr 转换。
         // Read marginAvailable for whether the asset is available as margin in Multi-Assets Mode using ToStr.
         string marginAvailable=jBalance["marginAvailable"].ToStr();//whether the asset can be used as margin in Multi-Assets mode 是否可用作联合保证金
         // 读取 crossWalletBalance 字段,表示全仓钱包余额,使用 ToStr 转换。
         // Read crossWalletBalance for cross wallet balance using ToStr.
         string crossWalletBalance=jBalance["crossWalletBalance"].ToStr();//crossed wallet balance 全仓余额
         // 读取 crossUnPnl 字段,表示全仓未实现盈亏,使用 ToStr 转换。
         // Read crossUnPnl for unrealized profit or loss of cross-margin positions using ToStr.
         string crossUnPnl=jBalance["crossUnPnl"].ToStr();//unrealized profit of crossed positions 全仓持仓未实现盈亏
         // 读取 availableBalance 字段,表示可用余额,使用 ToStr 转换。
         // Read availableBalance for available balance using ToStr.
         string availableBalance=jBalance["availableBalance"].ToStr();//available balance 下单可用余额
         // 读取 maxWithdrawAmount 字段,表示最大可转出金额,使用 ToStr 转换。
         // Read maxWithdrawAmount for maximum withdrawable amount using ToStr.
         string maxWithdrawAmount=jBalance["maxWithdrawAmount"].ToStr();//maximum amount for transfer out 最大可转出余额
         // 读取 updateTime 字段,表示更新时间戳,使用 ToStr 转换。
         // Read updateTime for update timestamp using ToStr.
         string updateTime=jBalance["updateTime"].ToStr();//update time 更新时间
         if(asset!="")
           {
            printf("Futures Account Balance V3: asset %s , balance %s , availableBalance %s", asset, balance, availableBalance);
           }


        }
     }
  }
//+------------------------------------------------------------------+