How can MQL5 modify a Binance USDⓈ-M futures order price?
Submit the new price through the MT5 Binance ufModifyOrder interface. This EA first queries all current account open orders through ufQueryCurrentAllOpenOrders, then attempts to modify the first returned item. For side=="BUY", it reduces the original order price by 5%; otherwise it increases it by 5%. It retains origQty and normalizes the new price using the order symbol’s SYMBOL_DIGITS.
What do you need to run this EA?
Install and configure MT5 Binance with the relevant services and API credentials. See the installation guide and API key setup.
Use an account and trading permissions appropriate for these USDⓈ-M futures interfaces. Make mt5binance.mqh and JAson.mqh available to MQL5.
Have an open order that can be modified, with its symbol’s SYMBOL_DIGITS available in MT5. The code reads the order symbol rather than filtering by the chart symbol.
The order, new price and quantity must satisfy current exchange modification rules. This example neither creates a new order nor cancels and replaces an order.
How does the EA query and modify an order?
Initialize:OnInit() initializes API credentials, global curl state and one request handle, and allocates a response buffer of 10,000 character elements.
Query account open orders: On the first tick, call ufQueryCurrentAllOpenOrders(handles, "", recvWindow, resultChar), print the UTF-8 response and parse it with CJAVal.
Read the first item: In the source’s code==0 branch, read the first item’s symbol, order ID, client order ID, original price, original quantity, side and price matching mode.
Calculate the new price: Use price × 0.95 for a BUY and price × 1.05 otherwise. Normalize with NormalizeDouble using the order symbol’s decimal precision. The reference is the original order price, not the current market price.
Submit the modification: Call ufModifyOrder(handles, orderId, clientOrderId, symbol, side, origQty, modifyPrice, priceMatch, recvWindow, resultChar), convert and print the synchronous response, then leave the loop.
Mark execution: Set isRun=true after the query or modification sequence. Later ticks do not repeat it or retry based on the response. Reloading the EA may run the sequence again.
Handle events and clean up:OnChartEvent() filters for id==3333, extracts JSON and handles ORDER_TRADE_UPDATE. OnDeinit() releases curl handles.
Which parameters does this example use?
Parameter
Value or source
Purpose
Query symbol
""
Query all account open orders, without restricting the chart symbol.
Target order
First returned array item
No additional filtering by EA identifier, order type or status.
orderId / clientOrderId
Read from the original order
Passed to the modification interface to identify the order.
side / quantity
side / origQty
Retain the side and submitted quantity from the original order fields.
modifyPrice
BUY: price × 0.95 Otherwise: price × 1.05
Adjust the original order price by 5%.
Price precision
SYMBOL_DIGITS
Normalize to the order symbol’s decimal precision.
priceMatch
Read from the original order
Pass through the original price matching field.
recvWindow
3000
A request timing window of 3,000 milliseconds.
Execution count
At most one sequence per attachment
The flag is set even if there are no orders or a request fails.
//+------------------------------------------------------------------+//| 币安U本位期货修改订单binanceUSDMarginFutureModifyOrder.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头文件// 先查询挂单,再按买卖方向调整第一笔可用订单的委托价格。// Query open orders, then adjust the first eligible order price according to its side.// 引入币安 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接口使用的curl handles// 保存币安请求使用的 curl 句柄,供接口调用复用。// Store curl handles for reuse by Binance API calls.int handles[];
//MQL币安API response data MQL币安API返回数据// 同步响应缓冲区,API 调用将返回数据写入此字符数组。// Synchronous response buffer populated by API calls.staticchar resultChar[];
// 执行标记,只有在后续代码检查并更新此变量时才限制重复运行。// Execution flag. It limits repeated execution only where later code checks and updates it.bool isRun=false;
//Current Position Mode持仓模式bool isHedgeMode=false;
//+------------------------------------------------------------------+//| Expert initialization function |//+------------------------------------------------------------------+// EA 加载时由 MT5 调用,执行本例所需的初始化。// MT5 calls this handler when the EA is loaded to perform initialization required by this example.intOnInit()
{
//---//initialize binance API key and secret key you set初始化你设置的币安API密钥// 初始化配置中已设置的币安 API 凭据,供后续签名请求使用。// Initialize the configured Binance API credentials for subsequent signed requests.initBinanceAPIKey();
//初始化币安MQL接口使用的curl handles// 初始化 curl 全局状态,后续分配句柄数组并创建请求句柄。// Initialize global curl state before allocating the handle array and creating request handles.curlGlobalInit();
ArrayResize(handles, 1);
curlInit(handles);
//set up length of resultChar 设置resultChar的字符长度// 为返回 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 handles release curl handles// 释放本例创建的 curl 请求句柄。// Release the curl request handles created by this example.curlCleanUp(handles);
}
//+------------------------------------------------------------------+//| Expert tick function |//+------------------------------------------------------------------+// 收到行情时检查执行标记,按函数体中的标记控制演示是否重复运行。// On each tick, check the execution flag and use the flag logic in the function body to control repeated execution.voidOnTick()
{
//---if(isRun==false)
{
//Get all open orders on a symbol 查看当前全部挂单// 查询指定交易对的全部未成交订单;交易对为空时按接口规则查询账户挂单。// Query all open orders for the specified symbol. An empty symbol requests account open orders according to the API rules.// 此处使用 handles 发起请求,并通过最后一个引用参数 resultChar 接收同步响应。// Use handles for the request and receive the synchronous response through the final reference parameter resultChar.ufQueryCurrentAllOpenOrders(handles, "", 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);
printf(result);
CJAVal jOrders;
// 解析 JSON 供后续按字段名读取;本例此处未检查解析函数的返回值。// Deserialize JSON for subsequent field access. This example does not check the parser return value here.
jOrders.Deserialize(result);
// 读取 code 错误码字段;成功响应的字段结构由各接口决定,后续按本例条件处理。// Read the code error field. Successful response structures depend on the endpoint and are handled by the conditions below.long code=jOrders["code"].ToInt();
if(code==0)
{
// 逐项遍历返回数组,读取每条记录。// Iterate through the returned array and read each record.for(int i=0;i<jOrders.Size();i++)
{
// 读取 symbol 字段,表示交易对,使用 ToStr 转换。// Read symbol for trading symbol using ToStr.string symbol=jOrders[i]["symbol"].ToStr();
if(symbol!="")
{
// 读取 orderId 字段,表示交易所订单 ID,使用 ToStr 转换。// Read orderId for exchange order ID using ToStr.string orderId=jOrders[i]["orderId"].ToStr();//order id 系统订单号printf("order id 系统订单号 %s", orderId);
// 读取 status 字段,表示订单状态,使用 ToStr 转换。// Read status for order status using ToStr.string status=jOrders[i]["status"].ToStr();//order status 订单状态printf("order status 订单状态 %s", status);
// 读取 clientOrderId 字段,表示用户自定义订单 ID,使用 ToStr 转换。// Read clientOrderId for client order ID using ToStr.string clientOrderId=jOrders[i]["clientOrderId"].ToStr();//client order id 用户自定义的订单号printf("client order id 用户自定义的订单号 %s", clientOrderId);
// 读取 price 字段,表示价格,使用 ToDbl 转换。// Read price for price using ToDbl.double price=jOrders[i]["price"].ToDbl();//price 委托价格printf("price 委托价格 %s", (string)price);
// 读取 avgPrice 字段,表示平均成交价,使用 ToStr 转换。// Read avgPrice for average fill price using ToStr.string avgPrice=jOrders[i]["avgPrice"].ToStr();//average price 平均成交价printf("average price 平均成交价 %s", (string)avgPrice);
// 读取 origQty 字段,表示原始委托数量,使用 ToDbl 转换。// Read origQty for original order quantity using ToDbl.double origQty=jOrders[i]["origQty"].ToDbl();//original quantity 原始委托数量printf("original quantity 原始委托数量 %s", (string)origQty);
// 读取 executedQty 字段,表示累计成交数量,使用 ToStr 转换。// Read executedQty for executed quantity using ToStr.string executedQty=jOrders[i]["executedQty"].ToStr();//executed quantity 成交量printf("executed quantity 成交量 %s", executedQty);
// 读取 cumQuote 字段,表示累计成交金额,使用 ToStr 转换。// Read cumQuote for cumulative quote amount using ToStr.string cumQuote=jOrders[i]["cumQuote"].ToStr();// 成交金额printf("cumQuote 成交金额 %s", cumQuote);
// 读取 timeInForce 字段,表示订单有效方式,使用 ToStr 转换。// Read timeInForce for time in force using ToStr.string timeInForce=jOrders[i]["timeInForce"].ToStr();//time In Force 有效方法printf("time In Force 有效方法 %s", timeInForce);
// 读取 type 字段,表示订单类型,使用 ToStr 转换。// Read type for order type using ToStr.string type=jOrders[i]["type"].ToStr();//order type 订单类型printf("order type 订单类型 %s", type);
// 读取 reduceOnly 字段,表示是否仅减仓,使用 ToStr 转换。// Read reduceOnly for whether the order is reduce-only using ToStr.string reduceOnly=jOrders[i]["reduceOnly"].ToStr();//is reduce Only 是否仅减仓printf("is reduce Only 是否仅减仓 %s", reduceOnly);
// 读取 closePosition 字段,表示是否为条件全平仓订单,使用 ToStr 转换。// Read closePosition for whether this is a conditional close-all order using ToStr.string closePosition=jOrders[i]["closePosition"].ToStr();// 是否条件全平仓printf("closePosition 是否条件全平仓 %s", closePosition);
// 读取 side 字段,表示买卖方向,使用 ToStr 转换。// Read side for order side using ToStr.string side=jOrders[i]["side"].ToStr();//order side 买卖方向printf("order side 买卖方向 %s", side);
// 读取 positionSide 字段,表示持仓方向,使用 ToStr 转换。// Read positionSide for position side using ToStr.string positionSide=jOrders[i]["positionSide"].ToStr();//position side 持仓方向printf("position side 持仓方向 %s", positionSide);
// 读取 stopPrice 字段,表示触发价格,使用 ToStr 转换。// Read stopPrice for trigger price using ToStr.string stopPrice=jOrders[i]["stopPrice"].ToStr();//Stop Price. Please ignore with TRAILING_STOP_MARKET order 条件订单触发价格,对追踪止损单无效printf("Stop Price 条件订单触发价格 %s", stopPrice);
// 读取 workingType 字段,表示触发价格类型,使用 ToStr 转换。// Read workingType for trigger price type using ToStr.string workingType=jOrders[i]["workingType"].ToStr();// Stop Price Working Type 触发价类型printf("Stop Price Working Type 触发价类型 %s", workingType);
// 读取 priceProtect 字段,表示是否开启条件单价格保护,使用 ToStr 转换。// Read priceProtect for whether conditional-order price protection is enabled using ToStr.string priceProtect=jOrders[i]["priceProtect"].ToStr();// If price protection is turned on 是否开启条件单触发保护printf("priceProtect 是否开启条件单触发保护 %s", priceProtect);
// 读取 origType 字段,表示原始订单类型,使用 ToStr 转换。// Read origType for original order type using ToStr.string origType=jOrders[i]["origType"].ToStr();// Original Order Type 原始订单类型printf("Original Order Type 原始订单类型 %s", origType);
// 读取 priceMatch 字段,表示价格匹配模式,使用 ToStr 转换。// Read priceMatch for price matching mode using ToStr.string priceMatch=jOrders[i]["priceMatch"].ToStr(); //Price match mode 价格匹配模式printf("Price match mode 价格匹配模式 %s", priceMatch);
// 读取 selfTradePreventionMode 字段,表示自成交防止模式,使用 ToStr 转换。// Read selfTradePreventionMode for self-trade prevention mode using ToStr.string selfTradePreventionMode=jOrders[i]["selfTradePreventionMode"].ToStr();//防止自成交模式 self trading preventation modeprintf("防止自成交模式 self trading preventation mode %s", selfTradePreventionMode);
// 读取 goodTillDate 字段,表示GTD 订单自动取消时间,使用 ToStr 转换。// Read goodTillDate for automatic cancellation time for a GTD order using ToStr.string goodTillDate=jOrders[i]["goodTillDate"].ToStr(); //order pre-set auot cancel time for TIF GTD orderprintf("order pre-set auot cancel time for TIF GTD order %s", selfTradePreventionMode);
// 读取 time 字段,表示时间戳,使用 ToStr 转换。// Read time for timestamp using ToStr.string time=jOrders[i]["time"].ToStr();//create order time 创建订单时间printf("create order time 创建订单时间 %s", time);
// 读取 updateTime 字段,表示更新时间戳,使用 ToStr 转换。// Read updateTime for update timestamp using ToStr.string updateTime=jOrders[i]["updateTime"].ToStr();//order update time 订单更新时间printf("order update time 订单更新时间 %s", updateTime);
//price precision 价格精度// 按合约属性确定显示或计算使用的小数位数。// Determine decimal precision for display or calculation from symbol properties.int pricePrecision=(int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
//modify price only for demo 演示只修改价格double modifyPrice=0;
if(side=="BUY")
{
//modify lower price 修改更低的价格
modifyPrice=NormalizeDouble(price-price*0.05, pricePrecision);
}
else
{
//modify higher price 修改更高的价格
modifyPrice=NormalizeDouble(price+price*0.05, pricePrecision);
}
// 通过订单 ID 或客户订单 ID 定位挂单,提交方向、数量、新价格和价格匹配方式;同步结果写入 resultChar。// Identify an open order by order ID or client order ID and submit its side, quantity, new price, and price matching mode. resultChar receives the synchronous response.// 此处使用 handles 发起请求,并通过最后一个引用参数 resultChar 接收同步响应。// Use handles for the request and receive the synchronous response through the final reference parameter resultChar.ufModifyOrder(handles, orderId, clientOrderId, symbol, side, origQty, modifyPrice, priceMatch, 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);
printf(result);
}
//modify first order only for demo 演示只修改第一个挂单break;
}
}
else
{
printf(result);
}
// 标记本次演示已执行;此处未按请求成功与否决定是否重试。// 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得到币安推送事件// OnChartEvent 是 MT5 图表及自定义事件入口,本接口通过它接收币安异步推送。// OnChartEvent handles MT5 chart and custom events. This API uses it to receive asynchronous Binance push events.// id 为事件类型,币安事件使用 3333;lparam、dparam 为附加数值参数,本例未读取。// id identifies the event type, with 3333 used for Binance events. lparam and dparam are additional numeric parameters that this example does not read.// sparam 携带事件字符串,经 processChartEventMsg 处理后再解析 JSON;同步 API 响应与推送事件分别处理。// sparam carries the event string. Process it with processChartEventMsg before parsing JSON. Handle synchronous API responses separately from push events.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 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: 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);
}
}
}
//+------------------------------------------------------------------+