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

如何用 MQL5 按订单标识区分双向模式下的 EA 多空仓位?

本例收到 ACCOUNT_UPDATE 后查询当前品种订单,用 clientOrderId 包含 myEA 区分订单来源,再按 positionSide 与 side 分别累加或扣减多空数量,尝试计算多空平均开仓价。源码还在首次定时器事件准备 ETHUSDT 的 BUY LONG 市价单。

运行这个示例需要什么?

  • 在 MT5 中安装并配置连接软件与 API 密钥,使 mt5binance.mqh、JAson.mqh 以及本例所需的账户权限可用。
  • 使用双向持仓模式,并让相关订单携带一致的 myEA 标记。当前 OnInit 只设置 ETHUSDT 与 1 秒定时器,没有初始化 API 凭据、curl 句柄或响应缓冲区;需按实际库环境准备这些依赖。

源码按什么流程执行?

  1. OnInit 调用 EventSetTimer(1)。首次 OnTimer 执行 runDemo,准备 ETHUSDT、BUY、LONG、MARKET、quantity=0.006 的下单请求。
  2. ACCOUNT_UPDATE 到达后调用 ufQueryAllOrders,按客户订单号中包含 myEA 过滤。
  3. LONG 分支中 BUY 增加多仓、其他方向减少多仓;其他 positionSide 分支中 SELL 增加空仓、其他方向减少空仓,再计算并输出均价与数量。

演示下单由首次定时器事件触发;归属统计由 ACCOUNT_UPDATE 触发。

源码中的计算方式

这些累加变量没有在每次重新读取订单列表前整体清零,完整历史也未做分页处理;同名局部 cumQuote 会影响成交额累计。因此该示例是归属计算思路展示,不能直接认定输出已等于账户真实多空仓位。页面不修改原始计算代码。

示例参数与执行方式

参数源码值或行为
主要接口ufQueryAllOrders
品种ETHUSDT
EA 标识myEA
定时器间隔1 s
演示下单BUY / LONG / MARKET / 0.006
分组字段positionSide / side
事件ACCOUNT_UPDATE
请求时间窗口recvWindow = 3000 ms
触发方式演示下单由首次定时器事件触发;归属统计由 ACCOUNT_UPDATE 触发。

相关教程与接口示例

完整 MQL5 源码

//+------------------------------------------------------------------+
//|                      币安U本位期货下单binanceUSDMarginFutureNewOrder.mq5 |
//|                                  Copyright 2024, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+

//import MQL binance API 引入MQL币安API头文件
// 在双向持仓模式下,按本 EA 订单分别统计多头和空头持仓。
// Track this EA long and short positions separately in Hedge Mode using its order records.
// 引入币安 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反序列化币安API返回的json数据  import json library open source from mql5.com to deserialize binance API 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;
string symbol=Symbol();

//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;

double buyPositionQty=0;
double sellPositionQty=0;
double buyCumQuote=0;
double sellCumQuote=0;
double buyPositionOpenQty=0;
double sellPositionOpenQty=0;
string myEA="myEA";

// 保存币安请求使用的 curl 句柄,供接口调用复用。
// Store curl handles for reuse by Binance API calls.
int handles[];
// 同步响应缓冲区,API 调用将返回数据写入此字符数组。
// Synchronous response buffer populated by API calls.
static char resultChar[];

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
// EA 加载时由 MT5 调用,执行本例所需的初始化。
// MT5 calls this handler when the EA is loaded to perform initialization required by this example.
int OnInit()
  {
//---
//demo hard code ethusdt 演示目的所以硬编码ethusdt
   symbol="ETHUSDT";

//run demo in one second 设置一秒钟后运行例子
   // 设置每秒触发一次的定时器,实际是否重复执行由 OnTimer 中的标记决定。
   // Set a one-second timer. The flag in OnTimer determines whether the demonstration runs again.
   EventSetTimer(1);

   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)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
