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

How can MQL5 query Binance account trade history?

Call ufQueryAccountTradeList to retrieve account fills for the chart symbol. This example sets a limit of 100, then reads and prints trade IDs, order IDs, fill prices, quantities, commission and realized PnL.

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.
  • Select the contract chart to query. The endpoint returns account fills rather than unfilled orders. This example requests up to 100 records and does not paginate further.

How does the source execute?

  1. On the first tick, call ufQueryAccountTradeList for the chart symbol with zero order, time and starting filters and limit=100.
  2. Deserialize the returned array with CJAVal and traverse the fills.
  3. Print quantity, quote quantity, commission asset, realized PnL, buyer and maker flags and time, then set isRun=true.

Run on the first tick of this attachment; isRun then prevents repetition. Reloading may execute it again.

Parameters and execution behavior

ParameterSource value or behavior
Main interfaceufQueryAccountTradeList
SymbolSymbol()
Filter arguments0 / 0 / 0 / 0
Limit100
Fill fieldsid / orderId / price / qty / commission / realizedPnl
Request timing windowrecvWindow = 3000 ms
Execution triggerRun on the first tick of this attachment; isRun then prevents repetition. Reloading may execute it again.

Related guides and examples

Full MQL5 source code

//+------------------------------------------------------------------+
//|币安U本位期货账户成交历史binanceUSDMarginFutureAccountTradeList   |
//|                                  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接口的头文件
// 查询账户在当前合约上的成交历史及手续费。
// Query account trade history and commissions for the current symbol.
// 引入币安 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>

//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[];

