← All EA examples
1023 / MQL5 / USDⓈ-M FUTURES

How can MQL5 distinguish an EA’s position in One-way Mode by order identifiers?

On ACCOUNT_UPDATE, this example calls ufQueryAllOrders, selects records whose clientOrderId contains myEA and uses executed quantities with positionSide=BOTH and BUY/SELL sides to update directional quantity. It demonstrates reconstruction from order records, not an exchange-native independent position for each EA.

What do you need to use this example?

  • Install and configure MT5 Binance and API credentials. Make mt5binance.mqh, JAson.mqh and the account permissions required by this example available.
  • Use One-way Mode and order client IDs containing the same myEA marker. OnTick is empty. Although OnTimer is defined, OnInit does not call EventSetTimer, so the sample order is not automatically timer-triggered merely by attaching this source.

How does the source execute?

  1. OnInit initializes the API, curl handles and response buffer. runDemo constructs a myEA+GetTickCount() client ID and prepares a BUY MARKET request for quantity 0.006.
  2. For id==3333 and e==ACCOUNT_UPDATE, query orders for the symbol and filter by clientOrderId containing myEA and positionSide==BOTH.
  3. Add BUY executedQty to positionQty and subtract it for the other side. The sample also attempts an average-price calculation and prints quantity variables.

Attribution calculations are triggered by ACCOUNT_UPDATE. OnTick is empty and this source does not register a timer.

Calculation behavior in the source

The current source does not reset positionQty before each traversal, does not accumulate positionOpenQty in the calculation path, and shadows the global cumQuote with a same-named local variable. Its output should not be treated as a verified EA net position and average price. The page preserves the original algorithm.

Parameters and execution behavior

ParameterSource value or behavior
Main interfaceufQueryAllOrders
SymbolSymbol()
EA markermyEA
MatchingStringFind(clientOrderId, myEA) >= 0
Position sideBOTH
Fill quantity fieldexecutedQty
EventACCOUNT_UPDATE
Request timing windowrecvWindow = 3000 ms
Execution triggerAttribution calculations are triggered by ACCOUNT_UPDATE. OnTick is empty and this source does not register a timer.

Related guides and examples

Full MQL5 source code

//+------------------------------------------------------------------+
//| 4-币安U本位期货单向持仓模式获得本EA仓位BinanceUSDMarginSingleModeGetMyEaPosition.mq5
//| Copyright Copyright 2025, MetaQuotes Ltd.
//| https://www.mql5.com
//+------------------------------------------------------------------+

//import MQL binance API 引入MQL币安API头文件
// 在单向持仓模式下,通过客户订单号筛选本 EA 的订单并估算净持仓。
// Estimate this EA net position in One-way Mode by filtering orders using client order IDs.
// 引入币安 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 positionQty=0;
double cumQuote=0;
double positionOpenQty=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()
  {
//---
   // 初始化配置中已设置的币安 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)
  {
//---

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

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

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
// 在单向持仓模式下,通过客户订单号筛选本 EA 的订单并估算净持仓。
// Estimate this EA net position in One-way Mode by filtering orders using client order IDs.
void runDemo()
  {
   //my EA order indentify 本EA订单标识
   // 将 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", "", "MARKET", "", "", 0.006, 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(resultChar);

   // 读取 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 events ID are defined as 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=="BOTH")
                    {
                     if(side=="BUY")
                       {
                        //current qty当前仓位数量
                        // 按当前买卖方向和持仓方向累加或扣减已成交数量。
                        // Add or subtract executed quantities according to the current order side and position side.
                        positionQty+=(double)executedQty;
                        cumQuote+=(double)cumQuote;
                       }
                     else
                       {
                        // 按当前买卖方向和持仓方向累加或扣减已成交数量。
                        // Add or subtract executed quantities according to the current order side and position side.
                        positionQty-=(double)executedQty;
                        cumQuote+=(double)cumQuote;
                       }
                    }
                 }
              }
           }

         double averagePrice=0;

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

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


         printf("%s %s short 仓位 %s average open price 平均开仓价格 %s", myEA, symbol, (string)positionOpenQty, (string)averagePrice);
        }
     }

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