//+------------------------------------------------------------------+//| 币安U本位期货批量下单binanceUSDMarginFuturePlaceMultipleOrders.mq5 |//| Copyright 2024, MetaQuotes Ltd. |//| https://www.mql5.com |//+------------------------------------------------------------------+// 本例在首次收到行情时批量提交 ETHUSDT 限价买单和 BNBUSDT 限价卖单,随后分别撤销两个交易对的全部未成交订单。// On the first tick, submit an ETHUSDT limit BUY and a BNBUSDT limit SELL in one batch, then cancel all open orders for each symbol.#property copyright "Copyright 2024, MetaQuotes Ltd."#property link "https://www.mql5.com"#property version "1.00"//import MQL binance API 引入MQL币安API头文件#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#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// 网络延迟可能波动,recvWindow 用于限制请求时间戳与币安服务器时间之间允许的偏差,本例为 3000 毫秒。// Network latency can fluctuate. recvWindow limits the permitted difference between the request timestamp and Binance server time to 3000 milliseconds in this example.long recvWindow=3000;
//币安MQL接口使用的curl handles// 保存币安接口请求使用的 curl 句柄,在初始化时创建,在 EA 退出时释放。// Store the curl handles used for Binance API requests. Create them during initialization and release them when the EA exits.int handles[];
//binance reponse 币安返回数据// 保存币安同步返回的 JSON 数据,调用后使用 UTF-8 编码转换为字符串。// Store the synchronous Binance JSON response and convert it to a string using UTF-8 after the API call.staticchar resultChar[];
//Current Position Mode持仓模式// false 表示单向持仓模式,true 表示双向持仓模式,由持仓模式查询结果更新。// false means One-way Mode and true means Hedge Mode. Update this flag from the position-mode query response.bool isHedgeMode=false;
// 标记本次加载是否已执行批量下单及撤单流程,避免后续每个 tick 重复执行。// Track whether the batch submission and cancellation sequence has run during this attachment, preventing repetition on subsequent ticks.bool isRun=false;
//+------------------------------------------------------------------+//| Expert initialization function |//+------------------------------------------------------------------+intOnInit()
{
//--//initialize binance API key and secret key you set初始化你设置的币安API密钥// 先在 mt5binance 配置中设置所用环境的 API 密钥,再初始化币安接口凭据。// Configure API credentials for the selected environment in the mt5binance configuration before initializing the Binance API credentials.initBinanceAPIKey();
//初始化币安MQL接口使用的curl handles// 初始化 curl 全局状态,分配一个句柄槽位,再创建实际请求句柄。// Initialize the global curl state, allocate one handle slot, and create the request handle.curlGlobalInit();
ArrayResize(handles, 1);
curlInit(handles);
//set up length of resultChar 设置resultChar的字符长度// 为响应预留 10000 个字符元素,缓冲区需要足够容纳批量订单返回的 JSON。// Allocate 10000 character elements for the response buffer, which must accommodate the batch-order JSON response.ArrayResize(resultChar, 10000);
//Get user's position mode (Hedge Mode or One-way Mode) 查询持仓模式(双向持仓或单向持仓)// 调用 mt5binance.mqh 的 ufGetCurrentPositionMode 查询经典账号 U 本位合约持仓模式,JSON 返回到最后一个引用参数。// Call ufGetCurrentPositionMode from mt5binance.mqh to query the classic account USDⓈ-M Futures position mode. The final reference parameter receives the JSON response.ufGetCurrentPositionMode(handles, recvWindow, resultChar);
string result=CharArrayToString(resultChar, 0, -1, CP_UTF8);
// 使用 JAson.mqh 解析持仓模式响应,读取 code 判断币安是否返回错误。// Use JAson.mqh to deserialize the position-mode response and inspect code for a Binance API error.CJAVal jPositionMode;
jPositionMode.Deserialize(result);
long code=jPositionMode["code"].ToInt();
//binance API dont return error code 币安API没有返回错误代码if(code==0)
{
// 使用 JAson.mqh 解析持仓模式响应,读取 code 判断币安是否返回错误。// Use JAson.mqh to deserialize the position-mode response and inspect code for a Binance API error.CJAVal jPositionMode;
jPositionMode.Deserialize(result);
// dualSidePosition 为 true 时使用双向持仓模式,为 false 时使用单向持仓模式。// dualSidePosition is true for Hedge Mode and false for One-way Mode.
isHedgeMode=jPositionMode["dualSidePosition"].ToBool();
}
else
{
printf(result);
}
// 当前示例即使持仓模式查询返回错误,也仅打印响应并返回初始化成功,isHedgeMode 将保留默认值。// This example prints a position-mode query error but still returns initialization success, leaving isHedgeMode at its default value.return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+//| Expert deinitialization function |//+------------------------------------------------------------------+voidOnDeinit(constint reason)
{
//---// EA 退出时释放已创建的 curl 句柄。// Release the curl handles when the EA exits.curlCleanUp(handles);
printf("curlCleanUp");
}
//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+voidOnTick()
{
// 仅在本次加载首次收到行情时进入此流程。两个交易对都需要有可用的最新价格和合约属性。// Run this sequence only on the first tick after attachment. Both symbols need available last prices and contract properties.if(isRun==false)
{
//order size 100 usdt 下单100 usdt// 分别用 100 USDT 除以各自最新价格估算数量,再按合约数量精度取整;限价单的实际委托金额随挂单价格变化。// Estimate each quantity as 100 USDT divided by its last price, then normalize to the contract quantity precision. The actual limit-order notional depends on the submitted price.double orderSizeUsdt=100;
//get current ethusdt price 获取当前ethusdt价格string ethUsdt="ETHUSDT";
// 从 MT5 的 ETHUSDT 合约属性读取最新成交价,用于计算下单数量和限价。// Read the ETHUSDT last trade price from MT5 symbol properties to calculate the order quantity and limit price.double ethUsdtLast=SymbolInfoDouble(ethUsdt,SYMBOL_LAST);
//calculate order size precision计算下单数量精度// 读取 ETHUSDT 的最小数量步长,并据此推算下单数量的小数位数。// Read the ETHUSDT volume step and use it to derive the number of decimal places for the order quantity.double ethUsdtSizeStep=SymbolInfoDouble(ethUsdt, SYMBOL_VOLUME_STEP);
int ethUsdtSizePrecision=0;
if(ethUsdtSizeStep<1)
{
int ethUsdtPoint=StringFind((string)ethUsdtSizeStep,".",0);
string ethUsdtSizeStepPreicsion=StringSubstr((string)ethUsdtSizeStep, ethUsdtPoint+1);
ethUsdtSizePrecision=StringLen(ethUsdtSizeStepPreicsion);
}
else
{
ethUsdtSizePrecision=0;
}
//ethusdt size ethusdt多单数量// 数量精度必须符合交易所对该合约的要求,否则订单可能被拒绝。// The quantity precision must satisfy the exchange requirements for this contract, or the order may be rejected.double ethUsdtSize=NormalizeDouble(orderSizeUsdt/ethUsdtLast, ethUsdtSizePrecision);
//ethusdt price precision ethusdt下单价格精度// 通过 SYMBOL_DIGITS 获取价格小数位数,用于规范化 ETHUSDT 限价。// Use SYMBOL_DIGITS to obtain the decimal precision for normalizing the ETHUSDT limit price.int ethUsdtPricePrecision=(int)SymbolInfoInteger(ethUsdt, SYMBOL_DIGITS);
//buy at 20% lower 在最新价格往下20%挂买单// 按当前价格的 80% 设置 ETHUSDT 限价买单,即比最新价低 20%。// Set the ETHUSDT limit BUY price to 80% of the last price, which is 20% below the last price.double ethUsdtOrderPrice=NormalizeDouble(ethUsdtLast-ethUsdtLast*0.2, ethUsdtPricePrecision);
// 为第二笔订单读取 BNBUSDT 最新成交价,独立计算其数量及价格精度。// Read the BNBUSDT last trade price for the second order and calculate its quantity and price precision separately.string bnbUsdt="BNBUSDT";
double bnbUsdtLast=SymbolInfoDouble(bnbUsdt,SYMBOL_LAST);
//calculate order size precision计算下单数量精度// 读取 BNBUSDT 数量步长;步长小于 1 时,按小数部分长度推算精度。// Read the BNBUSDT volume step. For a step below 1, derive the precision from the length of its fractional part.double bnbUsdtSizeStep=SymbolInfoDouble(bnbUsdt, SYMBOL_VOLUME_STEP);
int bnbUsdtSizePrecision=0;
if(bnbUsdtSizeStep<1)
{
int bnbUsdtPoint=StringFind((string)bnbUsdtSizeStep,".",0);
string bnbUsdtSizeStepPreicsion=StringSubstr((string)bnbUsdtSizeStep, bnbUsdtPoint+1);
bnbUsdtSizePrecision=StringLen(bnbUsdtSizeStepPreicsion);
}
else
{
// 此分支在数量步长不小于 1 时使用一位小数,这是当前示例的既有设置。// This branch uses one decimal place when the volume step is at least 1, as configured in the existing example.
bnbUsdtSizePrecision=1;
}
// 按 BNBUSDT 最新价格估算数量,再转换为前面计算的数量精度。// Estimate the BNBUSDT quantity from its last price and normalize it to the quantity precision calculated above.double bnbUsdtSize=NormalizeDouble(orderSizeUsdt/bnbUsdtLast, bnbUsdtSizePrecision);
//calculate bnbusdt price precision bnbusdt下单价格精度// 通过 SYMBOL_DIGITS 获取 BNBUSDT 价格小数位数。// Read the BNBUSDT price precision from SYMBOL_DIGITS.int bnbUsdtPricePrecision=(int)SymbolInfoInteger(bnbUsdt, SYMBOL_DIGITS);
//sell at 20% higher 在最新价格往上20%挂卖单// 按当前价格的 120% 设置 BNBUSDT 限价卖单,即比最新价高 20%。// Set the BNBUSDT limit SELL price to 120% of the last price, which is 20% above the last price.double bnbUsdtOrderPrice=NormalizeDouble(bnbUsdtLast+bnbUsdtLast*0.2, bnbUsdtPricePrecision);
// 批量下单参数 orders 是 JSON 数组,每个数组元素描述一笔订单。// The orders parameter is a JSON array in which each element describes one order.string orders="";
//my EA order unique indentify 本EA订单唯一标识// 用 EA 名称、交易对标识与系统启动后的毫秒数构造客户订单号,区分本 EA 的两笔订单。// Build client order IDs from the EA name, symbol identifier, and milliseconds since system startup to distinguish the two orders.string myEthUsdtOrder="ea1002Eth"+(string)GetTickCount();
string myBnbUsdtOrder="ea1002Bnb"+(string)GetTickCount();
// 单向持仓模式下省略 positionSide;双向持仓模式下,ETH 买单指定 LONG,BNB 卖单指定 SHORT。// Omit positionSide in One-way Mode. In Hedge Mode, specify LONG for the ETH BUY and SHORT for the BNB SELL.// type=LIMIT 表示限价单,timeInForce=GTC 表示持续有效直至成交或撤销;symbol、side、price、quantity 和 newClientOrderId 分别指定交易对、方向、价格、数量和客户订单号。// type=LIMIT selects a limit order and timeInForce=GTC keeps it active until filled or canceled. symbol, side, price, quantity, and newClientOrderId specify the trading symbol, order side, price, quantity, and client order ID.if(isHedgeMode==false) //单向持仓模式 position one way mode
{
orders="[{\"type\":\"LIMIT\",\"timeInForce\":\"GTC\",\"symbol\":\"ETHUSDT\",\"side\":\"BUY\",\"price\":\""+(string)ethUsdtOrderPrice+"\",\"quantity\":\""+ (string)ethUsdtSize + "\",\"newClientOrderId\":\""+myEthUsdtOrder+"\"},"+
"{\"type\":\"LIMIT\",\"timeInForce\":\"GTC\",\"symbol\":\"BNBUSDT\",\"side\":\"SELL\",\"price\":\""+(string)bnbUsdtOrderPrice+"\",\"quantity\":\""+(string)bnbUsdtSize+"\",\"newClientOrderId\":\""+myBnbUsdtOrder+"\"}]";
}
else//双向持仓模式 position hedge mode
{
orders="[{\"type\":\"LIMIT\",\"timeInForce\":\"GTC\",\"symbol\":\"ETHUSDT\",\"side\":\"BUY\",\"positionSide\":\"LONG\",\"price\":\""+(string)ethUsdtOrderPrice+"\",\"quantity\":\""+ (string)ethUsdtSize + "\",\"newClientOrderId\":\""+myEthUsdtOrder+"\"},"+
"{\"type\":\"LIMIT\",\"timeInForce\":\"GTC\",\"symbol\":\"BNBUSDT\",\"side\":\"SELL\",\"positionSide\":\"SHORT\",\"price\":\""+(string)bnbUsdtOrderPrice+"\",\"quantity\":\""+(string)bnbUsdtSize+"\",\"newClientOrderId\":\""+myBnbUsdtOrder+"\"}]";
}
//printf(orders);//send two open orders in one go: long 100 usdt ethusdt and short 100 usdt bnbusdt//一次发送两个挂单: 多100usdt ethusdt 空100usdt bnbusdt// 调用 mt5binance.mqh 的 ufPlaceMultipleOrders 一次提交两笔订单。批量响应中每笔订单可能分别成功或失败,需要逐项查看返回结果。// Call ufPlaceMultipleOrders from mt5binance.mqh to submit both orders in one request. Individual orders can succeed or fail independently, so inspect each result in the batch response.ufPlaceMultipleOrders(handles, orders,recvWindow,resultChar);
// 将批量下单同步响应转换为 UTF-8 字符串并输出,便于检查订单结果或错误信息。// Convert the synchronous batch-order response to a UTF-8 string and print it to inspect order results or API errors.string result=CharArrayToString(resultChar, 0, -1, CP_UTF8);
printf(result);
//close all open orders全部撤单// 撤销 ETHUSDT 的全部未成交订单,包括其他 EA 或手动创建的订单。此接口不会平掉已成交仓位。// Cancel all open ETHUSDT orders, including orders created manually or by other EAs. This API does not close filled positions.ufCancelAllOpenOrders(handles, "ETHUSDT", recvWindow, resultChar);
result=CharArrayToString(resultChar, 0, -1, CP_UTF8);
printf(result);
// 同样撤销 BNBUSDT 的全部未成交订单,并打印撤单响应。下单与撤单之间没有等待成交的步骤。// Likewise cancel all open BNBUSDT orders and print the cancellation response. This example does not wait for fills between submission and cancellation.ufCancelAllOpenOrders(handles, "BNBUSDT", recvWindow, resultChar);
result=CharArrayToString(resultChar, 0, -1, CP_UTF8);
printf(result);
// 无论请求成功与否都标记流程已执行,本次加载后续 tick 不会自动重试。// Mark the sequence as completed regardless of request success. Subsequent ticks during this attachment do not retry it automatically.
isRun=true;
}
}
//+------------------------------------------------------------------+//get binance call back event via OnChartEvent 从OnChartEvent得到币安推送事件// OnChartEvent 是 MQL5 的预定义图表事件处理函数,MT5 在收到图表交互或自定义事件时调用它。// OnChartEvent is a predefined MQL5 chart-event handler called by MT5 for chart interactions and custom events.// 本接口通过该函数接收币安异步推送,处理方式参考示例 1001。// This API receives asynchronous Binance push events through this handler, following example 1001.// 批量下单函数返回的是同步响应;后续订单状态、成交及账户变化通过推送事件单独处理。// The batch-order function returns a synchronous response. Later order-status, fill, and account changes are handled separately through push events.//// id 表示事件类型,本接口的币安推送事件使用 3333,用它区分普通图表事件。// id identifies the event type. This API uses 3333 for Binance push events to distinguish them from ordinary chart events.// lparam 是事件附带的 long 参数,其含义由事件类型决定,本示例不读取它。// lparam is the event's long parameter. Its meaning depends on the event type, and this example does not read it.// dparam 是事件附带的 double 参数,其含义由事件类型决定,本示例不读取它。// dparam is the event's double parameter. Its meaning depends on the event type, and this example does not read it.// sparam 是事件附带的字符串参数,币安事件需先交给 processChartEventMsg 转换为 JSON 字符串。// sparam is the event's string parameter. Pass it to processChartEventMsg to obtain the Binance JSON payload.// const 引用参数由 MT5 传入,处理函数读取这些参数以识别并解析事件。// MT5 supplies the const reference parameters for the handler to identify and decode the event.voidOnChartEvent(constint id,
constlong &lparam,
constdouble &dparam,
conststring &sparam)
{
// 币安推送事件使用 ID 3333;与普通图表交互事件区分后,再解析事件数据。// Binance push events use ID 3333. Distinguish them from ordinary chart interaction events before parsing their data.if(id==3333) //all binance event ID are 3333 币安推送事件代号都是3333
{
// 通过 processChartEventMsg 提取币安事件 JSON,供 JAson.mqh 反序列化。// Use processChartEventMsg to extract the Binance event JSON for deserialization with JAson.mqh.string event = processChartEventMsg(sparam);
// 币安事件是 JSON 对象,使用 JAson.mqh 的 CJAVal 解析,后续通过字段名读取数据。// Binance events are JSON objects. Deserialize them with CJAVal from JAson.mqh, then access their fields by name.// 实际处理时应检查 Deserialize 的返回值,解析成功后再读取事件字段。// When implementing event processing, check the return value of Deserialize before reading event fields.CJAVal jEvent;
jEvent.Deserialize(event);
}
}
//+------------------------------------------------------------------+