← EA 示例目录
1013 / MQL5 / USDⓈ-M FUTURES

如何用 MQL5 查询币安当前的一笔挂单?

使用 ufQueryCurrentOpenOrder,指定品种和客户订单号。本例查询当前图表品种下客户端标识为 myEAOrder123 的挂单,读取状态、委托价格、原始数量、已成交数量和方向等字段。

运行这个示例需要什么?

  • 在 MT5 中安装并配置连接软件与 API 密钥,使 mt5binance.mqh、JAson.mqh 以及本例所需的账户权限可用。
  • 将 myEAOrder123 替换为真实且当前仍可查询的挂单标识。此接口面向当前挂单;若需查询包含历史状态的单笔订单,可参考 1010。

源码按什么流程执行?

  1. 每次 tick 调用 ufQueryCurrentOpenOrder,orderId 传 0,origClientOrderId 传 myEAOrder123。
  2. 将返回字符数组转为 UTF-8 字符串,使用 CJAVal 解析。
  3. 从响应对象读取订单字段。源码虽然声明 isRun,但未用它限制 OnTick 查询。

每次 OnTick 执行请求,没有生效的单次执行标记;请求频率随图表行情到达而变化。

示例参数与执行方式

参数源码值或行为
主要接口ufQueryCurrentOpenOrder
品种Symbol()
交易所订单号0
客户订单号myEAOrder123
主要字段symbol / status / price / origQty / executedQty
请求时间窗口recvWindow = 3000 ms
触发方式每次 OnTick 执行请求,没有生效的单次执行标记;请求频率随图表行情到达而变化。

相关教程与接口示例

完整 MQL5 源码

//+------------------------------------------------------------------+
//|币安U本位期货查看当前单个挂单binanceUSDMarginFutureQueryOneOpenOrder|
//|                                  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接口的头文件
// 查询指定客户订单号对应的当前挂单。
// Query the current open order identified by a client order ID.
// 引入币安 MQL 接口声明,调用方式以本文件现有接口签名为准。
// Include the Binance MQL API declarations and use the API signatures present in this file.
#include <mt5binance.mqh>

//import mql5.com open source json library to deserialize binance reponse json https://www.mql5.com/en/code/13663
//引入mql5.com上的开源json library反序列化币安返回的json数据  https://www.mql5.com/zh/code/13663
// 使用 JAson.mqh 的 CJAVal 解析同步响应和异步事件 JSON。
// Use CJAVal from JAson.mqh to parse synchronous responses and asynchronous event JSON.
#include <JAson.mqh>


// 执行标记,只有在后续代码检查并更新此变量时才限制重复运行。
// Execution flag. It limits repeated execution only where later code checks and updates it.
bool isRun=false;

//setup Timing security https://developers.binance.com/docs/derivatives/usds-margined-futures/general-info#timing-security
//设置时间同步安全 https://developers.binance.com/docs/zh-CN/derivatives/usds-margined-futures/general-info#%E6%97%B6%E9%97%B4%E5%90%8C%E6%AD%A5%E5%AE%89%E5%85%A8
// 请求时间窗口为 3000 毫秒,币安按请求时间戳与服务器时间检查请求时效。
// The request timing window is 3000 milliseconds. Binance validates request timing against its server time.
long recvWindow=3000;

//MQL币安API response data  MQL币安API返回数据
// 同步响应缓冲区,API 调用将返回数据写入此字符数组。
// Synchronous response buffer populated by API calls.
static char resultChar[];

