How can MQL5 place a Binance USDⓈ-M futures market order?
Call ufNewOrder through the MT5 Binance MQL API. This example uses a Binance Classic account. After initialization and a position-mode query, the EA handles its first tick, calculates an order quantity from a target notional of 30 USDT for the current chart symbol, and sends a SELLMARKET order. It then parses the synchronous response and receives asynchronous order and account events.
What do you need to run this EA?
Install and configure the MT5 Binance connection software and start the relevant market data and trading services. See the installation guide.
Use a Binance Classic account and configure API keys with the appropriate USDⓈ-M futures trading permissions. See API key setup.
Make mt5binance.mqh and JAson.mqh available to MQL5. The former provides the Binance interfaces; the latter parses JSON using CJAVal.
Attach the EA to the chart for the intended Binance symbol. Ensure market data and SYMBOL_LAST are valid, and that the account and order quantity meet the exchange’s current requirements.
How does the code execute?
Initialize:OnInit() calls initBinanceAPIKey(), initializes curl handles, and queries position mode through ufGetCurrentPositionMode. It returns INIT_FAILED when the code detects an error.
Calculate quantity:OnTick() reads the latest price for Symbol() and applies NormalizeDouble to 30 / last, using decimal places derived from SYMBOL_VOLUME_STEP.
Submit a market sell order: Set SELL and MARKET. Use BOTH in One-way Mode or SHORT in Hedge Mode, then call ufNewOrder.
Parse the synchronous response: Convert resultChar to a UTF-8 string and use CJAVal to read order fields or print the error response. Set isRun=true after this attempt.
Handle asynchronous events:OnChartEvent() filters for id==3333, calls processChartEventMsg, and parses TRADE_LITE, ORDER_TRADE_UPDATE and ACCOUNT_UPDATE.
Clean up:OnDeinit() calls curlCleanUp(handles) to release the handles.
What are the default parameters?
Parameter
Default value
Purpose in this example
symbol
Symbol()
The current chart symbol; not hard-coded to BTCUSDT.
side / type
SELL / MARKET
A market sell order without a limit price.
orderSizeUsdt
30
Target notional used to calculate quantity, not margin. The final executed notional is not guaranteed to be exactly 30 USDT.
positionSide
BOTH / SHORT
Selected according to the queried One-way or Hedge position mode.
recvWindow
3000
A request timing window of 3,000 milliseconds. See timing security.
price / goodTillDate
0 / 0
This market order does not specify a price or a GTD cancellation time.
newClientOrderId
"1001ea" + GetTickCount()
A sample client order ID construction method, not a guarantee of uniqueness across processes or restarts.
//+------------------------------------------------------------------+//| 币安U本位期货下单binanceUSDMarginFutureNewOrder.mq5 | Binance USD-M futures new order example: binanceUSDMarginFutureNewOrder.mq5.//| Copyright 2024, MetaQuotes Ltd. |//| https://www.mql5.com |//+------------------------------------------------------------------+//本例子演示了收到行情后马上发送U本位合约的市价单(经典账号) This example sends a USD-M futures market order immediately after receiving a tick, using a Classic account.//import MQL binance API//引入币安MQL接口的头文件 Include the Binance MQL API header.#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 the open-source JSON library from mql5.com to deserialize Binance JSON responses: https://www.mql5.com/en/code/13663#include <JAson.mqh>//setup Timing security https://developers.binance.com/docs/derivatives/usds-margined-futures/general-info#timing-security//互联网状况并不完全稳定可靠,因此您的程序本地到币安服务器的时延会有抖动,这是设置recvWindow参数的原因 Network conditions vary, so latency between the local program and Binance servers can fluctuate. This is why recvWindow is configured.//币安服务器会检查每个请求的时间戳与币安服务器时间的偏差是否在 recvWindow 允许的范围内。如果偏差超过 recvWindow,请求将被拒绝 Binance checks whether each request timestamp is within the permitted recvWindow relative to server time. Requests outside the window are rejected.//如果您从事高频交易,对交易时效性有较高的要求,可以灵活设置 recvWindow 以达到您的要求 For high-frequency trading with stricter timing requirements, adjust recvWindow to suit your requirements.//币安关于recvWindow官方文档 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 Official Binance recvWindow documentation: https://developers.binance.com/docs/derivatives/usds-margined-futures/general-info#timing-security//本例子的时间同步安全设置为3秒 The request timing window in this example is three seconds.long recvWindow=3000;
//curl handlesint handles[];
//binance response 币安返回数据 Binance response data.staticchar resultChar[];
//Current Position Mode持仓模式 Current position mode.bool isHedgeMode=false;
//size precision 下单数量精度 Order quantity precision.int sizePrecision=0;
bool isRun=false;
//+------------------------------------------------------------------+//| Expert initialization function |//+------------------------------------------------------------------+intOnInit()
{
//initialize binance API key and secret key you set//币安官方提供API,本软件在MT5通过币安这些API去实现量化交易 Binance provides the APIs; this software exposes them in MT5 for quantitative trading.//您需要先自行创建币安账号的API密钥并设置到MT5 Create API keys for your Binance account and configure them in MT5 first.//下面是EA初始化您的币安API密钥后就可以进行交易 Initialize the configured Binance API keys before trading.initBinanceAPIKey();
//初始化curl handles Initialize curl handles.curlGlobalInit();
ArrayResize(handles, 1);
curlInit(handles);
//set up length of resultChar//resultChar是用来接受币安返回的JSON, 设置resultChar的字符长度要足够长 resultChar receives the Binance JSON response. Allocate a sufficiently large character buffer.ArrayResize(resultChar, 10000);
//Get Current Position Mode//调用mt5binance.mqh中的MQL函数ufGetCurrentPositionMode查询持仓模式, 将返回的JSON赋值resultChar Call ufGetCurrentPositionMode from mt5binance.mqh to query position mode and store the JSON response in resultChar.//该MQL函数对应币安官方查询持仓模式API,该MQL函数调用参数和安官方查询持仓模式API一致, This MQL function corresponds to the official Binance position-mode query API and uses matching parameters.//该MQL函数返回的数据就是安官方查询持仓模式API所返回的数据,保存在最后一个引用参数resultChar中 The function returns the original Binance API response through its final reference parameter, resultChar.ufGetCurrentPositionMode(handles, recvWindow, resultChar);
string result=CharArrayToString(resultChar, 0, -1, CP_UTF8);
//返回的JSON数据格式如下 The response JSON format is shown below./*
{
"dualSidePosition": true // "true": 双向持仓模式;"false": 单向持仓模式 true: Hedge Mode; false: One-way Mode.
}
*///deserialize binance response JSON//反序列化币安返回的JSON Deserialize the Binance JSON response.CJAVal jPositionMode;
jPositionMode.Deserialize(result);
//如果币安返回错误会放在code键 If Binance returns an error, its code is stored in the code field.long code=jPositionMode["code"].ToInt();
//binance API dont return error code//币安没有返回错误代码,成功获得持仓模式 No error code was returned; the position mode was retrieved successfully.if(code==0)
{
//dualSidePosition键的值就是持仓模式 The dualSidePosition field identifies the position mode.
isHedgeMode=jPositionMode["dualSidePosition"].ToBool();
//price precision//币安每个合约有不同的价格精度(例如ethusdt是小数后两位), 下单的价格必须是币安规定的该合约的价格精度,否则下单会失败 Each Binance contract has its own price precision, for example two decimal places for ETHUSDT in this example. An order price with invalid precision will be rejected.//通过属性SYMBOL_DIGITS获得当前图表合约的价格精度 Read the current chart symbol price precision from SYMBOL_DIGITS.long pricePrecision=SymbolInfoInteger(Symbol(), SYMBOL_DIGITS);
//calculate order size precision//币安每个合约有不同的下单数量精度,下单的数量精度必须是币安规定该合约的数量精度, 否则下单会失败 Each Binance contract has its own order quantity precision. An order quantity with invalid precision will be rejected.//通过合约属性SYMBOL_VOLUME_STEP获得当前图表的合约数量精度 Read the symbol quantity increment from SYMBOL_VOLUME_STEP.double sizeStep=SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_STEP);
if(sizeStep<1)
{
int point=StringFind((string)sizeStep,".",0);
string sizeStepPreicsion=StringSubstr((string)sizeStep, point+1);
sizePrecision=StringLen(sizeStepPreicsion);
}
else
{
sizePrecision=0;
}
printf("sizePrecision %d", sizePrecision);
return(INIT_SUCCEEDED);
}
else//币安返回了错误代码,EA初始化失败 Binance returned an error code; EA initialization failed.
{
printf(result);
return(INIT_FAILED);
}
}
//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+voidOnTick()
{
if(isRun==false)
{
//get current price//取得合约当前价格,和外汇EA一样 Get the current contract price as in a forex EA.double last=SymbolInfoDouble(Symbol(),SYMBOL_LAST);
//做空 Sell / short direction.string side="SELL";
//持仓模式 Position mode.string positionSide="";
//position one way mode//单向持仓模式下,一个合约只允许持有一个方向的仓位。如果您持有多单,则无法同时持有空单;反之亦然 In One-way Mode, a contract holds a position in only one direction: long or short, not separate long and short positions simultaneously.if(isHedgeMode==false)
{
positionSide="BOTH";
}
//position hedge mode//双向持仓模式下,一个合约可允许同时持有多空两个方向的仓位,并且同一合约下不同方向仓位风险对冲 Hedge Mode allows simultaneous long and short positions in the same contract with opposing directional exposure.else
{
positionSide="SHORT";
}
//根据您的策略选择不同的下单类型,本例子是下市价单 Select the order type for your strategy. This example uses a market order.string type="MARKET";
//市价单没有timeInForce A market order does not use timeInForce.string timeInForce="";
string reduceOnly="";
//new order 30 usdt//下单金额是30 usdt The target order notional is 30 USDT.double orderSizeUsdt=30;
//计算下单金额30 usdt对应多少下单数量 Calculate the quantity corresponding to a target notional of 30 USDT.//下单的数量精度必须是币安规定该合约的数量精度,否则下单会失败,所以下单前将计算后的下单数量转换成该合约规定的数量精度 The quantity must satisfy the contract precision requirements. Normalize the calculated quantity to the derived number of decimal places before submitting it.double orderSize=NormalizeDouble(orderSizeUsdt/last, sizePrecision);
double quantity=orderSize;
//market order no need price//市价单不需要价格 A market order does not require a limit price.double price=0;
//my ea order indentify//发单前我们自定义这个订单的标识,非常重要,是该订单属于哪个EA的标识,类似于外汇EA中的magic number Assign a client order identifier before submission to identify the originating EA, similarly to a magic number in a forex EA.//我们必须保证每个订单的标识是唯一的,需要保证两个唯一,1.该订单标识在本EA内是唯一的(不同订单不同标识) 2.如果有多个EA并行,该订单标识也是唯一的 Each order identifier must be unique within this EA and across multiple EAs running concurrently.//所以本例子中使用:EA名字 + 返回自操作系统启动以来所经过的毫秒数 来保证该订单标识达到以上两个唯一 This example combines an EA name with milliseconds elapsed since the operating system started to construct its order identifier.string newClientOrderId="1001ea"+IntegerToString(GetTickCount());
string newOrderRespType="";
string priceMatch="";
string selfTradePreventionMode="";
//市价单不需要自动取消时间 A market order does not require an automatic cancellation time.long goodTillDate=0;
//调用mt5binance.mqh中的MQL函数ufNewOrder下单 Call ufNewOrder from mt5binance.mqh to submit the order.//该MQL函数对应币安官方U本位合约下单API,该MQL函数调用参数和安官方API参数一致 This MQL function corresponds to the official Binance USD-M futures new-order API and uses matching parameters.//该MQL函数返回的数据即是安官方下单API所返回的数据 The function returns the response provided by the Binance new-order API.//其中的参数recvWindow是互联网状况并不完全稳定可靠,因此您的程序本地到币安服务器的时延会有抖动, recvWindow accommodates fluctuating latency between the local program and Binance servers.//币安服务器会检查每个请求的时间戳与币安服务器时间的偏差是否在recvWindow允许的范围内,如果偏差超过recvWindow(本例子是3秒),请求将被拒绝 Binance rejects requests whose timestamp falls outside recvWindow relative to server time; this example uses three seconds.//如果您从事高频交易,对交易时效性有较高的要求,可以灵活设置 recvWindow 以达到您的要求 For high-frequency trading, adjust recvWindow to your timing requirements.//币安关于recvWindow的官方文档 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 Official recvWindow documentation: https://developers.binance.com/docs/derivatives/usds-margined-futures/general-info#timing-securityufNewOrder(handles, Symbol(), side, positionSide, type, timeInForce, reduceOnly, quantity, price, newClientOrderId, newOrderRespType, priceMatch, selfTradePreventionMode, goodTillDate, recvWindow, resultChar);
//调用后币安同步返回下单结果,将其保存在最后一个引用参数resultChar中(币安异步返回的事件在OnChartEvent中处理) The synchronous order response is stored in the final reference parameter, resultChar. Asynchronous events are handled in OnChartEvent.//将字符数组resultChar换成字符串result Convert the resultChar character array to the result string.string result=CharArrayToString(resultChar, 0, -1, CP_UTF8);
//币安返回的JSON格式举例 Example Binance JSON response./*
{
"clientOrderId": "testOrder", // 用户自定义的订单号 User-defined client order ID
"cumQty": "0",
"cumQuote": "0", // 成交金额 — 迁移后会移除 Quote amount traded; marked for removal after migration in this sample
"executedQty": "0", // 成交量 Executed quantity
"orderId": 22542179, // 系统订单号 Exchange order ID
"avgPrice": "0.00000", // 平均成交价 — 迁移后会移除 Average fill price; marked for removal after migration in this sample
"origQty": "10", // 原始委托数量 Original order quantity
"price": "0", // 委托价格 Order price
"reduceOnly": false, // 仅减仓 Reduce only
"side": "SELL", // 买卖方向 Order side
"positionSide": "SHORT", // 持仓方向 Position side
"status": "NEW", // 订单状态 Order status
"stopPrice": "0", // 触发价,`LIMIT`/`MARKET` 订单忽略此字段 Trigger price; ignored for LIMIT and MARKET orders
"closePosition": false, // 是否条件全平仓 Whether the conditional order closes the entire position
"symbol": "BTCUSDT", // 交易对 Trading symbol
"timeInForce": "GTD", // 有效方法 Time in force
"type": "LIMIT", // 订单类型 Order type
"origType": "LIMIT", // 触发前订单类型 Original order type before triggering
"updateTime": 1566818724722, // 更新时间 Update time
"workingType": "CONTRACT_PRICE", // 条件价格触发类型 Trigger price type
"priceProtect": false, // 是否开启条件单触发保护 Whether conditional-order price protection is enabled
"priceMatch": "NONE", //盘口价格下单模式 Price matching mode
"selfTradePreventionMode": "NONE", //订单自成交保护模式 Self-trade prevention mode
"goodTillDate": 1693207680000 //订单TIF为GTD时的自动取消时间 Automatic cancellation time for a GTD order
}
*///deserialize binance response JSON//反序列化币安返回的数据 Deserialize the Binance response.CJAVal jOrder;
jOrder.Deserialize(result);
//binance API dont return error code//如果币安返回错误会放在返回JSON的code键 If Binance returns an error, its code appears in the response JSON code field.long code=jOrder["code"].ToInt();
//币安没有返回错误代码,下单成功,处理币安同步返回的数据 No error code was returned; process the synchronous order response.if(code==0)
{
printf(result);
//键s的值是交易对 The symbol field identifies the trading pair.string eventSymbol=jOrder["symbol"].ToStr();
printf("symbol 交易对: %s", eventSymbol);
//键clientOrderId的值是用户自定义的订单号 Field clientOrderId: User-defined client order ID.string clientOrderId=jOrder["clientOrderId"].ToStr();
printf("clientOrderId 用户自定义的订单号: %s", clientOrderId);
string cumQty=jOrder["cumQty"].ToStr();
printf("cumQty: %s", cumQty);
//键cumQuote的值是成交金额,该值是浮点数,反序列化成double变量 The cumQuote field is the quote amount traded. Deserialize this numeric value as double.double cumQuote=jOrder["cumQuote"].ToDbl();
printf("cumQuote成交金额: %s", (string)cumQuote);
//键executedQty的值是成交量,该值是浮点数,反序列化成double变量 Field executedQty: Executed quantity. Deserialize as double.double executedQty=jOrder["executedQty"].ToDbl();
printf("executedQty成交量: %s", (string)executedQty);
//键orderId的值是系统订单号 Field orderId: Exchange order ID.string orderId=jOrder["orderId"].ToStr();
printf("orderId系统订单号: %s", orderId);
//键avgPrice的值是平均成交价,该值是浮点数,反序列化成double变量 The avgPrice field is the average fill price. Deserialize this numeric value as double.double avgPrice=jOrder["avgPrice"].ToDbl();
printf("avgPrice平均成交价: %s", (string)avgPrice);
//键origQty的值是原始委托数量,该值是浮点数,反序列化成double变量 Field origQty: Original order quantity. Deserialize as double.double origQty=jOrder["origQty"].ToDbl();
printf("origQty: 原始委托数量%s", (string)origQty);
//键price的值是委托价格,该值是浮点数,反序列化成double变量 Field price: Order price. Deserialize as double.double price2=jOrder["price"].ToDbl();
printf("price委托价格: %s", (string)price2);
//键reduceOnly的值是仅减仓 Field reduceOnly: Reduce only.string reduceOnly2=jOrder["reduceOnly"].ToStr();
printf("reduceOnly仅减仓: %s", reduceOnly2);
//键side的值是买卖方向 Field side: Order side.string side2=jOrder["side"].ToStr();
printf("side买卖方向: %s", side2);
//键positionSide的值是持仓方向 Field positionSide: Position side.string positionSide2=jOrder["positionSide"].ToStr();
printf("positionSide持仓方向: %s", positionSide2);
//键status的值是订单状态 Field status: Order status.string status=jOrder["status"].ToStr();
printf("status订单状态: %s", status);
//please ignore when order type is TRAILING_STOP_MARKET//键stopPrice的值是触发价,对`TRAILING_STOP_MARKET`无效,该值是浮点数,反序列化成double变量 The stopPrice field is the trigger price; it is not applicable to TRAILING_STOP_MARKET in this example. Deserialize the numeric value as double.double stopPrice=jOrder["stopPrice"].ToDbl();
printf("stopPrice触发价: %s", (string)stopPrice);
// if Close-All//键closePosition的值是是否条件全平仓 Field closePosition: Whether the conditional order closes the entire position.string closePosition=jOrder["closePosition"].ToStr();
printf("closePosition是否条件全平仓: %s", closePosition);
//键timeInForce的值是有效方法 Field timeInForce: Time in force.string timeInForce2=jOrder["timeInForce"].ToStr();
printf("timeInForce有效方法: %s", timeInForce2);
//键type的值是订单类型 Field type: Order type.string type2=jOrder["type"].ToStr();
printf("type订单类型: %s", type2);
//键origType的值是订单类型 Field origType: Order type.string origType=jOrder["origType"].ToStr();
printf("origType订单类型: %s", origType);
//键updateTime的值是更新时间 Field updateTime: Update time.string updateTime=jOrder["updateTime"].ToStr();
printf("updateTime更新时间: %s", (string)updateTime);
//键workingType的值是条件价格触发类型 Field workingType: Trigger price type.string workingType=jOrder["workingType"].ToStr();
printf("workingType条件价格触发类型: %s", workingType);
//if conditional order trigger is protected//键priceProtect的值是是否开启条件单触发保护 Field priceProtect: Whether conditional-order price protection is enabled.string priceProtect=jOrder["priceProtect"].ToStr();
printf("priceProtect是否开启条件单触发保护: %s", priceProtect);
//price match mode//键priceMatch的值是盘口价格下单模式 Field priceMatch: Price matching mode.string priceMatch2=jOrder["priceMatch"].ToStr();
printf("price match mode盘口价格下单模式: %s", priceMatch2);
//self trading preventation mode//键selfTradePreventionMode的值是订单自成交保护模式 Field selfTradePreventionMode: Self-trade prevention mode.string selfTradePreventionMode2=jOrder["selfTradePreventionMode"].ToStr();
printf("self trading preventation mode订单自成交保护模式: %s", selfTradePreventionMode2);
//order pre-set auot cancel time for TIF GTD order//键goodTillDate的值是订单TIF为GTD时的自动取消时间 Field goodTillDate: Automatic cancellation time for a GTD order.string goodTillDate2=jOrder["goodTillDate"].ToStr();
printf("order pre-set auot cancel time for TIF GTD order订单TIF为GTD时的自动取消时间: %s", goodTillDate2);
}
else//币安返回了错误代码,下单失败,输出原因 Binance returned an error code; order submission failed. Print the response.
{
printf(result);
}
isRun=true;
}
}
//+------------------------------------------------------------------+//get binance call back event via OnChartEvent//OnChartEvent函数是MQL中的一个预定义事件处理函数,当用户在图表上进行操作(如点击、按键、移动鼠标等),MT5会自动调用此函数 OnChartEvent is a predefined MQL event handler invoked by MT5 for chart interactions such as clicks, keystrokes and mouse movements.//本软件可以通过 OnChartEvent函数得到币安异步推送事件 This software delivers 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)
{
//all binance event ID are 3333 币安推送事件代号都是3333 Binance push events use event ID 3333.if(id==3333)
{
//process binance event string 处理币安事件字符串 Process the Binance event string.string event = processChartEventMsg(sparam);
CJAVal jEvent;
//币安推送的事件都是JSON数据格式 Binance event payloads are JSON data.//使用JAson.mqh反序列化该事件JSON数据 Use JAson.mqh to deserialize the event JSON.//deserialize binance response JSON 反序列化币安返回的JSON Deserialize the Binance event JSON.
jEvent.Deserialize(event);
//获取该事件类型 Read the event type.string e=jEvent["e"].ToStr();
//calculate local timezone//计算本地电脑的时区 Calculate the local computer time zone.int timeZone=(int)(TimeLocal()-TimeGMT())/60/60;
//printf("local timezone %d", timeZone);//Event: Trade Lite Update https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Trade-Lite//下单后币安会推送精简交易事件 After order submission, Binance may push a Trade Lite event.//币安该事件的文档https://developers.binance.com/docs/zh-CN/derivatives/usds-margined-futures/user-data-streams/Event-Trade-Lite Official event documentation: https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Trade-Lite//该事件返回的JSON格式举例 Example JSON payload for this event./*
{
"e":"TRADE_LITE", // 事件类型 Event type
"E":1721895408092, // 事件时间 Event time
"T":1721895408214, // 交易时间 Transaction time
"s":"BTCUSDT", // 交易对 Trading symbol
"q":"0.001", // 订单原始数量 Original order quantity
"p":"0", // 订单原始价格 Original order price
"m":false, // 该成交是作为挂单成交吗? Whether this fill is on the maker side
"c":"z8hcUoOsqEdKMeKPSABslD", // 客户端自定订单ID Client order ID
// 特殊的自定义订单ID: Special client order identifiers:
// "autoclose-"开头的字符串: 系统强平订单 autoclose- prefix: a liquidation order.
// "adl_autoclose": ADL自动减仓订单 adl_autoclose: an auto-deleveraging order.
// "settlement_autoclose-": 下架或交割的结算订单 settlement_autoclose-: a delisting or delivery settlement order.
"S":"BUY", // 订单方向 Order side
"L":"64089.20", // 订单末次成交价格 Last fill price
"l":"0.040", // 订单末次成交量 Last fill quantity
"t":109100866, // 成交ID Trade ID
"i":8886774, // 订单ID Order ID
}*///Event Type//根据键e的值(事件类型)判断是精简交易事件 Use the e field to identify a Trade Lite event.if(e=="TRADE_LITE")
{
long eventTime=jEvent["E"].ToInt(); //Event Time 事件时间 Event time.printf("TRADE_LITE|Event Time 事件时间 %s", (string)eventTime);
//Transaction Time//键T的值是交易时间,该值是整形(时间戳),反序列化成int变量 The T field is the transaction timestamp; read it as an integer timestamp.long transactionTime=jEvent["T"].ToInt();
printf(" |Transaction Time 交易时间 %s", (string)transactionTime);
//symbol//键s的值是交易对 Field s: Trading symbol.string eventSymbol=jEvent["s"].ToStr();
printf(" |symbol 交易对 %s", eventSymbol);
//Original Quantity//键q的值是订单原始数量 Field q: Original order quantity.string originalQuantity=jEvent["q"].ToStr();
printf(" |Original Quantity 订单原始数量 %s", originalQuantity);
//Original Price//键p的值是订单原始价格 Field p: Original order price.string originalPrice=jEvent["p"].ToStr();
printf(" |Original Price 订单原始价格 %s", originalPrice);
//Is this trade the maker side?//键m的值是该成交是作为挂单成交吗?该值是布尔型,反序列化成bool变量 The m field indicates whether the fill is on the maker side. Deserialize this Boolean value as bool.bool isMaker=jEvent["m"].ToBool();
printf(" |Is this trade the maker side? 该成交是作为挂单成交吗? %s", (string)isMaker);
//Client Order Id//键c的值是客户端自定订单ID Field c: Client order ID.string clientOrderId=jEvent["c"].ToStr();
printf(" |Client Order Id 客户端自定订单ID %s", clientOrderId);
//Side//键S的值是订单方向 Field S: Order side.string side=jEvent["S"].ToStr();
printf(" |Side 订单方向 %s", side);
//Last Filled Price//键L的值是订单末次成交价格 Field L: Last fill price.string lastFilledPrice=jEvent["L"].ToStr();
printf(" |Last Filled Price 订单末次成交价格 %s", lastFilledPrice);
//Order Last Filled Quantity//键l的值是订单末次成交量 Field l: Last fill quantity.string orderLastFilledQuantity=jEvent["l"].ToStr();
printf(" |Order Last Filled Quantity 订单末次成交量 %s", orderLastFilledQuantity);
//Trade Id//键t的值是成交ID,该值是整数,反序列化成long变量 Field t: Trade ID. Deserialize as long.long tradeId=jEvent["t"].ToInt();
printf(" |Trade Id 成交ID %d", tradeId);
//Order Id//键i的值是订单ID,该值是整数,反序列化成long变量 Field i: Order ID. Deserialize as long.long orderId=jEvent["i"].ToInt();
printf(" |Order Id 订单ID %d", orderId);
}
//Event: Order Update https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Order-Update//下单后币安会推送订单交易更新事件 After order submission, Binance may push an order trade update event.//该事件的币安官方文档https://developers.binance.com/docs/zh-CN/derivatives/usds-margined-futures/user-data-streams/Event-Order-Update Official event documentation: https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Order-Update/* 该事件返回的JSON格式举例
{
"e":"ORDER_TRADE_UPDATE", // 事件类型 Event type
"E":1568879465651, // 事件时间 Event time
"T":1568879465650, // 撮合时间 Transaction time
"o":{
"s":"BTCUSDT", // 交易对 Trading symbol
"c":"TEST", // 客户端自定订单ID Client order ID
// 特殊的自定义订单ID: Special client order identifiers:
// "autoclose-"开头的字符串: 系统强平订单 autoclose- prefix: a liquidation order.
// "adl_autoclose": ADL自动减仓订单 adl_autoclose: an auto-deleveraging order.
// "settlement_autoclose-": 下架或交割的结算订单 settlement_autoclose-: a delisting or delivery settlement order.
"S":"SELL", // 订单方向 Order side
"o":"TRAILING_STOP_MARKET", // 订单类型 Order type
"f":"GTC", // 有效方式 Time in force
"q":"0.001", // 订单原始数量 Original order quantity
"p":"0", // 订单原始价格 Original order price
"ap":"0", // 订单平均价格 Average order fill price
"sp":"7103.04", // 条件订单触发价格,对追踪止损单无效 Conditional trigger price; not applicable to a trailing stop
"x":"NEW", // 本次事件的具体执行类型 Execution type for this event
"X":"NEW", // 订单的当前状态 Current order status
"i":8886774, // 订单ID Order ID
"l":"0", // 订单末次成交量 Last fill quantity
"z":"0", // 订单累计已成交量 Accumulated filled quantity
"L":"0", // 订单末次成交价格 Last fill price
"N": "USDT", // 手续费资产类型 Commission asset
"n": "0", // 手续费数量 Commission amount
"T":1568879465650, // 成交时间 Trade time
"t":0, // 成交ID Trade ID
"b":"0", // 买单净值 Bid notional
"a":"9.91", // 卖单净值 Ask notional
"m": false, // 该成交是作为挂单成交吗? Whether this fill is on the maker side
"R":false , // 是否是只减仓单 Whether this is a reduce-only order
"wt": "CONTRACT_PRICE", // 触发价类型 Trigger price type
"ot": "TRAILING_STOP_MARKET", // 原始订单类型 Original order type
"ps":"LONG" // 持仓方向 Position side
"cp":false, // 是否为触发平仓单; 仅在条件订单情况下会推送此字段 Whether this is a close-all conditional order; provided for conditional orders only
"AP":"7476.89", // 追踪止损激活价格, 仅在追踪止损单时会推送此字段 Trailing stop activation price; provided for trailing stops only
"cr":"5.0", // 追踪止损回调比例, 仅在追踪止损单时会推送此字段 Trailing stop callback rate; provided for trailing stops only
"pP": false, // 是否开启条件单触发保护 Whether conditional-order price protection is enabled
"si": 0, // 忽略 Ignore
"ss": 0, // 忽略 Ignore
"rp":"0", // 该交易实现盈亏 Realized profit or loss for this trade
"V":"EXPIRE_TAKER", // 自成交防止模式 Self-trade prevention mode
"pm":"OPPONENT", // 价格匹配模式 Price matching mode
"gtd":0, // TIF为GTD的订单自动取消时间 Automatic cancellation time for a GTD order
"er":"0" // 过期原因 Expiry reason
}
}
*///根据事件类型判断是订单交易更新事件 Identify an order trade update from the event type.if(e=="ORDER_TRADE_UPDATE")
{
//Event Time//键E的值是事件时间,该值是整数,反序列化成long变量 Field E: Event time. Deserialize as long.long eventTime=jEvent["E"].ToInt();
//convert API utc0 timestamp to local datetime//该时间是格林威治时间,转换成本地电脑时区的时间 Convert the UTC timestamp to local computer time.datetime eventDateTime=(datetime)(eventTime/1000)+timeZone*60*60;
printf("ORDER_TRADE_UPDATE|Event Time 事件时间 %s %s", (string)eventTime, (string)eventDateTime);
//Transaction Time//键T的值是交易时间,该值是整数,反序列化成long变量 Field T: Transaction time. Deserialize as long.long transactionTime=jEvent["T"].ToInt();
datetime transactionDateTime=(datetime)(transactionTime/1000)+timeZone*60*60;
printf(" |Transaction Time 交易时间 %s %s", (string)transactionTime, (string)transactionDateTime);
//deserialize binance response JSON//键o是一个嵌套的JSON包含订单信息 The o field is a nested JSON object containing order information.CJAVal jEventO=jEvent["o"];
// Symbol//键s的值是交易对 Field s: Trading symbol.string eventSymbol=jEventO["s"].ToStr();
printf(" |Symbol 交易对 %s", eventSymbol);
// Client Order Id//键c的值是客户端自定订单ID Field c: Client order ID.string clientOrderId=jEventO["c"].ToStr();
printf(" |Client Order Id 客户端自定订单ID %s", clientOrderId);
//Side//键S的值是订单方向 Field S: Order side.string side=jEventO["S"].ToStr();
printf(" |Side 订单方向 %s", side);
//Order Type//键o的值是订单类型 Field o: Order type.string orderType=jEventO["o"].ToStr();
printf(" |Order Type 订单类型 %s", orderType);
// Time in Force//键f的值是有效方式 Field f: Time in force.string timeInForce=jEventO["f"].ToStr();
printf(" |Time in Force 有效方式 %s", timeInForce);
//Original Quantity//键q的值是订单原始数量 Field q: Original order quantity.string originalQuantity=jEventO["q"].ToStr();
printf(" |Original Quantity 订单原始数量 %s", originalQuantity);
//Original Price//反序列化事件JSON得到订单原始价格 Deserialize the original order price from the event JSON.string originalPrice=jEventO["p"].ToStr();
printf(" |Original Price 订单原始价格 %s", originalPrice);
//Average Price//键ap的值是订单平均价格 Field ap: Average order fill price.string averagePrice=jEventO["ap"].ToStr();
printf(" |Average Price 订单平均价格 %s", averagePrice);
//Stop Price. Please ignore with TRAILING_STOP_MARKET order//键sp的值是条件订单触发价格,对追踪止损单无效 Field sp: Conditional trigger price; not applicable to a trailing stop.string stopPrice=jEventO["sp"].ToStr();
printf(" |Stop Price 条件订单触发价格 %s", averagePrice);
//Execution Type//键x的值是本次事件的具体执行类型 Field x: Execution type for this event.string executionType=jEventO["x"].ToStr();
printf(" |Execution Type 本次事件的具体执行类型 %s", executionType);
//Order Status//键X的值是订单的当前状态 Field X: Current order status.string orderStatus=jEventO["X"].ToStr();
printf(" |Order Status 订单的当前状态 %s", orderStatus);
//Order Id//键i的值是订单ID,该值是整数,反序列化成long变量 Field i: Order ID. Deserialize as long.long orderId=jEventO["i"].ToInt();
printf(" |Order Id 订单ID %s", (string)orderId);
//Order Last Filled Quantity//键l的值是订单末次成交量 Field l: Last fill quantity.string orderLastFilledQuantity=jEventO["l"].ToStr();
printf(" |Order Last Filled Quantity 订单末次成交量 %s", orderLastFilledQuantity);
//Order Filled Accumulated Quantity//键z的值是订单累计已成交量 Field z: Accumulated filled quantity.string orderFilledAccumulatedQuantity=jEventO["z"].ToStr();
printf(" |Order Filled Accumulated Quantity 订单累计已成交量 %s", orderFilledAccumulatedQuantity);
//Last Filled Price//键L的值是订单末次成交价格 Field L: Last fill price.string lastFilledPrice=jEventO["L"].ToStr();
printf(" |Last Filled Price 订单末次成交价格 %s", lastFilledPrice);
//Commission Asset//键N的值是手续费资产类型 Field N: Commission asset.string commissionAsset=jEventO["N"].ToStr();
printf(" |Commission Asset 手续费资产类型 %s", commissionAsset);
//键n的值是手续费数量 Field n: Commission amount.string commission=jEventO["n"].ToStr(); //Commission 手续费数量 Commission amount.printf(" |Commission 手续费数量 %s", commission);
//Order Trade Time//键T的值是成交时间,该值是整数(时间戳),反序列化成long变量 Field T: Trade time. Deserialize as long.long orderTradeTime=jEventO["T"].ToInt();
//convert API utc0 timestamp to local datetime//该时间是格林威治时间,转换成本地电脑时区的时间 Convert the UTC timestamp to local computer time.datetime orderTradeDateTime=(datetime)((long)orderTradeTime/1000)+timeZone*60*60;
printf(" |Order Trade Time 成交时间 %s %s", (string)orderTradeTime,(string)orderTradeDateTime);
//Trade Id//键t的值是成交ID,该值是整数,反序列化成long变量 Field t: Trade ID. Deserialize as long.long tradeId=jEventO["t"].ToInt();
printf(" |Trade Id 成交ID %s", (string)tradeId);
//Bids Notional//反序列化事件JSON得到买单净值 Deserialize the bid notional from the event JSON.string bidsNotional=jEventO["b"].ToStr();
printf(" |Bids Notional 买单净值 %s", bidsNotional);
//Ask Notional//反序列化事件JSON得到卖单净值 Deserialize the ask notional from the event JSON.string askNotional=jEventO["a"].ToStr();
printf(" |Ask Notional 卖单净值 %s", askNotional);
//Is this trade the maker side?//键m的值是该成交是作为挂单成交吗,该值是布尔型,反序列化成bool变量 The m field indicates whether the fill is on the maker side. Deserialize this Boolean value as bool.bool isMaker=jEventO["m"].ToBool();
printf(" |Is this trade the maker side? 该成交是作为挂单成交吗?%s", (string)isMaker);
//Is this reduce only//键R的值是是否是只减仓单,该值是布尔型,反序列化成bool变量 Field R: Whether this is a reduce-only order. Deserialize as bool.bool isReduce=jEventO["R"].ToBool();
printf(" |Is this reduce only 是否是只减仓单 %s", (string)isReduce);
//Stop Price Working Type//键wt的值是触发价类型 Field wt: Trigger price type.string stopPriceWorkingType=jEventO["wt"].ToStr();
printf(" |Stop Price Working Type 触发价类型 %s", stopPriceWorkingType);
// Original Order Type//键ot的值原始订单类型 Field ot: Original order type.string originalOrderType=jEventO["ot"].ToStr();
printf(" |Original Order Type 原始订单类型 %s", originalOrderType);
// Position Side//键ps的值是持仓方向 Field ps: Position side.string positionSide=jEventO["ps"].ToStr();
printf(" |Position Side 持仓方向 %s", positionSide);
//If Close-All, pushed with conditional order//键cp的值是是否为触发平仓单; 仅在条件订单情况下会推送此字段 Field cp: Whether this is a close-all conditional order; provided for conditional orders only.bool isCloseAll=jEventO["cp"].ToBool();
printf(" |If Close-All 是否为触发平仓单 %s", (string)isCloseAll);
//Activation Price, only puhed with TRAILING_STOP_MARKET order//键AP的值是追踪止损激活价格, 仅在追踪止损单时会推送此字段 Field AP: Trailing stop activation price; provided for trailing stops only.string activationPrice=jEventO["AP"].ToStr();
printf(" |Activation Price 追踪止损激活价格 %s", activationPrice);
// Callback Rate, only puhed with TRAILING_STOP_MARKET order//键cr的值是追踪止损回调比例, 仅在追踪止损单时会推送此字段 Field cr: Trailing stop callback rate; provided for trailing stops only.string callBackRate=jEventO["cr"].ToStr();
printf(" |Activation Price 追踪止损激活价格 %s", callBackRate);
//If price protection is turned on//键pP的值是是否开启条件单触发保护,该值是布尔值,反序列化成bool变量 Field pP: Whether conditional-order price protection is enabled. Deserialize as bool.bool isPriceProtection=jEventO["pP"].ToBool();
printf(" |If price protection is turned on 是否开启条件单触发保护 %s", (string)isPriceProtection);
//Realized Profit of the trade//键rp的值是该交易实现盈亏 Field rp: Realized profit or loss for this trade.string realizedProfit =jEventO["rp"].ToStr();
printf(" |Realized Profit of the trade 该交易实现盈亏 %s", realizedProfit);
// STP mode//键V的值是自成交防止模式 Field V: Self-trade prevention mode.string stpMode =jEventO["V"].ToStr();
printf(" |If price protection is turned on 是否开启条件单触发保护 %s", stpMode);
//Price match mode//键pm的值是价格匹配模式 Field pm: Price matching mode.string PriceMatchMode =jEventO["pm"].ToStr();
printf(" |Price match mode 价格匹配模式 %s", PriceMatchMode);
//TIF GTD order auto cancel time//键gtd的值是TIF为GTD的订单自动取消时间,该值是整数(时间戳),反序列化成long变量 Field gtd: Automatic cancellation time for a GTD order. Deserialize as long.long gtd =jEventO["gtd"].ToInt();
printf(" |TIF GTD order auto cancel time TIF为GTD的订单自动取消时间 %s", (string)gtd);
}
//Event: Balance and Position Update//https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Balance-and-Position-Update//下单后币安还会推送Balance 和 Position 更新事件 After order submission, Binance may also push a balance and position update event.//该事件的币安官方文档 https://developers.binance.com/docs/zh-CN/derivatives/usds-margined-futures/user-data-streams/Event-Balance-and-Position-Update Official event documentation: https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Balance-and-Position-Update//该事件返回的JSON格式举例,是一个多层嵌套的JSON The example event JSON below contains nested objects and arrays./*
{
"e": "ACCOUNT_UPDATE", // 事件类型 Event type
"E": 1564745798939, // 事件时间 Event time
"T": 1564745798938 , // 撮合时间 Transaction time
"a": // 账户更新事件 Account update event
{
"m":"ORDER", // 事件推出原因 Event reason
"B":[ // 余额信息 Balance information
{
"a":"USDT", // 资产名称 Asset name
"wb":"122624.12345678", // 钱包余额 Wallet balance
"cw":"100.12345678", // 除去逐仓仓位保证金的钱包余额 Cross wallet balance excluding isolated position margin
"bc":"50.12345678" // 除去盈亏与交易手续费以外的钱包余额改变量 Wallet balance change excluding profit, loss and trading fees
},
{
"a":"BUSD",
"wb":"1.00000000",
"cw":"0.00000000",
"bc":"-49.12345678"
}
],
"P":[
{
"s":"BTCUSDT", // 交易对 Trading symbol
"pa":"0", // 仓位 Position amount
"ep":"0.00000", // 入仓价格 Entry price
"bep":"0", // 盈亏平衡价 Break-even price
"cr":"200", // (费前)累计实现损益 Accumulated realized profit or loss before fees
"up":"0", // 持仓未实现盈亏 Unrealized position profit or loss
"mt":"isolated", // 保证金模式 Margin type
"iw":"0.00000000", // 若为逐仓,仓位保证金 Isolated position margin, when applicable
"ps":"BOTH" // 持仓方向 Position side
},
{
"s":"BTCUSDT",
"pa":"20",
"ep":"6563.66500",
"bep":"6563.6",
"cr":"0",
"up":"2850.21200",
"mt":"isolated",
"iw":"13200.70726908",
"ps":"LONG"
},
{
"s":"BTCUSDT",
"pa":"-10",
"ep":"6563.86000",
"bep":"6563.6",
"cr":"-45.04000000",
"up":"-1423.15600",
"mt":"isolated",
"iw":"6570.42511771",
"ps":"SHORT"
}
]
}
}
*///根据事件类型判断是余额和仓位更新事件 Identify a balance and position update from the event type.if(e=="ACCOUNT_UPDATE")
{
//Event Time//键E的值是事件时间, 该值是整数,反序列化成long变量 Field E: Event time. Deserialize as long.long eventTime=jEvent["E"].ToInt();
//convert API utc0 timestamp to local datetime//该时间是格林威治时间,转换成本地电脑时区的时间 Convert the UTC timestamp to local computer time.datetime eventDateTime=(datetime)(eventTime/1000)+timeZone*60*60;
printf("ACCOUNT_UPDATE|Event Time 事件时间 %s %s", (string)eventTime, (string)eventDateTime);
//Transaction Time//键T的值是撮合时间,该值是整数(时间戳),反序列化成long变量 Field T: Transaction time. Deserialize as long.long transactionTime=jEvent["T"].ToInt();
//该时间是格林威治时间,转换成本地电脑时区的时间 Convert the UTC timestamp to local computer time.datetime transactionDateTime=(datetime)(transactionTime/1000)+timeZone*60*60;
printf(" |Transaction Time 撮合时间 %s %s", (string)transactionTime, (string)transactionDateTime);
// Update Data//键a的值是账户更新事件 Field a: Account update event.CJAVal jEventO=jEvent["a"];
// Event reason type// 键m的值是事件推出原因 Field m: Event reason.string reasonType=jEventO["m"].ToStr();
printf(" |Event reason type 事件推出原因 %s", reasonType);
// Balances//键B的值是余额信息 Field B: Balance information.CJAVal jBalances=jEventO["B"];
if(jBalances.Size()>0)
{
for(int i=0;i<jBalances.Size();i++)
{
CJAVal jBalance=jBalances[i];
//Asset//键a的值是资产名称 Field a: Asset name.string asset=jBalance["a"].ToStr();
printf(" |Asset 资产名称 %s", asset);
// Wallet Balance//键wb的值是钱包余额 Field wb: Wallet balance.string walletBalance=jBalance["wb"].ToStr();
printf(" |Wallet Balance 钱包余额 %s", walletBalance);
// Cross Wallet Balance//键cw的值是除去逐仓仓位保证金的钱包余额 Field cw: Cross wallet balance excluding isolated position margin.string crossWalletBalance=jBalance["cw"].ToStr();
printf(" |Cross Wallet Balance 除去逐仓仓位保证金的钱包余额 %s", crossWalletBalance);
// Balance Change except PnL and Commission//键bc的值是除去盈亏与交易手续费以外的钱包余额改变量 Field bc: Wallet balance change excluding profit, loss and trading fees.string balanceChange=jBalance["bc"].ToStr();
printf(" |Wallet Balance 钱包余额 %s", walletBalance);
}
}
// Position// 键P的值是仓位 Field P: Position amount.CJAVal jPositions=jEventO["P"];
if(jPositions.Size()>0)
{
for(int i=0;i<jPositions.Size();i++)
{
CJAVal jPosition=jPositions[i];
// Symbol// 键s的值是交易对 Field s: Trading symbol.string symbol=jPosition["s"].ToStr();
printf(" |Symbol 交易对 %s", symbol);
// Position Amount//键pa的值是仓位 Field pa: Position amount.string positionAmount=jPosition["pa"].ToStr();
printf(" |Position Amount 仓位 %s", positionAmount);
// Entry Price//键ep的值是入仓价格 Field ep: Entry price.string entryPrice=jPosition["ep"].ToStr();
printf(" |Entry Price 入仓价格 %s", entryPrice);
// Balance Change except PnL and Commission//键bep的值是盈亏平衡价 Field bep: Break-even price.string balanceChange=jPosition["bep"].ToStr();
printf(" |Balance Change except PnL and Commission 盈亏平衡价 %s", balanceChange);
//(Pre-fee) Accumulated Realized//键cr的值是(费前)累计实现损益 Field cr: Accumulated realized profit or loss before fees.string accumulatedRealized=jPosition["cr"].ToStr();
printf(" |(Pre-fee) Accumulated Realized (费前)累计实现损益 %s", accumulatedRealized);
// Unrealized PnL//键up的值是持仓未实现盈亏 Field up: Unrealized position profit or loss.string unrealizedPnL=jPosition["up"].ToStr();
printf(" |Unrealized PnL 持仓未实现盈亏 %s", unrealizedPnL);
// Margin Type//键mt的值是保证金模式 Field mt: Margin type.string marginType=jPosition["mt"].ToStr();
printf(" |Margin Type 保证金模式 %s", marginType);
//Isolated Wallet (if isolated position)//键iw的值是若为逐仓,仓位保证金 Field iw: Isolated position margin, when applicable.string isolatedWallet=jPosition["iw"].ToStr();
printf(" |Isolated Wallet (if isolated position) 若为逐仓,仓位保证金 %s", isolatedWallet);
// Position Side//键ps的值是持仓方向 Field ps: Position side.string positionSide=jPosition["ps"].ToStr();
printf(" |Position Side 持仓方向 %s", positionSide);
}
}
}
}
}
//+------------------------------------------------------------------+//+------------------------------------------------------------------+//| Expert deinitialization function |//+------------------------------------------------------------------+voidOnDeinit(constint reason)
{
//---//release curl handles//EA退出时释放curl handles Release curl handles when the EA exits.curlCleanUp(handles);
}
//+------------------------------------------------------------------+