// 本例通过 OnTimer 启动演示,OnTick 保留为空。
// This example starts its demonstration through OnTimer and leaves OnTick empty.
void OnTick()
  {
//---

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

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
// 在双向持仓模式下,按本 EA 订单分别统计多头和空头持仓。
// Track this EA long and short positions separately in Hedge Mode using its order records.
void runDemo()
  {
   // 将 EA 标识和系统启动后的毫秒计数拼接为客户订单号,供后续归属筛选。
   // Combine the EA identifier with milliseconds since system startup to form the client order ID used for later attribution.
   string myEAOrderId=myEA+(string)GetTickCount();
   // 本例提交数量为 0.006 的市价买单,并以包含 myEA 的客户订单号标识归属;具体持仓方向由参数决定。
   // Submit a market BUY for 0.006 units using a client order ID containing myEA to identify ownership. The argument determines the position side.
   // 此处使用直接返回响应字符串的调用形式,具体参数以当前头文件声明为准。
   // This call form returns the response string directly. Refer to the current header declaration for the exact parameters.
   ufNewOrder(handles, symbol, "BUY", "LONG", "MARKET", "", "", 0.006, 0, myEAOrderId, "", "", "", 0, recvWindow, resultChar);

   //调用后币安同步返回下单结果,将其保存在最后一个引用参数resultChar中(币安异步返回的事件在OnChartEvent中处理)
   //将字符数组resultChar换成字符串result
   string result=CharArrayToString(resultChar, 0, -1, CP_UTF8);
   
   printf(result);

   CJAVal jOrder;

//deserialize binance response json  反序列化币安返回的json
   // 解析 JSON 供后续按字段名读取;本例此处未检查解析函数的返回值。
   // Deserialize JSON for subsequent field access. This example does not check the parser return value here.
   jOrder.Deserialize(result);

   // 读取 code 错误码字段;成功响应的字段结构由各接口决定,后续按本例条件处理。
   // Read the code error field. Successful response structures depend on the endpoint and are handled by the conditions below.
   string code=jOrder["code"].ToStr();
   printf("code %s", code);

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

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
// 定时器回调检查 isRun,首次执行 runDemo 后设置标记,后续回调跳过演示。
// The timer callback checks isRun, runs runDemo once, and sets the flag so later callbacks skip the demonstration.
void OnTimer()
  {
   if(isRun==false)
     {
      runDemo();
      // 标记本次演示已执行;此处未按请求成功与否决定是否重试。
      // Mark this demonstration as executed. This assignment does not select retries based on request success.
      isRun=true;
     }
  }

//get binance call back event via OnChartEvent
//OnChartEvent函数是MQL中的一个预定义事件处理函数,当用户在图表上进行操作(如点击、按键、移动鼠标等),MT5会自动调用此函数
// OnChartEvent is a predefined MQL event handler that MT5 calls for chart interactions such as clicks, keystrokes, and mouse movements.
//本软件可以通过 OnChartEvent函数得到币安异步推送事件
// This software receives asynchronous Binance events through OnChartEvent.
//这些币安事件代号都是 3333,根据该代号可以区分哪些是币安推送事件而非用户在图表上进行操作产生的事件
// Binance events use ID 3333 to distinguish them from events generated by user interactions with the chart.
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 callback event ID are 3333  币安事件推送代号都是3333
     {
      //process binance event string 处理币安推送事件字符串
      // 转换币安事件参数,取得待反序列化的 JSON 字符串。
      // Decode the Binance event parameter to obtain the JSON string for deserialization.
      string  event = processChartEventMsg(sparam);

      CJAVal jEvent;

      //deserialize binance response json  反序列化币安返回的json
      // 解析 JSON 供后续按字段名读取;本例此处未检查解析函数的返回值。
      // Deserialize JSON for subsequent field access. This example does not check the parser return value here.
      jEvent.Deserialize(event);

      //e is event type e是事件类型
      // 读取 e 字段,表示事件类型,使用 ToStr 转换。
      // Read e for event type using ToStr.
      string e=jEvent["e"].ToStr();

      //calculate EA position when position modified 当仓位发生变化的时候,根据所有订单计算本EA仓位
      //Event: Balance and Position Update https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Balance-and-Position-Update
      //Balance 和 Position 更新推送 https://developers.binance.com/docs/zh-CN/derivatives/usds-margined-futures/user-data-streams/Event-Balance-and-Position-Update
      // 账户余额或持仓更新后进入此分支,按本例逻辑读取数据或重新查询订单。
      // Enter this branch after balance or position updates to read data or query orders again as implemented by this example.
      if(e=="ACCOUNT_UPDATE")
        {
         //Get all account orders to calculate position of my EA
         //查询所有订单(包括历史订单) 计算本EA仓位
         // 查询订单列表,包含接口可返回的历史订单;返回范围受查询参数及接口保留范围限制。
         // Query an order list including available historical orders. Coverage is limited by request parameters and the API retention range.
         // 此处使用直接返回响应字符串的调用形式,具体参数以当前头文件声明为准。
         // This call form returns the response string directly. Refer to the current header declaration for the exact parameters.
         ufQueryAllOrders(handles, symbol, 0, 0, 0, 0, recvWindow,resultChar);
         CJAVal jOrders;
         // 解析 JSON 供后续按字段名读取;本例此处未检查解析函数的返回值。
         // Deserialize JSON for subsequent field access. This example does not check the parser return value here.
         jOrders.Deserialize(resultChar);

         // 读取 code 错误码字段;成功响应的字段结构由各接口决定,后续按本例条件处理。
         // Read the code error field. Successful response structures depend on the endpoint and are handled by the conditions below.
         string code=jOrders["code"].ToStr();
         printf(code);

         //qty precision 下单数量精度
         double qtyStep=SymbolInfoDouble(symbol, SYMBOL_VOLUME_STEP);

         int point=StringFind((string)qtyStep,".",0);
         string qtyStepPreicsion=StringSubstr((string)qtyStep, point+1);
         // 按合约属性确定显示或计算使用的小数位数。
         // Determine decimal precision for display or calculation from symbol properties.
         int qtyPrecision=StringLen(qtyStepPreicsion);

         //price precision 下单价格精度
         // 按合约属性确定显示或计算使用的小数位数。
         // Determine decimal precision for display or calculation from symbol properties.
         int pricePrecision=(int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);

         // 逐项遍历返回数组,读取每条记录。
         // Iterate through the returned array and read each record.
         for(int i=0;i<jOrders.Size();i++)
           {
            CJAVal jOrder=jOrders[i];

            if(jOrder.Size()>0)
              {
               printf("order %d ==============================", i);

               // 读取 symbol 字段,表示交易对,使用 ToStr 转换。
               // Read symbol for trading symbol using ToStr.
               string eventSymbol=jOrder["symbol"].ToStr();// symbol 合约名称
               printf("symbol 合约名称 %s", eventSymbol);

               // 读取 orderId 字段,表示交易所订单 ID,使用 ToStr 转换。
               // Read orderId for exchange order ID using ToStr.
               string orderId=jOrder["orderId"].ToStr();//order id 系统订单号
               printf("order id 系统订单号 %s", orderId);

               // 读取 status 字段,表示订单状态,使用 ToStr 转换。
               // Read status for order status using ToStr.
               string status=jOrder["status"].ToStr();//order status 订单状态
               printf("order status 订单状态 %s", status);

               // 读取 clientOrderId 字段,表示用户自定义订单 ID,使用 ToStr 转换。
               // Read clientOrderId for client order ID using ToStr.
               string clientOrderId=jOrder["clientOrderId"].ToStr();//client order id 用户自定义的订单号
               printf("client order id 用户自定义的订单号 %s", clientOrderId);

               // 读取 price 字段,表示价格,使用 ToStr 转换。
               // Read price for price using ToStr.
               string price=jOrder["price"].ToStr();//price 委托价格
               printf("price 委托价格 %s", price);

               // 读取 avgPrice 字段,表示平均成交价,使用 ToStr 转换。
               // Read avgPrice for average fill price using ToStr.
               string avgPrice=jOrder["avgPrice"].ToStr();//average price 平均成交价
               printf("average price 平均成交价 %s", avgPrice);

               // 读取 origQty 字段,表示原始委托数量,使用 ToStr 转换。
               // Read origQty for original order quantity using ToStr.
               string origQty=jOrder["origQty"].ToStr();//original quantity 原始委托数量
               printf("original quantity 原始委托数量 %s", origQty);

               // 读取 executedQty 字段,表示累计成交数量,使用 ToStr 转换。
               // Read executedQty for executed quantity using ToStr.
               string executedQty=jOrder["executedQty"].ToStr();//executed quantity 成交量
               printf("executed quantity 成交量 %s", executedQty);

               // 读取 cumQuote 字段,表示累计成交金额,使用 ToStr 转换。
               // Read cumQuote for cumulative quote amount using ToStr.
               string cumQuote=jOrder["cumQuote"].ToStr();// 成交金额
               printf("成交金额 %s", cumQuote);

               // 读取 timeInForce 字段,表示订单有效方式,使用 ToStr 转换。
               // Read timeInForce for time in force using ToStr.
               string timeInForce=jOrder["timeInForce"].ToStr();//time In Force 有效方法
               printf("time In Force 有效方法 %s", timeInForce);

               // 读取 type 字段,表示订单类型,使用 ToStr 转换。
               // Read type for order type using ToStr.
               string type=jOrder["type"].ToStr();//order type 订单类型
               printf("order type 订单类型 %s", type);

               // 读取 reduceOnly 字段,表示是否仅减仓,使用 ToStr 转换。
               // Read reduceOnly for whether the order is reduce-only using ToStr.
               string reduceOnly=jOrder["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=jOrder["closePosition"].ToStr();// 是否条件全平仓
               printf("是否条件全平仓 %s", closePosition);

               // 读取 side 字段,表示买卖方向,使用 ToStr 转换。
               // Read side for order side using ToStr.
               string side=jOrder["side"].ToStr();//order side 买卖方向
               printf("order side 买卖方向 %s", side);

               // 读取 positionSide 字段,表示持仓方向,使用 ToStr 转换。
               // Read positionSide for position side using ToStr.
               string positionSide=jOrder["positionSide"].ToStr();//position side 持仓方向
               printf("position side 持仓方向 %s", positionSide);

               //calculate local timezone计算本地时区
               int timeZone=(int)(TimeLocal()-TimeGMT())/60/60;
               printf("local timezone %d", timeZone);

               // 读取 time 字段,表示时间戳,使用 ToStr 转换。
               // Read time for timestamp using ToStr.
               string time=jOrder["time"].ToStr();//create order 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 orderTime=(datetime)((long)time/1000)+timeZone*60*60;

               printf("create order time 创建订单时间 %s %s", time, (string)orderTime);

               // 读取 updateTime 字段,表示更新时间戳,使用 ToStr 转换。
               // Read updateTime for update timestamp using ToStr.
               string updateTime=jOrder["updateTime"].ToStr();//order update 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 updateDateTime=(datetime)((long)updateTime/1000)+timeZone*60*60;
               printf("order update time 订单更新时间 %s %s", updateTime, (string)updateDateTime);

               //calculate my EA position by my EA orders 根据本EA的单子计算本EA的仓位
               // 只统计客户订单号包含 myEA 标识的订单,归属判断依赖该标识的唯一性和查询结果覆盖范围。
               // Include only orders whose client order IDs contain myEA. Attribution depends on identifier uniqueness and query coverage.
               if(StringFind(clientOrderId,myEA)>=0)
                 {
                  if(positionSide=="LONG")
                    {
                     if(side=="BUY")  //buy open 多开
                       {
                        //current qty当前仓位数量
                        // 按当前买卖方向和持仓方向累加或扣减已成交数量。
                        // Add or subtract executed quantities according to the current order side and position side.
                        buyPositionQty+=(double)executedQty;

                        //open qty开仓数量
                        buyPositionOpenQty+=(double)executedQty;

                        buyCumQuote+=(double)cumQuote;
                       }
                     else  //buy close 多平
                       {
                        // 按当前买卖方向和持仓方向累加或扣减已成交数量。
                        // Add or subtract executed quantities according to the current order side and position side.
                        buyPositionQty-=(double)executedQty;

                        //set qty precision设置数量精度
                        buyPositionQty=NormalizeDouble(buyPositionQty, qtyPrecision);

                        if(buyPositionQty==0)
                          {
                           buyCumQuote=0;

                           printf("close all long position 平掉全部多仓");
                          }
                       }
                    }
                  else
                    {
                     if(side=="SELL")   //sell short空开
                       {
                        //current qty当前仓位数量
                        // 按当前买卖方向和持仓方向累加或扣减已成交数量。
                        // Add or subtract executed quantities according to the current order side and position side.
                        sellPositionQty+=(double)executedQty;

                        //open qty开仓数量
                        sellPositionOpenQty+=(double)executedQty;

                        sellCumQuote+=(double)cumQuote;
                       }
                     else //sell close 空平
                       {
                        // 按当前买卖方向和持仓方向累加或扣减已成交数量。
                        // Add or subtract executed quantities according to the current order side and position side.
                        sellPositionQty-=(double)executedQty;

                        //set qty precision设置数量精度
                        sellPositionQty=NormalizeDouble(sellPositionQty, qtyPrecision);

                        if(sellPositionQty==0)
                          {
                           sellCumQuote=0;

                           printf("close all short position 平掉全部空仓");
                          }
                       }
                    }
                 }
              }
           }

         double buyAveragePrice=0;

         //get current price获取当前价格
         double last=SymbolInfoDouble(symbol, SYMBOL_LAST);

         if(buyPositionQty>0)
           {
            //calculate open average price and set precision 计算开仓平均价格并设置精度
            buyAveragePrice=NormalizeDouble(buyCumQuote/buyPositionOpenQty, pricePrecision);
           }

         double sellAveragePrice=0;

         if(sellPositionQty>0)
           {
            //calculate open average price and set precision 计算开仓平均价格并设置精度
            sellAveragePrice=NormalizeDouble(sellCumQuote/sellPositionOpenQty, pricePrecision);
           }

         printf("%s %s long 多头仓位 %s average open price 平均开仓价格 %s", myEA, symbol, (string)buyPositionQty, (string)buyAveragePrice);

         printf("%s %s short 空头仓位 %s average open price 平均开仓价格 %s", myEA, symbol, (string)sellPositionQty, (string)sellAveragePrice);
        }

      //printf(sparam);

     }

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