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

如何用 MQL5 查询币安持仓风险信息 V3?

使用 ufPositionInformationV3 查询当前图表品种的持仓风险信息。本例遍历返回数组,读取持仓数量、入场价、盈亏平衡价、标记价格、未实现盈亏、强平价格和保证金相关字段。

运行这个示例需要什么?

  • 在 MT5 中安装并配置连接软件与 API 密钥,使 mt5binance.mqh、JAson.mqh 以及本例所需的账户权限可用。
  • 选择要查询的合约图表,并确保账户 API 可读取相关持仓信息。此示例读取账户持仓,不通过客户端订单号计算单个 EA 的专属仓位。

源码按什么流程执行?

  1. 每个 tick 调用 ufPositionInformationV3(handles, Symbol(), recvWindow, resultChar)。
  2. 转换 UTF-8 响应,用 CJAVal 解析并遍历每条持仓记录。
  3. 读取 positionAmt、entryPrice、breakEvenPrice、markPrice、unRealizedProfit、liquidationPrice、positionSide 以及保证金、ADL 等字段。

每次 OnTick 执行请求,没有生效的单次执行标记;请求频率随图表行情到达而变化。

示例参数与执行方式

参数源码值或行为
主要接口ufPositionInformationV3
品种Symbol()
接口版本V3
持仓字段positionAmt / entryPrice / markPrice / positionSide
风险字段liquidationPrice / initialMargin / maintMargin / adl
请求时间窗口recvWindow = 3000 ms
触发方式每次 OnTick 执行请求,没有生效的单次执行标记;请求频率随图表行情到达而变化。

相关教程与接口示例

完整 MQL5 源码

//+------------------------------------------------------------------+
//|币安U本位期货查看用户持仓风险V3binanceUSDMarginFutureQueryPositionRiskV3.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 MT5 binance API header file 引入MT5币安API头文件
// 查询 V3 持仓风险信息并读取持仓、价格和保证金字段。
// Query V3 position risk and read position, price, and margin fields.
// 引入币安 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/binance-spot-api-docs/rest-api/endpoint-security-type#timing-security
//设置时间同步安全 https://developers.binance.com/docs/zh-CN/binance-spot-api-docs/rest-api/endpoint-security-type#%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 current position information 用户持仓风险V3
   // 查询 V3 持仓风险信息,返回列表包含持仓、标记价格及保证金等数据。
   // Query V3 position risk information, including position amounts, mark prices, and margin data.
   // 此处使用 handles 发起请求,并通过最后一个引用参数 resultChar 接收同步响应。
   // Use handles for the request and receive the synchronous response through the final reference parameter resultChar.
   ufPositionInformationV3(handles, Symbol(), 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 jPositions;
   // 解析 JSON 供后续按字段名读取;本例此处未检查解析函数的返回值。
   // Deserialize JSON for subsequent field access. This example does not check the parser return value here.
   jPositions.Deserialize(result);

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

      if(jPosition.Size()>0)
        {
         // 读取 symbol 字段,表示交易对,使用 ToStr 转换。
         // Read symbol for trading symbol using ToStr.
         string symbol=jPosition["symbol"].ToStr();
         // 读取 positionAmt 字段,表示持仓数量,使用 ToStr 转换。
         // Read positionAmt for position amount using ToStr.
         string positionAmt=jPosition["positionAmt"].ToStr();
         // 读取 entryPrice 字段,表示入仓价格,使用 ToStr 转换。
         // Read entryPrice for entry price using ToStr.
         string entryPrice=jPosition["entryPrice"].ToStr();
         // 读取 breakEvenPrice 字段,表示盈亏平衡价格,使用 ToStr 转换。
         // Read breakEvenPrice for break-even price using ToStr.
         string breakEvenPrice=jPosition["breakEvenPrice"].ToStr();
         // 读取 markPrice 字段,表示标记价格,使用 ToStr 转换。
         // Read markPrice for mark price using ToStr.
         string markPrice=jPosition["markPrice"].ToStr();
         // 读取 unRealizedProfit 字段,表示未实现盈亏,使用 ToStr 转换。
         // Read unRealizedProfit for unrealized profit or loss using ToStr.
         string unRealizedProfit=jPosition["unRealizedProfit"].ToStr();// unrealized profit 持仓未实现盈亏
         // 读取 liquidationPrice 字段,表示强平价格,使用 ToStr 转换。
         // Read liquidationPrice for liquidation price using ToStr.
         string liquidationPrice=jPosition["liquidationPrice"].ToStr();
         // 读取 isolatedMargin 字段,表示逐仓保证金,使用 ToStr 转换。
         // Read isolatedMargin for isolated margin using ToStr.
         string isolatedMargin=jPosition["isolatedMargin"].ToStr();
         // 读取 positionSide 字段,表示持仓方向,使用 ToStr 转换。
         // Read positionSide for position side using ToStr.
         string positionSide=jPosition["positionSide"].ToStr(); // position side 持仓方向
         // 读取 updateTime 字段,表示更新时间戳,使用 ToStr 转换。
         // Read updateTime for update timestamp using ToStr.
         string updateTime=jPosition["updateTime"].ToStr();
         // 读取 notional 字段,表示持仓名义价值,使用 ToStr 转换。
         // Read notional for position notional value using ToStr.
         string notional=jPosition["notional"].ToStr();
         // 读取 marginAsset 字段,表示保证金资产,使用 ToStr 转换。
         // Read marginAsset for margin asset using ToStr.
         string marginAsset=jPosition["marginAsset"].ToStr();
         // 读取 isolatedWallet 字段,表示逐仓钱包余额,使用 ToStr 转换。
         // Read isolatedWallet for isolated wallet balance using ToStr.
         string isolatedWallet=jPosition["isolatedWallet"].ToStr();
         // 读取 initialMargin 字段,表示初始保证金,使用 ToStr 转换。
         // Read initialMargin for initial margin using ToStr.
         string initialMargin=jPosition["initialMargin"].ToStr();// initial margin required with current mark price 初始保证金
         // 读取 maintMargin 字段,表示维持保证金,使用 ToStr 转换。
         // Read maintMargin for maintenance margin using ToStr.
         string maintMargin=jPosition["maintMargin"].ToStr();// maintenance margin required 维持保证金
         // 读取 positionInitialMargin 字段,表示持仓所需初始保证金,使用 ToStr 转换。
         // Read positionInitialMargin for initial margin required for positions using ToStr.
         string positionInitialMargin=jPosition["positionInitialMargin"].ToStr();// initial margin required for positions with current mark price 仓位初始保证金
         // 读取 openOrderInitialMargin 字段,表示挂单所需初始保证金,使用 ToStr 转换。
         // Read openOrderInitialMargin for initial margin required for open orders using ToStr.
         string openOrderInitialMargin=jPosition["openOrderInitialMargin"].ToStr();// initial margin required for open orders with current mark price  订单初始保证金
         // 读取 adl 字段,表示自动减仓量化指标,使用 ToStr 转换。
         // Read adl for auto-deleveraging indicator using ToStr.
         string adl=jPosition["adl"].ToStr();
         // 读取 bidNotional 字段,表示买单名义价值,使用 ToStr 转换。
         // Read bidNotional for bid notional using ToStr.
         string bidNotional=jPosition["bidNotional"].ToStr();// bids notional, ignore
         // 读取 askNotional 字段,表示卖单名义价值,使用 ToStr 转换。
         // Read askNotional for ask notional using ToStr.
         string askNotional=jPosition["askNotional"].ToStr();// ask notional, ignore
        }
     }
  }


//+------------------------------------------------------------------+
//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 event 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();
     }

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