How can MQL5 modify multiple Binance USD-M futures orders?
Build a JSON array of amendments and call ufModifyMultipleOrders. This example targets two ETHUSDT limit BUY orders, setting their price to the current chart last price minus 500 and their quantities to 0.066 and 0.065. It reads each response item’s code and handles order updates.
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.
Prepare two amendable ETHUSDT orders and replace the generated sample origClientOrderId values with identifiers of existing orders. The example does not create those orders. Price is read from Symbol(), while amendments specify ETHUSDT.
How does the source execute?
Build two ETHUSDT BUY LIMIT GTC amendment objects with quantities 0.066 and 0.065, using myClientOrderId01 and myClientOrderId02 as origClientOrderId.
Read SYMBOL_LAST from the current chart, use price-500 for both amendments, and submit them in one ufModifyMultipleOrders call.
Iterate through the response array with CJAVal and read each code. Handle asynchronous ORDER_TRADE_UPDATE separately in OnChartEvent.
Run on the first tick of this attachment; isRun then prevents repetition. Reloading may execute it again.
Parameters and execution behavior
Parameter
Source value or behavior
Main interface
ufModifyMultipleOrders
Symbol
ETHUSDT
Side
BUY
Type
LIMIT / GTC
Quantities
0.066 / 0.065
New price
SymbolInfoDouble(Symbol(), SYMBOL_LAST) - 500
Order IDs
myClientOrderId + GetTickCount() + _01 / _02
Request timing window
recvWindow = 3000 ms
Execution trigger
Run on the first tick of this attachment; isRun then prevents repetition. Reloading may execute it again.
//+------------------------------------------------------------------+//|币安U本位期货批量修改订单binanceUSDMarginFutureModifyMultipleOrders.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头文件// 构造两笔 ETHUSDT 限价订单的修改请求并批量提交,随后处理订单更新推送。// Build and submit amendment requests for two ETHUSDT limit orders, then handle order-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>//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;
bool isModifyOrder=false;
string tickCount=(string)GetTickCount();
string myClientOrderId01="myClientOrderId"+tickCount+"_01";
string myClientOrderId02="myClientOrderId"+tickCount+"_02";
//MQL币安API response data MQL币安API返回数据// 同步响应缓冲区,API 调用将返回数据写入此字符数组。// Synchronous response buffer populated by API calls.staticchar resultChar[];
// 保存币安请求使用的 curl 句柄,供接口调用复用。// Store curl handles for reuse by Binance API calls.int handles[];
// 执行标记,只有在后续代码检查并更新此变量时才限制重复运行。// 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.intOnInit()
{
// 初始化配置中已设置的币安 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.voidOnDeinit(constint reason)
{
//---// 释放本例创建的 curl 请求句柄。// Release the curl request handles created by this example.curlCleanUp(handles);
printf("curlCleanUp");
}
//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+// 收到行情时检查执行标记,按函数体中的标记控制演示是否重复运行。// On each tick, check the execution flag and use the flag logic in the function body to control repeated execution.voidOnTick()
{
if(isRun==false)
{
double price=SymbolInfoDouble(Symbol(), SYMBOL_LAST);
string multipleOrders="[{\"type\":\"LIMIT\",\"timeInForce\":\"GTC\",\"symbol\":\"ETHUSDT\",\"side\":\"BUY\",\"price\":\""+(string)(price-500)+"\",\"quantity\":\"0.066\",\"origClientOrderId\": \""+myClientOrderId01+"\"},{\"type\":\"LIMIT\",\"timeInForce\":\"GTC\",\"symbol\":\"ETHUSDT\",\"side\":\"BUY\",\"price\":\""+(string)(price-500)+"\",\"quantity\":\"0.065\",\"origClientOrderId\": \""+myClientOrderId02+"\"}]";
//Modify Multiple Orders https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Modify-Multiple-Orders//批量修改订单 https://developers.binance.com/docs/zh-CN/derivatives/usds-margined-futures/trade/rest-api/Modify-Multiple-Orders// multipleOrders 是修改请求的 JSON 数组,每项使用原客户订单号定位订单;批量返回中每项可能独立成功或失败。// multipleOrders is a JSON array of amendment requests identified by original client order ID. Each item in the batch response can succeed or fail independently.// 此处使用 handles 发起请求,并通过最后一个引用参数 resultChar 接收同步响应。// Use handles for the request and receive the synchronous response through the final reference parameter resultChar.ufModifyMultipleOrders(handles, multipleOrders, 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 jOrders;
// 解析 JSON 供后续按字段名读取;本例此处未检查解析函数的返回值。// Deserialize JSON for subsequent field access. This example does not check the parser return value here.
jOrders.Deserialize(result);
// 逐项遍历返回数组,读取每条记录。// Iterate through the returned array and read each record.for(int i=0;i<jOrders.Size();i++)
{
CJAVal jOrder=jOrders[i];
// 读取 code 错误码字段;成功响应的字段结构由各接口决定,后续按本例条件处理。// Read the code error field. Successful response structures depend on the endpoint and are handled by the conditions below.string code=jOrder["code"].ToStr();
}
}
// 标记本次演示已执行;此处未按请求成功与否决定是否重试。// Mark this demonstration as executed. This assignment does not select retries based on request success.
isRun=true;
}
//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.voidOnChartEvent(constint id,
constlong &lparam,
constdouble &dparam,
conststring &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();
//Event: Order Update https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Order-Update//订单交易更新推送 https://developers.binance.com/docs/zh-CN/derivatives/usds-margined-futures/user-data-streams/Event-Order-Update// 订单更新事件的 E、T 是毫秒时间戳,订单明细位于 o 对象,使用客户订单号识别订单归属。// E and T are millisecond timestamps in an order-update event. Order details are in o, and the client order ID identifies order ownership.if(e=="ORDER_TRADE_UPDATE")
{
int timeZone=(int)(TimeLocal()-TimeGMT())/60/60;
// 读取 E 字段,表示事件时间,单位为毫秒,使用 ToInt 转换。// Read E for event time in milliseconds using ToInt.long eventTime=jEvent["E"].ToInt(); //Event Time 事件时间//convert API utc0 timestamp to local datetime 把API utc0时间戳转换成当前时区的时间// 将毫秒时间戳除以 1000 后转换为 datetime,再加上本例计算的本地时区偏移。// Divide the millisecond timestamp by 1000, convert it to datetime, and add the local time-zone offset calculated by this example.datetime eventDateTime=(datetime)(eventTime/1000)+timeZone*60*60;
printf("ORDER_TRADE_UPDATE|Event Time 事件时间 %s %s", (string)eventTime, (string)eventDateTime);
// 读取 T 字段,表示交易时间,单位为毫秒,使用 ToInt 转换。// Read T for transaction time in milliseconds using ToInt.long transactionTime=jEvent["T"].ToInt(); //Transaction Time 交易时间// 将毫秒时间戳除以 1000 后转换为 datetime,再加上本例计算的本地时区偏移。// Divide the millisecond timestamp by 1000, convert it to datetime, and add the local time-zone offset calculated by this example.datetime transactionDateTime=(datetime)(transactionTime/1000)+timeZone*60*60;
printf(" |Transaction Time 交易时间 %s %s", (string)transactionTime, (string)transactionDateTime);
//deserialize binance response json 反序列化币安返回的json// 读取 o 节点,即订单明细对象。// Read o, the order details object.CJAVal jEventO=jEvent["o"];
// 读取 s 字段,表示交易对,使用 ToStr 转换。// Read s for trading symbol using ToStr.string eventSymbol=jEventO["s"].ToStr(); // Symbol 交易对printf(" |Symbol 交易对 %s", eventSymbol);
// 读取 c 字段,表示用户自定义订单 ID,使用 ToStr 转换。// Read c for client order ID using ToStr.string clientOrderId=jEventO["c"].ToStr(); // Client Order Id 客户端自定订单IDprintf(" |Client Order Id 客户端自定订单ID %s", clientOrderId);
// 读取 S 字段,表示买卖方向,使用 ToStr 转换。// Read S for order side using ToStr.string side=jEventO["S"].ToStr(); //Side 订单方向printf(" |Side 订单方向 %s", side);
// 读取 o 字段,表示订单类型,使用 ToStr 转换。// Read o for order type using ToStr.string orderType=jEventO["o"].ToStr(); //Order Type 订单类型printf(" |Order Type 订单类型 %s", orderType);
// 读取 f 字段,表示订单有效方式,使用 ToStr 转换。// Read f for time in force using ToStr.string timeInForce=jEventO["f"].ToStr(); // Time in Force 有效方式printf(" |Time in Force 有效方式 %s", timeInForce);
// 读取 q 字段,表示原始委托数量,使用 ToStr 转换。// Read q for original order quantity using ToStr.string originalQuantity=jEventO["q"].ToStr(); //Original Quantity 订单原始数量printf(" |Original Quantity 订单原始数量 %s", originalQuantity);
// 读取 p 字段,表示原始委托价格,使用 ToStr 转换。// Read p for original order price using ToStr.string originalPrice=jEventO["p"].ToStr(); //Original Price 订单原始价格printf(" |Original Price 订单原始价格 %s", originalPrice);
// 读取 ap 字段,表示平均成交价格,使用 ToStr 转换。// Read ap for average fill price using ToStr.string averagePrice=jEventO["ap"].ToStr(); //Average Price 订单平均价格printf(" |Average Price 订单平均价格 %s", averagePrice);
// 读取 sp 字段,表示触发价格,使用 ToStr 转换。// Read sp for trigger price using ToStr.string stopPrice=jEventO["sp"].ToStr(); //Stop Price. Please ignore with TRAILING_STOP_MARKET order 条件订单触发价格,对追踪止损单无效printf(" |Stop Price 条件订单触发价格 %s", averagePrice);
// 读取 x 字段,表示本次事件的执行类型,使用 ToStr 转换。// Read x for execution type for this event using ToStr.string executionType=jEventO["x"].ToStr(); //Execution Type 本次事件的具体执行类型printf(" |Execution Type 本次事件的具体执行类型 %s", executionType);
// 读取 X 字段,表示订单当前状态,使用 ToStr 转换。// Read X for current order status using ToStr.string orderStatus=jEventO["X"].ToStr(); //Order Status 订单的当前状态printf(" |Order Status 订单的当前状态 %s", orderStatus);
// 读取 i 字段,表示交易所订单 ID,使用 ToInt 转换。// Read i for exchange order ID using ToInt.long orderId=jEventO["i"].ToInt(); //Order Id 订单IDprintf(" |Order Id 订单ID %s", (string)orderId);
// 读取 l 字段,表示本次成交数量,使用 ToStr 转换。// Read l for last fill quantity using ToStr.string orderLastFilledQuantity=jEventO["l"].ToStr(); //Order Last Filled Quantity 订单末次成交量printf(" |Order Last Filled Quantity 订单末次成交量 %s", orderLastFilledQuantity);
// 读取 z 字段,表示累计成交数量,使用 ToStr 转换。// Read z for cumulative filled quantity using ToStr.string orderFilledAccumulatedQuantity=jEventO["z"].ToStr(); //Order Filled Accumulated Quantity 订单累计已成交量printf(" |Order Filled Accumulated Quantity 订单累计已成交量 %s", orderFilledAccumulatedQuantity);
// 读取 L 字段,表示本次成交价格,使用 ToStr 转换。// Read L for last fill price using ToStr.string lastFilledPrice=jEventO["L"].ToStr(); //Last Filled Price 订单末次成交价格printf(" |Last Filled Price 订单末次成交价格 %s", lastFilledPrice);
// 读取 N 字段,表示手续费资产,使用 ToStr 转换。// Read N for commission asset using ToStr.string commissionAsset=jEventO["N"].ToStr(); //Commission Asset 手续费资产类型printf(" |Commission Asset 手续费资产类型 %s", commissionAsset);
// 读取 n 字段,表示手续费金额,使用 ToStr 转换。// Read n for commission amount using ToStr.string commission=jEventO["n"].ToStr(); //Commission 手续费数量printf(" |Commission 手续费数量 %s", commission);
// 读取 T 字段,表示成交时间,单位为毫秒,使用 ToInt 转换。// Read T for trade time in milliseconds using ToInt.long orderTradeTime=jEventO["T"].ToInt(); //Order Trade Time 成交时间//convert API utc0 timestamp to local datetime 把API utc0时间戳转换成当前时区的时间// 将毫秒时间戳除以 1000 后转换为 datetime,再加上本例计算的本地时区偏移。// Divide the millisecond timestamp by 1000, convert it to datetime, and add the local time-zone offset calculated by this example.datetime orderTradeDateTime=(datetime)((long)orderTradeTime/1000)+timeZone*60*60;
printf(" |Order Trade Time 成交时间 %s %s", (string)orderTradeTime,(string)orderTradeDateTime);
// 读取 t 字段,表示成交 ID,使用 ToInt 转换。// Read t for trade ID using ToInt.long tradeId=jEventO["t"].ToInt(); //Trade Id 成交IDprintf(" |Trade Id 成交ID %s", (string)tradeId);
// 读取 b 字段,表示买单名义价值,使用 ToStr 转换。// Read b for bid notional using ToStr.string bidsNotional=jEventO["b"].ToStr(); //Bids Notional 买单净值printf(" |Bids Notional 买单净值 %s", bidsNotional);
// 读取 a 字段,表示卖单名义价值,使用 ToStr 转换。// Read a for ask notional using ToStr.string askNotional=jEventO["a"].ToStr(); //Ask Notional 卖单净值printf(" |Ask Notional 卖单净值 %s", askNotional);
// 读取 m 字段,表示是否为 maker 成交,使用 ToBool 转换。// Read m for whether the fill is on the maker side using ToBool.bool isMaker=jEventO["m"].ToBool(); //Is this trade the maker side? 该成交是作为挂单成交吗?printf(" |Is this trade the maker side? 该成交是作为挂单成交吗?%s", (string)isMaker);
// 读取 R 字段,表示是否仅减仓,使用 ToBool 转换。// Read R for whether the order is reduce-only using ToBool.bool isReduce=jEventO["R"].ToBool(); //Is this reduce only 是否是只减仓单printf(" |Is this reduce only 是否是只减仓单 %s", (string)isReduce);
// 读取 wt 字段,表示触发价格类型,使用 ToStr 转换。// Read wt for trigger price type using ToStr.string stopPriceWorkingType=jEventO["wt"].ToStr(); //Stop Price Working Type 触发价类型printf(" |Stop Price Working Type 触发价类型 %s", stopPriceWorkingType);
// 读取 ot 字段,表示原始订单类型,使用 ToStr 转换。// Read ot for original order type using ToStr.string originalOrderType=jEventO["ot"].ToStr(); // Original Order Type 原始订单类型printf(" |Original Order Type 原始订单类型 %s", originalOrderType);
// 读取 ps 字段,表示持仓方向,使用 ToStr 转换。// Read ps for position side using ToStr.string positionSide=jEventO["ps"].ToStr(); // Position Side 持仓方向printf(" |Position Side 持仓方向 %s", positionSide);
// 读取 cp 字段,表示是否为条件全平仓订单,使用 ToBool 转换。// Read cp for whether this is a conditional close-all order using ToBool.bool isCloseAll=jEventO["cp"].ToBool(); //If Close-All, pushed with conditional order 是否为触发平仓单; 仅在条件订单情况下会推送此字段printf(" |If Close-All 是否为触发平仓单 %s", (string)isCloseAll);
// 读取 AP 字段,表示追踪止损激活价格,使用 ToStr 转换。// Read AP for trailing-stop activation price using ToStr.string activationPrice=jEventO["AP"].ToStr(); //Activation Price, only puhed with TRAILING_STOP_MARKET order 追踪止损激活价格, 仅在追踪止损单时会推送此字段printf(" |Activation Price 追踪止损激活价格 %s", activationPrice);
// 读取 cr 字段,表示追踪止损回调比例,使用 ToStr 转换。// Read cr for trailing-stop callback rate using ToStr.string callBackRate=jEventO["cr"].ToStr(); // Callback Rate, only puhed with TRAILING_STOP_MARKET order 追踪止损回调比例, 仅在追踪止损单时会推送此字段printf(" |Activation Price 追踪止损激活价格 %s", callBackRate);
// 读取 pP 字段,表示是否开启条件单价格保护,使用 ToBool 转换。// Read pP for whether conditional-order price protection is enabled using ToBool.bool isPriceProtection=jEventO["pP"].ToBool(); //If price protection is turned on 是否开启条件单触发保护printf(" |If price protection is turned on 是否开启条件单触发保护 %s", (string)isPriceProtection);
// 读取 rp 字段,表示本次成交实现盈亏,使用 ToStr 转换。// Read rp for realized profit or loss for this trade using ToStr.string realizedProfit =jEventO["rp"].ToStr(); // Realized Profit of the trade 该交易实现盈亏printf(" |Realized Profit of the trade 该交易实现盈亏 %s", realizedProfit);
// 读取 V 字段,表示自成交防止模式,使用 ToStr 转换。// Read V for self-trade prevention mode using ToStr.string stpMode =jEventO["V"].ToStr(); // STP mode 自成交防止模式printf(" |If price protection is turned on 是否开启条件单触发保护 %s", stpMode);
// 读取 pm 字段,表示价格匹配模式,使用 ToStr 转换。// Read pm for price matching mode using ToStr.string PriceMatchMode =jEventO["pm"].ToStr(); //Price match mode 价格匹配模式printf(" |Price match mode 价格匹配模式 %s", PriceMatchMode);
// 读取 gtd 字段,表示GTD 订单自动取消时间,使用 ToInt 转换。// Read gtd for automatic cancellation time for a GTD order using ToInt.long gtd =jEventO["gtd"].ToInt(); //TIF GTD order auto cancel time TIF为GTD的订单自动取消时间printf(" |TIF GTD order auto cancel time TIF为GTD的订单自动取消时间 %s", (string)gtd);
}
}
}
//+------------------------------------------------------------------+//+------------------------------------------------------------------+//+------------------------------------------------------------------+