diff --git a/src/lib_python_interop/python_interop_plugins/bybit_execution_gateway.py b/src/lib_python_interop/python_interop_plugins/bybit_execution_gateway.py index 97b185112..d4d7cd9ed 100644 --- a/src/lib_python_interop/python_interop_plugins/bybit_execution_gateway.py +++ b/src/lib_python_interop/python_interop_plugins/bybit_execution_gateway.py @@ -2,7 +2,7 @@ import json import time from typing import Optional import uuid -from pybit_unified_trading import WebSocket, WebSocketTrading +from pybit_unified_trading import WebSocket, WebSocketTrading, HTTP from spark_core import ( JsonElement, as_bool, @@ -21,6 +21,8 @@ from python_interop_module import ( PyCancelReplaceOrderRequest, PyCancelOrderRequest, PyExecutionReport, + PyPositionInfo, + PyPositionInfoList, PySecurity, PySecurityList, ) @@ -169,6 +171,7 @@ class BybitExecutionGateway(ExecutionGateway): self.stop_event = threading.Event() self.stream_cli: Optional[WebSocket] = None self.trade_cli: Optional[WebSocketTrading] = None + self.trade_http_cli: Optional[HTTP] = None # bts id -> exch id self.orders: dict[int, OrderData] = {} self.securities: dict[str, PySecurity] = {} @@ -238,6 +241,64 @@ class BybitExecutionGateway(ExecutionGateway): % (key, req_type, rsn, time.time_ns()) ) + def get_positions(self): + try: + next_pg = None + pos_dict: dict[str, PyPositionInfo] = {} + # Safe guard against spamming requests in endless loop. + MAX_REQUESTS = 10 + request_count = 0 + while True: + request_count += 1 + if request_count == MAX_REQUESTS: + raise ValueError( + f"BybitExecutionGateway.get_positions performed too many requests in loop ({MAX_REQUESTS})" + ) + # Just get USDT positions for now. + # TODO: support other settleCoins + params = {"category": "linear", "settleCoin": "USDT"} + if next_pg: + params["cursor"] = next_pg + http_res = self.trade_http_cli.get_positions(**params) + self.logger.info("[bybit_gw_pos_res.json]%s" % JsonElement(http_res)) + if type(http_res) != dict or http_res["retCode"] != 0: + break + res = http_res["result"] + posns: list = res["list"] + for p in posns: + exch_sec_id = p["symbol"] + pi: Optional[PyPositionInfo] = pos_dict.get(exch_sec_id) + # Convert ms to ns + ts = int(p["updatedTime"]) * 1_000_000 + if not pi: + pi = PyPositionInfo() + pos_dict[exch_sec_id] = pi + pi.set_venue("BYBIT") + pi.set_exchange_security_id(exch_sec_id) + pi.set_security_type(SecurityType.FUTURE.name) + pi.set_account(self.account) + pi.set_transact_time(ts) + else: + if pi.transact_time() < ts: + pi.set_transact_time(ts) + if p["side"] == "Buy": + pi.set_long_avg_cost(float(p["avgPrice"])) + pi.set_long_quantity(float(p["size"])) + else: + pi.set_short_avg_cost(float(p["avgPrice"])) + pi.set_short_quantity(float(p["size"])) + next_pg = res.get("nextPageCursor") + if not next_pg: + break + pos_infos = PyPositionInfoList() + for p in pos_dict.values(): + pos_infos.append(p) + self.bridge.on_position_info(pos_infos) + except Exception as e: + self.logger.error("[bybit_gw_get_pos_err.json]%s" % SLog(err=str(e))) + return False + return True + def start_impl(self, bridge: ExecutionGatewayBridge): def on_order_update(msg: dict): def on_error(err: str): @@ -297,6 +358,14 @@ class BybitExecutionGateway(ExecutionGateway): def on_exe_report(msg): self.logger.info("[bybit_gw_exe_rep.json]%s" % msg) + # Http client (gets position snapshots) + params = { + "api_key": self.api_key, + "api_secret": self.secret_key, + "testnet": self.use_testnet, + } + self.logger.info("[trade_http_cli.json]%s" % JsonElement(params)) + self.trade_http_cli = HTTP(**params) # Stream client (receives order updates) params = { "api_key": self.api_key, @@ -320,6 +389,8 @@ class BybitExecutionGateway(ExecutionGateway): self.logger.info("[bybit_gw_start_trd_cli.json]%s" % JsonElement(params)) self.trade_cli = WebSocketTrading(**params) self.bridge.on_is_ready(True) + POS_SNAPSHOT_INTERVAL = 10 + next_pos_snapshot_time = time.time() + POS_SNAPSHOT_INTERVAL # Sleep loop to keep thread alive and detect connection status changes conn_statuses = { "stream": self.stream_cli.is_connected(), @@ -339,6 +410,10 @@ class BybitExecutionGateway(ExecutionGateway): "[bybit_gw_connection_status.json]%s" % SLog(**conn_statuses), ) self.bridge.on_is_ready(all_connected) + now = time.time() + if now >= next_pos_snapshot_time: + self.get_positions() + next_pos_snapshot_time = now + POS_SNAPSHOT_INTERVAL def start(self, bridge: ExecutionGatewayBridge): def start_wrapper():