// 执行标记,只有在后续代码检查并更新此变量时才限制重复运行。
// Execution flag. It limits repeated execution only where later code checks and updates it.
bool isRun=false;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
// EA 加载时由 MT5 调用,执行本例所需的初始化。
// MT5 calls this handler when the EA is loaded to perform initialization required by this example.
int OnInit()
  {
//initialize binance API key and secret key you set初始化你设置的币安API密钥
   // 初始化配置中已设置的币安 API 凭据,供后续签名请求使用。
   // Initialize the configured Binance API credentials for subsequent signed requests.
   initBinanceAPIKey();

//初始化币安MQL接口使用的curl handles
   // 初始化 curl 全局状态,后续分配句柄数组并创建请求句柄。
   // Initialize global curl state before allocating the handle array and creating request handles.
   curlGlobalInit();
   ArrayResize(handles, 1);
   curlInit(handles);

//set up length of resultChar 设置resultChar的字符长度
   // 为返回 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");
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
// 收到行情时检查执行标记,按函数体中的标记控制演示是否重复运行。
// On each tick, check the execution flag and use the flag logic in the function body to control repeated execution.
void OnTick()
  {
   if(isRun==false)
     {
      //Get trades for a specific account and symbol 账户成交历史
      // 查询当前合约的账户成交记录,本例最多请求 100 条,逐项读取成交和手续费信息。
      // Query account trades for the current symbol, requesting up to 100 records and reading fill and commission information for each trade.
      // 此处使用 handles 发起请求,并通过最后一个引用参数 resultChar 接收同步响应。
      // Use handles for the request and receive the synchronous response through the final reference parameter resultChar.
      ufQueryAccountTradeList(handles, Symbol(), 0, 0, 0, 0, 100, recvWindow, resultChar);
      printf(Symbol());
      // 按 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 jTrades;
      // 解析 JSON 供后续按字段名读取;本例此处未检查解析函数的返回值。
      // Deserialize JSON for subsequent field access. This example does not check the parser return value here.
      jTrades.Deserialize(result);

      if(jTrades.Size()>0)
        {
         // 逐项遍历返回数组,读取每条记录。
         // Iterate through the returned array and read each record.
         for(int i=0; i<jTrades.Size(); i++)
           {
            CJAVal jTrade=jTrades[i];
            // 读取 id 字段,表示成交记录 ID,使用 ToInt 转换。
            // Read id for trade record ID using ToInt.
            long id=jTrade["id"].ToInt();//trade id 交易ID
            printf("trade id 交易ID %s", (string)id);

            // 读取 orderId 字段,表示交易所订单 ID,使用 ToInt 转换。
            // Read orderId for exchange order ID using ToInt.
            long orderId=jTrade["orderId"].ToInt(); //order id 订单编号
            printf("order id 订单编号 %s", (string)orderId);

            // 读取 symbol 字段,表示交易对,使用 ToStr 转换。
            // Read symbol for trading symbol using ToStr.
            string symbol=jTrade["symbol"].ToStr();//symbol 交易对
            printf("symbol 交易对 %s", symbol);

            // 读取 side 字段,表示买卖方向,使用 ToStr 转换。
            // Read side for order side using ToStr.
            string side=jTrade["side"].ToStr(); //side 买卖方向
            printf("side 买卖方向 %s", side);

            // 读取 price 字段,表示价格,使用 ToStr 转换。
            // Read price for price using ToStr.
            string price=jTrade["price"].ToStr();//fill price 成交价
            printf("fill price 成交价 %s", price);

            // 读取 qty 字段,表示成交数量,使用 ToStr 转换。
            // Read qty for fill quantity using ToStr.
            string qty=jTrade["qty"].ToStr();//quantity 成交量
            printf("quantity 成交量 %s", qty);

            // 读取 quoteQty 字段,表示成交金额,使用 ToStr 转换。
            // Read quoteQty for quote quantity using ToStr.
            string quoteQty=jTrade["quoteQty"].ToStr(); //quote quantity 成交额
            printf("quote quantity 成交额 %s", quoteQty);

            // 读取 commission 字段,表示手续费金额,使用 ToStr 转换。
            // Read commission for commission amount using ToStr.
            string commission=jTrade["commission"].ToStr();//commission 手续费
            printf("commission 手续费 %s", commission);

            // 读取 commissionAsset 字段,表示手续费资产,使用 ToStr 转换。
            // Read commissionAsset for commission asset using ToStr.
            string commissionAsset=jTrade["commissionAsset"].ToStr();//commission asset 手续费计价单位
            printf("commission asset 手续费计价单位 %s", commissionAsset);

            // 读取 realizedPnl 字段,表示已实现盈亏,使用 ToStr 转换。
            // Read realizedPnl for realized profit or loss using ToStr.
            string realizedPnl=jTrade["realizedPnl"].ToStr();//realized Pnl 实现盈亏
            printf("realized Pnl 实现盈亏 %s", realizedPnl);

            // 读取 positionSide 字段,表示持仓方向,使用 ToStr 转换。
            // Read positionSide for position side using ToStr.
            string positionSide=jTrade["positionSide"].ToStr();//position side 持仓方向
            printf("position side 持仓方向 %s", positionSide);

            // 读取 buyer 字段,表示是否为买方,使用 ToBool 转换。
            // Read buyer for whether this trade is a buy using ToBool.
            bool isBuyer=jTrade["buyer"].ToBool();//is buyer 是否是买方
            printf("is buyer 是否是买方 %s", (string)isBuyer);

            // 读取 maker 字段,表示是否为 maker 成交,使用 ToStr 转换。
            // Read maker for whether this fill is on the maker side using ToStr.
            string maker=jTrade["maker"].ToStr();//is maker 是否是挂单方
            printf("is maker 是否是挂单方 %s", maker);

            // 读取 time 字段,表示时间戳,使用 ToInt 转换。
            // Read time for timestamp using ToInt.
            long time=jTrade["time"].ToInt();//time 时间
            printf("time 时间 %s", (string)time);

            printf("-------------------------------------------------");
           }
        }

      // 标记本次演示已执行;此处未按请求成功与否决定是否重试。
      // Mark this demonstration as executed. This assignment does not select retries based on request success.
      isRun=true;
     }
  }


//+------------------------------------------------------------------+
//get binance call back event via OnChartEvent
//OnChartEvent函数是MQL中的一个预定义事件处理函数,当用户在图表上进行操作(如点击、按键、移动鼠标等),MT5会自动调用此函数
// OnChartEvent is a predefined MQL event handler that MT5 calls for chart interactions such as clicks, keystrokes, and mouse movements.
//本软件可以通过 OnChartEvent函数得到币安异步推送事件
// This software receives asynchronous Binance events through OnChartEvent.
//这些币安事件代号都是 3333,根据该代号可以区分哪些是币安推送事件而非用户在图表上进行操作产生的事件
// Binance events use ID 3333 to distinguish them from events generated by user interactions with the chart.
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
   // 仅处理币安自定义事件,其他图表事件由此判断过滤。
   // Process only Binance custom events and filter out other chart events with this check.
   if(id==3333)  //all binance call back ID are 3333  币安回调统一代号是3333
     {
      // 转换币安事件参数,取得待反序列化的 JSON 字符串。
      // Decode the Binance event parameter to obtain the JSON string for deserialization.
      string  event = processChartEventMsg(sparam);

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

      // 读取 e 字段,表示事件类型,使用 ToStr 转换。
      // Read e for event type using ToStr.
      string e=jEvent["e"].ToStr();


     }
  }

//+------------------------------------------------------------------+