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

如何用 MQL5 切换币安联合保证金模式?

调用 ufChangeMultiAssetsMode,传入字符串 true 或 false。本例在首次定时器事件中先请求开启联合保证金模式,再请求关闭,并解析两次响应;它修改的是账户模式,不是仅 ETHUSDT 的设置。

运行这个示例需要什么?

  • 在 MT5 中安装并配置连接软件与 API 密钥,使 mt5binance.mqh、JAson.mqh 以及本例所需的账户权限可用。
  • 账户需满足模式切换条件并具有对应 API 权限。当前源码 OnInit 只设置 symbol 和定时器,未完成本组其他示例中的 initBinanceAPIKey、curl 句柄与缓冲区初始化;接入时需结合所用库与环境补齐准备。

源码按什么流程执行?

  1. OnInit 设置 symbol="ETHUSDT" 并调用 EventSetTimer(1);OnTick 为空。
  2. 首次 OnTimer 在 isRun==false 时执行 runDemo,依次调用 ufChangeMultiAssetsMode(..., "true", ...) 和 "false"。
  3. 设置 isRun=true;OnChartEvent 对 ACCOUNT_CONFIG_UPDATE 进行处理。最终模式以实际成功的响应为准。

首次定时器事件运行演示,isRun 阻止后续重复;EventSetTimer(1) 设置 1 秒间隔。

示例参数与执行方式

参数源码值或行为
主要接口ufChangeMultiAssetsMode
定时器间隔1 s
第一次请求"true"
第二次请求"false"
作用范围账户模式
事件ACCOUNT_CONFIG_UPDATE
请求时间窗口recvWindow = 3000 ms
触发方式首次定时器事件运行演示,isRun 阻止后续重复;EventSetTimer(1) 设置 1 秒间隔。

相关教程与接口示例

完整 MQL5 源码

//+------------------------------------------------------------------+
//|币安U本位期货更改联合保证金模式binanceUSDMarginFutureChangeMultiAssetsMode.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头文件
// 通过定时器先启用再关闭联合保证金模式,并接收配置更新事件。
// Use a timer to enable and then disable Multi-Assets Mode and receive configuration updates.
// 引入币安 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>

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

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

// 保存币安请求使用的 curl 句柄,供接口调用复用。
// Store curl handles for reuse by Binance API calls.
int handles[];
// 同步响应缓冲区,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()
  {
//---
   symbol="ETHUSDT";

//run demo in one second 设置一秒钟后运行例子
   // 设置每秒触发一次的定时器,实际是否重复执行由 OnTimer 中的标记决定。
   // Set a one-second timer. The flag in OnTimer determines whether the demonstration runs again.
   EventSetTimer(1);

   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)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
