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

How can MQL5 change Binance USD-M futures leverage?

Call ufChangeInitialLeverage with a symbol and target leverage. On each tick, this example first requests 10× leverage and then 15× leverage for the chart symbol, parsing both responses. It changes account configuration rather than querying data or placing orders.

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.
  • Use the intended contract symbol and appropriate trading permissions. Calls are sequential; determine the actual final leverage from successful responses and account configuration, not merely from the second requested value of 15.

How does the source execute?

  1. In OnTick, call ufChangeInitialLeverage(handles, Symbol(), 10, recvWindow, resultChar).
  2. Convert and parse the first response, then call again with leverage 15 and parse the second response.
  3. OnChartEvent handles ACCOUNT_CONFIG_UPDATE for event ID 3333.

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 interfaceufChangeInitialLeverage
SymbolSymbol()
First requested leverage10
Second requested leverage15
Push eventACCOUNT_CONFIG_UPDATE
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本位期货调整开仓杠杆binanceUSDMarginFutureChangeInitialLeverage.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接口的头文件
// 依次将当前合约杠杆设置为 10 倍、15 倍,并接收账户配置更新推送。
// Set the current symbol leverage to 10 and then 15, and receive account-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>

//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币安API response data  MQL币安API返回数据
// 同步响应缓冲区,API 调用将返回数据写入此字符数组。
// Synchronous response buffer populated by API calls.
static char resultChar[];

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

//+------------------------------------------------------------------+
//| 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");
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
// 每次收到行情都会执行函数体中的请求流程,本函数未使用一次性运行判断。
// Each tick executes the request sequence in this handler, which has no one-shot execution guard.
void OnTick()
  {
//---
//Change Initial Leverage  调整开仓杠杆
   // 调整当前图表合约的初始杠杆倍数;本函数的参数值决定目标杠杆。
   // Change the initial leverage for the current chart symbol to the leverage specified by the argument.
   // 此处使用 handles 发起请求,并通过最后一个引用参数 resultChar 接收同步响应。
   // Use handles for the request and receive the synchronous response through the final reference parameter resultChar.
   ufChangeInitialLeverage(handles, Symbol(), 10, 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 jInitialLeverage;
   // 解析 JSON 供后续按字段名读取;本例此处未检查解析函数的返回值。
   // Deserialize JSON for subsequent field access. This example does not check the parser return value here.
   jInitialLeverage.Deserialize(result);

   // 调整当前图表合约的初始杠杆倍数;本函数的参数值决定目标杠杆。
   // Change the initial leverage for the current chart symbol to the leverage specified by the argument.
   // 此处使用 handles 发起请求,并通过最后一个引用参数 resultChar 接收同步响应。
   // Use handles for the request and receive the synchronous response through the final reference parameter resultChar.
   ufChangeInitialLeverage(handles, Symbol(), 15, recvWindow, resultChar);
   // 按 UTF-8 将同步响应字符数组转换为 MQL 字符串。
   // Convert the synchronous response character array to an MQL string using UTF-8.
   result=CharArrayToString(resultChar, 0, -1, CP_UTF8);
   // 解析 JSON 供后续按字段名读取;本例此处未检查解析函数的返回值。
   // Deserialize JSON for subsequent field access. This example does not check the parser return value here.
   jInitialLeverage.Deserialize(result);
  }
//+------------------------------------------------------------------+



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

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

      //Event: Account Configuration Update previous Leverage Update
      //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 交易时间
         // 读取 ac 节点,即杠杆配置对象。
         // Read ac, the leverage configuration object.
         CJAVal jAc=jEvent["ac"]; //account json 账号 json
         // 读取 s 字段,表示交易对,使用 ToStr 转换。
         // Read s for trading symbol using ToStr.
         string symbol=jAc["s"].ToStr();    //symbol 交易对
         // 读取 l 字段,表示杠杆倍数,使用 ToInt 转换。
         // Read l for leverage using ToInt.
         long leverage=jAc["l"].ToInt();    //leverage 杠杆倍数

         printf("change initial leverage: symbol %s, leverage %s",symbol,(string)leverage);
        }

     }

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