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

How can MQL5 add margin to a Binance isolated position?

Call ufModifyIsolatedPositionMargin to adjust isolated position margin. This example first requests ISOLATED margin mode for the chart symbol, then queries position mode. It uses BOTH in One-way Mode or LONG in Hedge Mode and submits amount=4, type=1 to add margin.

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.
  • Have an applicable isolated position, permissions and available funds for the symbol. The Hedge Mode branch targets LONG, not SHORT. Determine whether the preceding margin-mode change succeeded from its response.

How does the source execute?

  1. On the first tick, call runDemo and first request ufChangeMarginType(..., "ISOLATED", ...).
  2. Call ufGetCurrentPositionMode and read dualSidePosition to select BOTH or LONG.
  3. Call ufModifyIsolatedPositionMargin with amount=4 and type=1, then parse the response. OnChartEvent handles ACCOUNT_UPDATE.

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 interfaceufModifyIsolatedPositionMargin
SymbolSymbol()
Margin modeISOLATED
Amount4
Type1
Position sideBOTH / LONG
EventACCOUNT_UPDATE
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本位期货调整逐仓保证金binanceUSDMarginFutureModifyIsolatedPositionMargin.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币安API头文件
// 切换逐仓模式、查询持仓模式后追加保证金,并解析账户更新事件。
// Select isolated margin, query position mode, add margin, and parse account-update events.
// 引入币安 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;

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

// 保存币安请求使用的 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()
  {
//---
   // 初始化配置中已设置的币安 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)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
// 收到行情时检查执行标记,按函数体中的标记控制演示是否重复运行。
// 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)
     {
      runDemo();
      // 标记本次演示已执行;此处未按请求成功与否决定是否重试。
      // Mark this demonstration as executed. This assignment does not select retries based on request success.
      isRun=true;
     }
  }