// 本例通过 OnTimer 启动演示,OnTick 保留为空。
// This example starts its demonstration through OnTimer and leaves OnTick empty.
void OnTick()
  {
//---

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

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
// 定时器回调检查 isRun,首次执行 runDemo 后设置标记,后续回调跳过演示。
// The timer callback checks isRun, runs runDemo once, and sets the flag so later callbacks skip the demonstration.
void OnTimer()
  {
   if(isRun==false)
     {
      runDemo();
      // 标记本次演示已执行;此处未按请求成功与否决定是否重试。
      // Mark this demonstration as executed. This assignment does not select retries based on request success.
      isRun=true;
     }
   }  


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
// 通过定时器先启用再关闭联合保证金模式,并接收配置更新事件。
// Use a timer to enable and then disable Multi-Assets Mode and receive configuration updates.
void runDemo()
  {

   //Change Multi-Assets Mode 更改联合保证金模式
   //https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Change-Multi-Assets-Mode
   //https://developers.binance.com/docs/zh-CN/derivatives/usds-margined-futures/trade/rest-api/Change-Multi-Assets-Mode
   // true 启用联合保证金模式,false 切回单资产保证金模式,按当前调用的字符串参数执行。
   // true enables Multi-Assets Mode and false selects Single-Asset Mode, as specified by the current string argument.
   // 此处使用直接返回响应字符串的调用形式,具体参数以当前头文件声明为准。
   // This call form returns the response string directly. Refer to the current header declaration for the exact parameters.
   ufChangeMultiAssetsMode(handles, "true",recvWindow, resultChar);

   //调用后币安同步返回下单结果,将其保存在最后一个引用参数resultChar中(币安异步返回的事件在OnChartEvent中处理)
   //将字符数组resultChar换成字符串result
   string result=CharArrayToString(resultChar, 0, -1, CP_UTF8);
      
   CJAVal jMultiAssetsMode;
   // 解析 JSON 供后续按字段名读取;本例此处未检查解析函数的返回值。
   // Deserialize JSON for subsequent field access. This example does not check the parser return value here.
   jMultiAssetsMode.Deserialize(result);


   // true 启用联合保证金模式,false 切回单资产保证金模式,按当前调用的字符串参数执行。
   // true enables Multi-Assets Mode and false selects Single-Asset Mode, as specified by the current string argument.
   // 此处使用直接返回响应字符串的调用形式,具体参数以当前头文件声明为准。
   // This call form returns the response string directly. Refer to the current header declaration for the exact parameters.
   ufChangeMultiAssetsMode(handles, "false",recvWindow,resultChar);
   // 解析 JSON 供后续按字段名读取;本例此处未检查解析函数的返回值。
   // Deserialize JSON for subsequent field access. This example does not check the parser return value here.
   jMultiAssetsMode.Deserialize(resultChar);
  }
//+------------------------------------------------------------------+

//get binance event via OnChartEvent 从OnChartEvent得到币安事件推送
// OnChartEvent 是 MT5 图表及自定义事件入口,本接口通过它接收币安异步推送。
// OnChartEvent handles MT5 chart and custom events. This API uses it to receive asynchronous Binance push events.
// id 为事件类型,币安事件使用 3333;lparam、dparam 为附加数值参数,本例未读取。
// id identifies the event type, with 3333 used for Binance events. lparam and dparam are additional numeric parameters that this example does not read.
// sparam 携带事件字符串,经 processChartEventMsg 处理后再解析 JSON;同步 API 响应与推送事件分别处理。
// sparam carries the event string. Process it with processChartEventMsg before parsing JSON. Handle synchronous API responses separately from push events.
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();

      //https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Account-Configuration-Update-previous-Leverage-Update
      //https://developers.binance.com/docs/zh-CN/derivatives/usds-margined-futures/user-data-streams/Event-Account-Configuration-Update-previous-Leverage-Update      
      // 账户配置更新推送,ac 对象描述杠杆变化,ai 对象描述联合保证金模式变化。
      // Account configuration update. ac describes leverage changes and ai describes Multi-Assets Mode changes.
      if(e=="ACCOUNT_CONFIG_UPDATE")  //Event Type  事件类型
        {
         // 读取 E 字段,表示事件时间,单位为毫秒,使用 ToInt 转换。
         // Read E for event time in milliseconds using ToInt.
         long eventTime=jEvent["E"].ToInt();    //Event Time 事件时间
         // 读取 T 字段,表示交易时间,单位为毫秒,使用 ToInt 转换。
         // Read T for transaction time in milliseconds using ToInt.
         long transactionTime=jEvent["T"].ToInt();    //Transaction Time 撮合时间
         // 读取 ai 节点,即联合保证金配置对象。
         // Read ai, the Multi-Assets Mode configuration object.
         CJAVal jAi=jEvent["ai"]; //User's Account Configuration 用户账户配置
         // 读取 j 字段,表示是否启用联合保证金模式,使用 ToStr 转换。
         // Read j for whether Multi-Assets Mode is enabled using ToStr.
         string j=jAi["j"].ToStr();    //Multi-Assets Mode 联合保证金状态
       
         
         printf("Change Multi Assets Mode: %s, true: Multi-Assets Mode; false: Single-Asset Mode",j );
        }

     }

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