← EA 示例目录
1021 / MQL5 / USDⓈ-M FUTURES

如何用 MQL5 分页查询币安账户资金流水?

使用 ufGetIncomeHistory,配合 page、limit 和时间区间分页读取资金流水。本例查询 2025-05-01 至 2025-07-01 22:59:59 的记录,每页 1000 条;当返回数量小于 1000 时退出本次翻页循环。

运行这个示例需要什么?

  • 在 MT5 中安装并配置连接软件与 API 密钥,使 mt5binance.mqh、JAson.mqh 以及本例所需的账户权限可用。
  • 将源码中的固定日期改为所需查询区间。时间由 StringToTime 转成秒后乘 1000;本例没有额外时区换算。请求可返回范围仍受接口规则约束,示例日期不保证一直可查。

源码按什么流程执行?

  1. 每次 tick 重新设置 startTime、endTime、page=1、limit=1000 与 returnRows=limit。
  2. 当 returnRows==limit 时查询下一页;symbol 和 incomeType 均传空字符串。
  3. 解析结果,page 加 1,按数组大小更新 returnRows,遍历 incomeType、income、asset、time、tranId 和 tradeId。

每次 OnTick 从第 1 页重新查询,当前循环在返回条数小于 limit 时结束。

示例参数与执行方式

参数源码值或行为
主要接口ufGetIncomeHistory
起始时间2025-05-01 00:00:00
结束时间2025-07-01 22:59:59
品种与类型筛选空字符串
页码1
每页数量1000
继续翻页条件returnRows == limit
请求时间窗口recvWindow = 3000 ms
触发方式每次 OnTick 从第 1 页重新查询,当前循环在返回条数小于 limit 时结束。

相关教程与接口示例

完整 MQL5 源码

//+------------------------------------------------------------------+
//|币安U本位期货查看账户损益资金流水binanceUSDMarginFutureQueryIncomeHistory.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接口的头文件
// 按固定时间范围分页查询资金流水,直至返回数量少于每页限制。
// Page through income history for a fixed time range until a page contains fewer records than the page limit.
// 引入币安 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反序列化币安API返回的json数据  import json library open source from mql5.com to deserialize binance API 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()
  {
   // 初始化配置中已设置的币安 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()
  {
   // 将示例日期转换为秒级时间后乘以 1000,生成接口使用的毫秒时间戳。
   // Convert the example date to seconds and multiply by 1000 to obtain the millisecond timestamp used by the API.
   long startTime=StringToTime("2025-05-01 00:00:00")*1000;
   // 将示例日期转换为秒级时间后乘以 1000,生成接口使用的毫秒时间戳。
   // Convert the example date to seconds and multiply by 1000 to obtain the millisecond timestamp used by the API.
   long endTime=StringToTime("2025-07-01 22:59:59")*1000;
   int page=1;
   int limit=1000;
   int returnRows=limit;

   // 当前页返回满额时继续查询下一页,少于 limit 时结束分页循环。
   // Request another page when the current page is full and stop when fewer than limit records are returned.
   while(returnRows==limit)
     {
      //Get income history  获取账户损益资金流水
      // 按起止时间、页码和每页数量查询资金流水;空交易对和空流水类型不限定这两项筛选。
      // Query income history by time range, page, and page size. Empty symbol and income-type arguments leave those filters unspecified.
      // 此处使用 handles 发起请求,并通过最后一个引用参数 resultChar 接收同步响应。
      // Use handles for the request and receive the synchronous response through the final reference parameter resultChar.
      ufGetIncomeHistory(handles, "","",startTime,endTime,page,limit,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 jIncomes;
      // 解析 JSON 供后续按字段名读取;本例此处未检查解析函数的返回值。
      // Deserialize JSON for subsequent field access. This example does not check the parser return value here.
      jIncomes.Deserialize(result);

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

            // 读取 symbol 字段,表示交易对,使用 ToStr 转换。
            // Read symbol for trading symbol using ToStr.
            string symbol=jIncome["symbol"].ToStr(); //symbol 交易对
            // 读取 incomeType 字段,表示资金流水类型,使用 ToStr 转换。
            // Read incomeType for income type using ToStr.
            string incomeType=jIncome["incomeType"].ToStr(); //income Type 收益类型
            // 读取 income 字段,表示资金变动金额,使用 ToStr 转换。
            // Read income for income amount using ToStr.
            string income=jIncome["income"].ToStr(); //income 资金流数量
            // 读取 asset 字段,表示资产名称,使用 ToStr 转换。
            // Read asset for asset name using ToStr.
            string asset=jIncome["asset"].ToStr(); //asset 资产内容
            // 读取 info 字段,表示流水备注,使用 ToStr 转换。
            // Read info for income record information using ToStr.
            string info=jIncome["info"].ToStr(); //infomation 备注信息

            // 读取 time 字段,表示时间戳,使用 ToStr 转换。
            // Read time for timestamp using ToStr.
            string time=jIncome["time"].ToStr(); //time 时间
            // 读取 tranId 字段,表示资金流水 ID,使用 ToStr 转换。
            // Read tranId for transaction ID using ToStr.
            string tranId=jIncome["tranId"].ToStr(); //tranfer Id 划转ID
            // 读取 tradeId 字段,表示成交 ID,使用 ToStr 转换。
            // Read tradeId for trade ID using ToStr.
            string tradeId=jIncome["tradeId"].ToStr(); //trade Id 引起流水产生的原始交易ID
           }
        }
     }
  }
//+------------------------------------------------------------------+