//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
// 切换逐仓模式、查询持仓模式后追加保证金,并解析账户更新事件。
// Select isolated margin, query position mode, add margin, and parse account-update events.
void runDemo()
  {
//Change Margin Type 变换逐全仓模式
   // 将当前图表合约的保证金模式设置为 ISOLATED,即逐仓模式。
   // Set the current chart symbol's margin mode to ISOLATED.
   // 此处使用 handles 发起请求,并通过最后一个引用参数 resultChar 接收同步响应。
   // Use handles for the request and receive the synchronous response through the final reference parameter resultChar.
   ufChangeMarginType(handles, Symbol(), "ISOLATED", 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);

//Get Current Position Mode  查询持仓模式
   // 查询双向或单向持仓模式,通过 dualSidePosition 决定后续请求的持仓方向。
   // Query Hedge Mode or One-way Mode and use dualSidePosition to determine the position side for subsequent requests.
   // 此处使用 handles 发起请求,并通过最后一个引用参数 resultChar 接收同步响应。
   // Use handles for the request and receive the synchronous response through the final reference parameter resultChar.
   ufGetCurrentPositionMode(handles, 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);
   CJAVal jPositionMode;
//deserialize binance response json  反序列化币安API返回的json
   // 解析 JSON 供后续按字段名读取;本例此处未检查解析函数的返回值。
   // Deserialize JSON for subsequent field access. This example does not check the parser return value here.
   jPositionMode.Deserialize(result);

   // 读取 dualSidePosition 字段,表示是否为双向持仓模式,使用 ToBool 转换。
   // Read dualSidePosition for whether Hedge Mode is enabled using ToBool.
   bool isHedgeMode=jPositionMode["dualSidePosition"].ToBool();

   if(isHedgeMode==false)  //单向持仓模式 position one way mode
     {
      //Modify Isolated Position Margin 调整逐仓保证金
      // 为指定持仓方向追加 4 单位保证金,type=1 表示增加;单向模式使用 BOTH,双向模式使用 LONG。
      // Add 4 units of margin to the specified position side with type=1. Use BOTH in One-way Mode and LONG in Hedge Mode in this example.
      // 此处使用 handles 发起请求,并通过最后一个引用参数 resultChar 接收同步响应。
      // Use handles for the request and receive the synchronous response through the final reference parameter resultChar.
      ufModifyIsolatedPositionMargin(handles, Symbol(), "BOTH", 4, 1, recvWindow, resultChar);
     }
   else  //双向持仓模式 position hedge mode
     {
      // 为指定持仓方向追加 4 单位保证金,type=1 表示增加;单向模式使用 BOTH,双向模式使用 LONG。
      // Add 4 units of margin to the specified position side with type=1. Use BOTH in One-way Mode and LONG in Hedge Mode in this example.
      // 此处使用 handles 发起请求,并通过最后一个引用参数 resultChar 接收同步响应。
      // Use handles for the request and receive the synchronous response through the final reference parameter resultChar.
      ufModifyIsolatedPositionMargin(handles, Symbol(), "LONG", 4, 1, 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);

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

      //https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Balance-and-Position-Update
      //https://developers.binance.com/docs/zh-CN/derivatives/usds-margined-futures/user-data-streams/Event-Balance-and-Position-Update 中文
      // 账户余额或持仓更新后进入此分支,按本例逻辑读取数据或重新查询订单。
      // Enter this branch after balance or position updates to read data or query orders again as implemented by this example.
      if(e=="ACCOUNT_UPDATE")
        {
         // 读取 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 撮合时间

         // 读取 a 节点,即账户更新对象。
         // Read a, the account update object.
         CJAVal jEventO=jEvent["a"]; // Update Data 账户更新事件
         // 读取 m 字段,表示账户更新原因,使用 ToStr 转换。
         // Read m for account update reason using ToStr.
         string reasonType=jEventO["m"].ToStr(); // Event reason type 事件推出原因

         // 读取 b 节点,即当前代码读取的顶层 b 节点。
         // Read b, the top-level b node read by the current code.
         CJAVal jBalances=jEvent["b"]; // Balances  余额信息
         if(jBalances.Size()>0)
           {
            // 逐项遍历返回数组,读取每条记录。
            // Iterate through the returned array and read each record.
            for(int i=0;i<jBalances.Size();i++)
              {
               CJAVal jBalance=jBalances[i];

               // 读取 a 字段,表示资产名称,使用 ToStr 转换。
               // Read a for asset name using ToStr.
               string asset=jBalance["a"].ToStr(); // Asset 资产名称
               // 读取 wb 字段,表示钱包余额,使用 ToStr 转换。
               // Read wb for wallet balance using ToStr.
               string walletBalance=jBalance["wb"].ToStr(); // Wallet Balance 钱包余额
               // 读取 cw 字段,表示全仓钱包余额,使用 ToStr 转换。
               // Read cw for cross wallet balance using ToStr.
               string crossWalletBalance=jBalance["cw"].ToStr(); // Cross Wallet Balance 除去逐仓仓位保证金的钱包余额
               // 读取 bc 字段,表示不含盈亏和手续费的钱包余额变动,使用 ToStr 转换。
               // Read bc for wallet balance change excluding profit or loss and commissions using ToStr.
               string balanceChange=jBalance["bc"].ToStr(); // Balance Change except PnL and Commission 除去盈亏与交易手续费以外的钱包余额改变量

               printf("balance: asset %s, wallet balance %s, cross wallet balance %s, balance change %s",
                      asset, walletBalance, crossWalletBalance, balanceChange);

              }
           }

         // 读取 p 节点,即当前代码读取的顶层 p 节点。
         // Read p, the top-level p node read by the current code.
         CJAVal jPositions=jEvent["p"];   // Position
         if(jPositions.Size()>0)
           {
            // 逐项遍历返回数组,读取每条记录。
            // Iterate through the returned array and read each record.
            for(int i=0;i<jPositions.Size();i++)
              {
               CJAVal jPosition=jPositions[i];

               // 读取 s 字段,表示交易对,使用 ToStr 转换。
               // Read s for trading symbol using ToStr.
               string symbol=jPosition["s"].ToStr();// Symbol 交易对
               // 读取 pa 字段,表示持仓数量,使用 ToStr 转换。
               // Read pa for position amount using ToStr.
               string positionAmount=jPosition["pa"].ToStr();// Position Amount 仓位
               // 读取 ep 字段,表示入仓价格,使用 ToStr 转换。
               // Read ep for entry price using ToStr.
               string entryPrice=jPosition["ep"].ToStr();// Entry Price 入仓价格
               // 读取 bep 字段,表示盈亏平衡价格,使用 ToStr 转换。
               // Read bep for break-even price using ToStr.
               string balanceChange=jPosition["bep"].ToStr();// Balance Change except PnL and Commission 盈亏平衡价
               // 读取 cr 字段,表示累计已实现盈亏,使用 ToStr 转换。
               // Read cr for accumulated realized profit or loss using ToStr.
               string accumulatedRealized=jPosition["cr"].ToStr();//(Pre-fee) Accumulated Realized (费前)累计实现损益
               // 读取 up 字段,表示未实现盈亏,使用 ToStr 转换。
               // Read up for unrealized profit or loss using ToStr.
               string unrealizedPnL=jPosition["up"].ToStr();// Unrealized PnL 持仓未实现盈亏
               // 读取 mt 字段,表示保证金模式,使用 ToStr 转换。
               // Read mt for margin mode using ToStr.
               string marginType=jPosition["mt"].ToStr();// Margin Type 保证金模式
               // 读取 iw 字段,表示逐仓钱包余额,使用 ToStr 转换。
               // Read iw for isolated wallet balance using ToStr.
               string isolatedWallet=jPosition["iw"].ToStr();// Isolated Wallet (if isolated position) 若为逐仓,仓位保证金
               // 读取 ps 字段,表示持仓方向,使用 ToStr 转换。
               // Read ps for position side using ToStr.
               string positionSide=jPosition["ps"].ToStr();// Position Side 持仓方向
               printf("position: symbol %s, positionAmount %s, entryPrice %s, balanceChange %s, accumulatedRealized %s, unrealizedPnL %s, marginType %s, isolatedWallet %s, isolatedWallet %s,",
                      symbol, positionAmount, entryPrice, balanceChange, accumulatedRealized, unrealizedPnL, marginType, isolatedWallet, isolatedWallet);

              }
           }
        }


     }

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