// 保存币安请求使用的 curl 句柄,供接口调用复用。
// Store curl handles for reuse by Binance API calls.
int handles[];

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
// EA 加载时由 MT5 调用,执行本例所需的初始化。
// MT5 calls this handler when the EA is loaded to perform initialization required by this example.
int OnInit()
  {
   // 初始化配置中已设置的币安 API 凭据,供后续签名请求使用。
   // Initialize the configured Binance API credentials for subsequent signed requests.
   initBinanceAPIKey();
   // 初始化 curl 全局状态,后续分配句柄数组并创建请求句柄。
   // Initialize global curl state before allocating the handle array and creating request handles.
   curlGlobalInit();
   ArrayResize(handles, 1);
   curlInit(handles);

   // 为返回 JSON 分配缓冲区,响应长度需要在分配容量内。
   // Allocate a response buffer large enough to hold the returned JSON.
   ArrayResize(resultChar, 10000);
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
// EA 卸载或重新初始化前调用,reason 为卸载原因;清理操作以函数体为准。
// Called before EA removal or reinitialization. reason identifies the cause, and the function body defines the cleanup performed.
void OnDeinit(const int reason)
  {
//---
   // 释放本例创建的 curl 请求句柄。
   // Release the curl request handles created by this example.
   curlCleanUp(handles);

   printf("curlCleanUp");
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
// 每次收到行情都会执行函数体中的请求流程,本函数未使用一次性运行判断。
// Each tick executes the request sequence in this handler, which has no one-shot execution guard.
void OnTick()
  {

//Query current open order 查询当前某个挂单
   // 按当前图表合约和示例客户订单号 myEAOrder123 查询一笔未成交订单。
   // Query one open order using the current chart symbol and example client order ID myEAOrder123.
   // 此处使用 handles 发起请求,并通过最后一个引用参数 resultChar 接收同步响应。
   // Use handles for the request and receive the synchronous response through the final reference parameter resultChar.
   ufQueryCurrentOpenOrder(handles, Symbol(), 0, "myEAOrder123", 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 jOrder;
   // 解析 JSON 供后续按字段名读取;本例此处未检查解析函数的返回值。
   // Deserialize JSON for subsequent field access. This example does not check the parser return value here.
   jOrder.Deserialize(result);

   // 读取 symbol 字段,表示交易对,使用 ToStr 转换。
   // Read symbol for trading symbol using ToStr.
   string symbol=jOrder["symbol"].ToStr();// symbol 合约名称
   // 读取 orderId 字段,表示交易所订单 ID,使用 ToStr 转换。
   // Read orderId for exchange order ID using ToStr.
   string orderId=jOrder["orderId"].ToStr();//order id 系统订单号
   // 读取 status 字段,表示订单状态,使用 ToStr 转换。
   // Read status for order status using ToStr.
   string status=jOrder["status"].ToStr();//order status 订单状态
   // 读取 clientOrderId 字段,表示用户自定义订单 ID,使用 ToStr 转换。
   // Read clientOrderId for client order ID using ToStr.
   string clientOrderId=jOrder["clientOrderId"].ToStr();//client order id 用户自定义的订单号
   // 读取 price 字段,表示价格,使用 ToStr 转换。
   // Read price for price using ToStr.
   string price=jOrder["price"].ToStr();//price 委托价格
   // 读取 avgPrice 字段,表示平均成交价,使用 ToStr 转换。
   // Read avgPrice for average fill price using ToStr.
   string avgPrice=jOrder["avgPrice"].ToStr();//average price 平均成交价
   // 读取 origQty 字段,表示原始委托数量,使用 ToStr 转换。
   // Read origQty for original order quantity using ToStr.
   string origQty=jOrder["origQty"].ToStr();//original quantity 原始委托数量
   // 读取 executedQty 字段,表示累计成交数量,使用 ToStr 转换。
   // Read executedQty for executed quantity using ToStr.
   string executedQty=jOrder["executedQty"].ToStr();//executed quantity 成交量
   // 读取 cumQuote 字段,表示累计成交金额,使用 ToStr 转换。
   // Read cumQuote for cumulative quote amount using ToStr.
   string cumQuote=jOrder["cumQuote"].ToStr();// 成交金额
   // 读取 timeInForce 字段,表示订单有效方式,使用 ToStr 转换。
   // Read timeInForce for time in force using ToStr.
   string timeInForce=jOrder["timeInForce"].ToStr();//time In Force 有效方法
   // 读取 type 字段,表示订单类型,使用 ToStr 转换。
   // Read type for order type using ToStr.
   string type=jOrder["type"].ToStr();//order type 订单类型
   // 读取 reduceOnly 字段,表示是否仅减仓,使用 ToStr 转换。
   // Read reduceOnly for whether the order is reduce-only using ToStr.
   string reduceOnly=jOrder["reduceOnly"].ToStr();//is reduce Only 是否仅减仓
   // 读取 closePosition 字段,表示是否为条件全平仓订单,使用 ToStr 转换。
   // Read closePosition for whether this is a conditional close-all order using ToStr.
   string closePosition=jOrder["closePosition"].ToStr();// 是否条件全平仓
   // 读取 side 字段,表示买卖方向,使用 ToStr 转换。
   // Read side for order side using ToStr.
   string side=jOrder["side"].ToStr();//order side 买卖方向
   // 读取 positionSide 字段,表示持仓方向,使用 ToStr 转换。
   // Read positionSide for position side using ToStr.
   string positionSide=jOrder["positionSide"].ToStr();//position side 持仓方向
   // 读取 stopPrice 字段,表示触发价格,使用 ToStr 转换。
   // Read stopPrice for trigger price using ToStr.
   string stopPrice=jOrder["stopPrice"].ToStr();//Stop Price. Please ignore with TRAILING_STOP_MARKET order 条件订单触发价格,对追踪止损单无效
   // 读取 workingType 字段,表示触发价格类型,使用 ToStr 转换。
   // Read workingType for trigger price type using ToStr.
   string workingType=jOrder["workingType"].ToStr();//  Stop Price Working Type 触发价类型
   // 读取 priceProtect 字段,表示是否开启条件单价格保护,使用 ToStr 转换。
   // Read priceProtect for whether conditional-order price protection is enabled using ToStr.
   string priceProtect=jOrder["priceProtect"].ToStr();// If price protection is turned on 是否开启条件单触发保护
   // 读取 origType 字段,表示原始订单类型,使用 ToStr 转换。
   // Read origType for original order type using ToStr.
   string origType=jOrder["origType"].ToStr();// Original Order Type 原始订单类型
   // 读取 priceMatch 字段,表示价格匹配模式,使用 ToStr 转换。
   // Read priceMatch for price matching mode using ToStr.
   string priceMatch=jOrder["priceMatch"].ToStr(); ////Price match mode 价格匹配模式
   // 读取 selfTradePreventionMode 字段,表示自成交防止模式,使用 ToStr 转换。
   // Read selfTradePreventionMode for self-trade prevention mode using ToStr.
   string selfTradePreventionMode=jOrder["selfTradePreventionMode"].ToStr();//防止自成交模式 self trading preventation mode
   // 读取 goodTillDate 字段,表示GTD 订单自动取消时间,使用 ToStr 转换。
   // Read goodTillDate for automatic cancellation time for a GTD order using ToStr.
   string goodTillDate=jOrder["goodTillDate"].ToStr(); //order pre-set auot cancel time for TIF GTD order
   // 读取 time 字段,表示时间戳,使用 ToStr 转换。
   // Read time for timestamp using ToStr.
   string time=jOrder["time"].ToStr();//create order time 创建订单时间
   // 读取 updateTime 字段,表示更新时间戳,使用 ToStr 转换。
   // Read updateTime for update timestamp using ToStr.
   string updateTime=jOrder["updateTime"].ToStr();//order update time 订单更新时间

  }

//+------------------------------------------------------------------+
//get binance call back event via OnChartEvent
//OnChartEvent函数是MQL中的一个预定义事件处理函数,当用户在图表上进行操作(如点击、按键、移动鼠标等),MT5会自动调用此函数
// OnChartEvent is a predefined MQL event handler that MT5 calls for chart interactions such as clicks, keystrokes, and mouse movements.
//本软件可以通过 OnChartEvent函数得到币安异步推送事件
// This software receives asynchronous Binance events through OnChartEvent.
//这些币安事件代号都是 3333,根据该代号可以区分哪些是币安推送事件而非用户在图表上进行操作产生的事件
// Binance events use ID 3333 to distinguish them from events generated by user interactions with the chart.
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
   // 仅处理币安自定义事件,其他图表事件由此判断过滤。
   // Process only Binance custom events and filter out other chart events with this check.
   if(id==3333)  //all binance 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();
     }

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

//+------------------------------------------------------------------+