From db9667b450bd14e53b5cbd0faba9a3c9f70e8d29 Mon Sep 17 00:00:00 2001 From: PredictAsiaX Date: Sat, 5 Dec 2026 09:21:25 +0800 Subject: [PATCH] (feat) add PredictAsiaX prediction market connector (on Hummingbot v2.18.0) --- README.md | 1 + .../exchange/predictasiax/__init__.py | 0 ...predictasiax_api_order_book_data_source.py | 322 ++++++++ ...redictasiax_api_user_stream_data_source.py | 91 ++ .../predictasiax/predictasiax_auth.py | 21 + .../predictasiax/predictasiax_constants.py | 172 ++++ .../predictasiax/predictasiax_exchange.py | 777 ++++++++++++++++++ .../predictasiax/predictasiax_order_entry.py | 227 +++++ .../predictasiax/predictasiax_utils.py | 35 + .../predictasiax/predictasiax_web_utils.py | 81 ++ .../exchange/predictasiax/__init__.py | 0 ...predictasiax_api_order_book_data_source.py | 365 ++++++++ .../predictasiax/test_predictasiax_auth.py | 26 + .../test_predictasiax_exchange.py | 639 ++++++++++++++ .../test_predictasiax_order_entry.py | 255 ++++++ ...st_predictasiax_user_stream_data_source.py | 134 +++ .../test_predictasiax_web_utils.py | 41 + 17 files changed, 3187 insertions(+) create mode 100644 hummingbot/connector/exchange/predictasiax/__init__.py create mode 100644 hummingbot/connector/exchange/predictasiax/predictasiax_api_order_book_data_source.py create mode 100644 hummingbot/connector/exchange/predictasiax/predictasiax_api_user_stream_data_source.py create mode 100644 hummingbot/connector/exchange/predictasiax/predictasiax_auth.py create mode 100644 hummingbot/connector/exchange/predictasiax/predictasiax_constants.py create mode 100644 hummingbot/connector/exchange/predictasiax/predictasiax_exchange.py create mode 100644 hummingbot/connector/exchange/predictasiax/predictasiax_order_entry.py create mode 100644 hummingbot/connector/exchange/predictasiax/predictasiax_utils.py create mode 100644 hummingbot/connector/exchange/predictasiax/predictasiax_web_utils.py create mode 100644 test/hummingbot/connector/exchange/predictasiax/__init__.py create mode 100644 test/hummingbot/connector/exchange/predictasiax/test_predictasiax_api_order_book_data_source.py create mode 100644 test/hummingbot/connector/exchange/predictasiax/test_predictasiax_auth.py create mode 100644 test/hummingbot/connector/exchange/predictasiax/test_predictasiax_exchange.py create mode 100644 test/hummingbot/connector/exchange/predictasiax/test_predictasiax_order_entry.py create mode 100644 test/hummingbot/connector/exchange/predictasiax/test_predictasiax_user_stream_data_source.py create mode 100644 test/hummingbot/connector/exchange/predictasiax/test_predictasiax_web_utils.py diff --git a/README.md b/README.md index 20dadd443..bdb70d426 100644 --- a/README.md +++ b/README.md @@ -189,6 +189,7 @@ Currently, the master branch of Hummingbot also includes the following exchange | [OKX DEX](https://hummingbot.org/exchanges/gateway/jupiter/#other-solana-routers) | AMM DEX | Router | `okx` | - | | [Pacifica](https://hummingbot.org/exchanges/pacifica/) | CLOB CEX | Perpetual | `pacifica_perpetual` | - | | [PancakeSwap](https://hummingbot.org/exchanges/gateway/pancakeswap/) | AMM DEX | AMM | `pancakeswap` | - | +| [PredictAsiaX](https://docs.predictasiax.com/hummingbot) | CEX | Spot (prediction markets) | `predictasiax` | - | | [Raydium](https://hummingbot.org/exchanges/gateway/raydium/) | AMM DEX | AMM, CLMM | `raydium` | - | | [Titan](https://hummingbot.org/exchanges/gateway/jupiter/#other-solana-routers) | AMM DEX | Router | `titan` | - | | [Uniswap](https://hummingbot.org/exchanges/gateway/uniswap/) | AMM DEX | Router, AMM, CLMM | `uniswap` | - | diff --git a/hummingbot/connector/exchange/predictasiax/__init__.py b/hummingbot/connector/exchange/predictasiax/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/hummingbot/connector/exchange/predictasiax/predictasiax_api_order_book_data_source.py b/hummingbot/connector/exchange/predictasiax/predictasiax_api_order_book_data_source.py new file mode 100644 index 000000000..541e44c6b --- /dev/null +++ b/hummingbot/connector/exchange/predictasiax/predictasiax_api_order_book_data_source.py @@ -0,0 +1,322 @@ +import asyncio +import itertools +from decimal import Decimal +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple + +from hummingbot.connector.exchange.predictasiax import ( + predictasiax_constants as CONSTANTS, + predictasiax_web_utils as web_utils, +) +from hummingbot.core.data_type.common import TradeType +from hummingbot.core.data_type.order_book_message import OrderBookMessage, OrderBookMessageType +from hummingbot.core.data_type.order_book_tracker_data_source import OrderBookTrackerDataSource +from hummingbot.core.web_assistant.connections.data_types import RESTMethod, WSJSONRequest +from hummingbot.core.web_assistant.web_assistants_factory import WebAssistantsFactory +from hummingbot.core.web_assistant.ws_assistant import WSAssistant + +if TYPE_CHECKING: + from hummingbot.connector.exchange.predictasiax.predictasiax_exchange import PredictasiaxExchange + +ONE = Decimal("1") + + +def _levels(raw_levels: Any) -> List[Tuple[Decimal, Decimal]]: + levels = [] + for level in raw_levels or []: + try: + price = Decimal(str(level[0])) + size = Decimal(str(level[1])) + except Exception: + continue + if size >= 0 and 0 < price < 1: + levels.append((price, size)) + return levels + + +def _rows(levels: Iterable[Tuple[Decimal, Decimal]], descending: bool) -> List[List[str]]: + return [[str(price), str(size)] for price, size in sorted(levels, key=lambda lv: lv[0], reverse=descending)] + + +def outcome_levels( + bids: Any, asks: Any, outcome: str +) -> Tuple[List[List[str]], List[List[str]]]: + """ + Bids and asks of one outcome from the consolidated YES book. + + The YES book already includes the liquidity of the NO side: YES bids include NO asks at + 1 - p, YES asks include NO bids at 1 - p. The NO book is the exact complement: NO bids = 1 - YES asks, NO asks = 1 - YES bids. Bids come best (highest) first, + asks best (lowest) first. Sizes are kept as sent, so a size of 0 (a removed level in a + delta) passes through. + """ + yes_bids, yes_asks = _levels(bids), _levels(asks) + if outcome == "YES": + return _rows(yes_bids, descending=True), _rows(yes_asks, descending=False) + no_bids = [(ONE - price, size) for price, size in yes_asks] + no_asks = [(ONE - price, size) for price, size in yes_bids] + return _rows(no_bids, descending=True), _rows(no_asks, descending=False) + + +class PredictasiaxAPIOrderBookDataSource(OrderBookTrackerDataSource): + """ + Order books from the exchange's market data channel. Each market is one consolidated YES book + kept by sequence number: a snapshot, then deltas with absolute level sizes. A missing sequence + number triggers a fresh snapshot; deltas are ignored until it arrives. Both trading pairs of a + market (YES and NO) are fed from the same book, the NO pair as its complement. + """ + + def __init__( + self, + trading_pairs: List[str], + connector: 'PredictasiaxExchange', + api_factory: WebAssistantsFactory, + domain: str = CONSTANTS.DEFAULT_DOMAIN, + ): + super().__init__(trading_pairs) + self._connector = connector + self._api_factory = api_factory + self._domain = domain + self._ws_assistant: Optional[WSAssistant] = None + # market id -> (epoch, seq) of the last applied book message; absent = waiting for a snapshot + self._book_seq: Dict[str, Tuple[int, int]] = {} + self._trade_counter = itertools.count(1) + + async def get_last_traded_prices(self, trading_pairs: List[str], domain: Optional[str] = None) -> Dict[str, float]: + markets = await self._connector.fetch_all_markets() + prices_by_market = {str(m.get("id")): (m.get("prices") or {}) for m in markets} + result = {} + for trading_pair in trading_pairs: + market_id, outcome = await self._connector.market_and_outcome(trading_pair) + price = prices_by_market.get(market_id, {}).get(outcome.lower()) + if price is not None: + result[trading_pair] = float(price) + return result + + # ----- subscriptions + + async def _markets_of(self, trading_pairs: Iterable[str]) -> List[str]: + markets = [] + for trading_pair in trading_pairs: + market_id, _ = await self._connector.market_and_outcome(trading_pair) + if market_id not in markets: + markets.append(market_id) + return markets + + @staticmethod + def _topic(market_id: str) -> str: + return CONSTANTS.WS_BOOK_TOPIC.format(market_id) + + async def _send(self, method: str, topics: List[str]) -> bool: + ws = self._ws_assistant + if ws is None or not topics: + return False + await ws.send(WSJSONRequest(payload={"method": method, "params": topics})) + return True + + async def subscribe_to_trading_pair(self, trading_pair: str) -> bool: + if trading_pair in self._trading_pairs: + self.logger().warning(f"{trading_pair} already subscribed. Ignoring request.") + return True + market_id, _ = await self._connector.market_and_outcome(trading_pair) + already = market_id in await self._markets_of(self._trading_pairs) + self.add_trading_pair(trading_pair) + if already: + # The other outcome of this market is tracked: replay the book for the new pair. + return await self._send(CONSTANTS.WS_BOOK_RESYNC_METHOD, [self._topic(market_id)]) or True + try: + await self._send("SUBSCRIBE", [self._topic(market_id)]) + except asyncio.CancelledError: + raise + except Exception: + self.logger().exception(f"Error subscribing to the order book of {trading_pair}.") + return False + return True + + async def unsubscribe_from_trading_pair(self, trading_pair: str) -> bool: + if trading_pair not in self._trading_pairs: + self.logger().warning(f"{trading_pair} not subscribed. Ignoring request.") + return True + market_id, _ = await self._connector.market_and_outcome(trading_pair) + self.remove_trading_pair(trading_pair) + if market_id in await self._markets_of(self._trading_pairs): + return True + self._book_seq.pop(market_id, None) + try: + await self._send("UNSUBSCRIBE", [self._topic(market_id)]) + except asyncio.CancelledError: + raise + except Exception: + self.logger().exception(f"Error unsubscribing from the order book of {trading_pair}.") + return False + return True + + async def _connected_websocket_assistant(self) -> WSAssistant: + ws: WSAssistant = await self._api_factory.get_ws_assistant() + await ws.connect(ws_url=web_utils.wss_url(self._domain), ping_timeout=CONSTANTS.WS_PING_INTERVAL) + return ws + + async def _subscribe_channels(self, ws: WSAssistant): + try: + self._ws_assistant = ws + self._book_seq.clear() + await ws.send(WSJSONRequest(payload={"method": "UNSUBSCRIBE", "params": CONSTANTS.WS_DEFAULT_CHANNELS})) + topics = [self._topic(m) for m in await self._markets_of(self._trading_pairs)] + if topics: + await ws.send(WSJSONRequest(payload={"method": "SUBSCRIBE", "params": topics})) + self.logger().info("Subscribed to public order book channels...") + except asyncio.CancelledError: + raise + except Exception: + self.logger().error("Unexpected error occurred subscribing to order book streams...", exc_info=True) + raise + + async def _on_order_stream_interruption(self, websocket_assistant: Optional[WSAssistant] = None): + self._ws_assistant = None + self._book_seq.clear() + await super()._on_order_stream_interruption(websocket_assistant) + + async def _process_websocket_messages(self, websocket_assistant: WSAssistant): + # The proxy closes a socket after 60 seconds without traffic: send an application ping + # whenever the stream has been quiet for WS_PING_INTERVAL seconds. + while True: + try: + await asyncio.wait_for(self._dispatch_messages(websocket_assistant), + timeout=CONSTANTS.WS_PING_INTERVAL) + return + except asyncio.TimeoutError: + await websocket_assistant.send(WSJSONRequest(payload={"type": "ping"})) + + async def _dispatch_messages(self, websocket_assistant: WSAssistant): + valid_channels = self._get_messages_queue_keys() + async for ws_response in websocket_assistant.iter_messages(): + for message in web_utils.decode_ws_frame(ws_response.data): + channel = self._channel_originating_message(event_message=message) + if channel in valid_channels: + self._message_queue[channel].put_nowait(message) + + def _channel_originating_message(self, event_message: Dict[str, Any]) -> str: + channel = "" + event_type = event_message.get("type") + if event_type in ("error", "subscribe_denied", CONSTANTS.WS_BOOK_ERROR_EVENT): + self.logger().error(f"Error in WS stream: {event_message}") + elif int(event_message.get("outcome") or 0) != 0: + pass + elif event_type == CONSTANTS.WS_BOOK_SNAPSHOT_EVENT: + channel = self._snapshot_messages_queue_key + elif event_type == CONSTANTS.WS_BOOK_DELTA_EVENT: + channel = self._diff_messages_queue_key + elif event_type == CONSTANTS.WS_LAST_TRADE_EVENT: + channel = self._trade_messages_queue_key + return channel + + # ----- order book + + @staticmethod + def _update_id(epoch: int, seq: int) -> int: + return epoch * CONSTANTS.BOOK_EPOCH_SCALE + seq + + async def _tracked_pairs_of_market(self, market_id: str) -> List[Tuple[str, str]]: + pairs = [] + for trading_pair in list(self._trading_pairs): + pair_market, outcome = await self._connector.market_and_outcome(trading_pair) + if pair_market == market_id: + pairs.append((trading_pair, outcome)) + return pairs + + def _book_message( + self, message_type: OrderBookMessageType, raw: Dict[str, Any], trading_pair: str, outcome: str, + update_id: int, bids: Any, asks: Any, + ) -> OrderBookMessage: + pair_bids, pair_asks = outcome_levels(bids, asks, outcome) + ts_ms = raw.get("ts") + timestamp = float(ts_ms) * 1e-3 if ts_ms else self._time() + return OrderBookMessage( + message_type=message_type, + content={"trading_pair": trading_pair, "update_id": update_id, "bids": pair_bids, "asks": pair_asks}, + timestamp=timestamp, + ) + + async def _request_market_book(self, market_id: str) -> Dict[str, Any]: + rest_assistant = await self._api_factory.get_rest_assistant() + return await rest_assistant.execute_request( + url=web_utils.market_data_url(CONSTANTS.MARKET_BOOK_PATH_URL.format(market_id), domain=self._domain), + method=RESTMethod.GET, + throttler_limit_id=CONSTANTS.MARKET_BOOK_LIMIT_ID, + ) + + async def _order_book_snapshot(self, trading_pair: str) -> OrderBookMessage: + market_id, outcome = await self._connector.market_and_outcome(trading_pair) + book = await self._request_market_book(market_id) + if book.get("type") != CONSTANTS.WS_BOOK_SNAPSHOT_EVENT: + raise IOError(f"Order book of market {market_id} unavailable: {book}") + update_id = self._update_id(int(book.get("epoch") or 0), int(book.get("seq") or 0)) + return self._book_message(OrderBookMessageType.SNAPSHOT, book, trading_pair, outcome, update_id, + book.get("bids"), book.get("asks")) + + async def _parse_order_book_snapshot_message(self, raw_message: Dict[str, Any], message_queue: asyncio.Queue): + market_id = str(raw_message.get("market") or "") + if not market_id: + return + epoch, seq = int(raw_message.get("epoch") or 0), int(raw_message.get("seq") or 0) + self._book_seq[market_id] = (epoch, seq) + for trading_pair, outcome in await self._tracked_pairs_of_market(market_id): + message_queue.put_nowait(self._book_message( + OrderBookMessageType.SNAPSHOT, raw_message, trading_pair, outcome, self._update_id(epoch, seq), + raw_message.get("bids"), raw_message.get("asks"))) + + async def _parse_order_book_diff_message(self, raw_message: Dict[str, Any], message_queue: asyncio.Queue): + market_id = str(raw_message.get("market") or "") + state = self._book_seq.get(market_id) + if not market_id or state is None: + return + epoch, last_seq = state + seq = int(raw_message.get("seq") or 0) + if seq <= last_seq: + return + if seq != last_seq + 1: + self.logger().info(f"Order book of {market_id} skipped from seq {last_seq} to {seq}; resyncing.") + del self._book_seq[market_id] + await self._send(CONSTANTS.WS_BOOK_RESYNC_METHOD, [self._topic(market_id)]) + return + self._book_seq[market_id] = (epoch, seq) + bids, asks = [], [] + for change in raw_message.get("changes") or []: + if len(change) >= 3 and change[0] in ("bid", "ask"): + (bids if change[0] == "bid" else asks).append(change[1:3]) + for trading_pair, outcome in await self._tracked_pairs_of_market(market_id): + message_queue.put_nowait(self._book_message( + OrderBookMessageType.DIFF, raw_message, trading_pair, outcome, self._update_id(epoch, seq), + bids, asks)) + + # ----- trades + + async def _parse_trade_message(self, raw_message: Dict[str, Any], message_queue: asyncio.Queue): + """ + Every fill is reported once, in YES terms: price of a YES share and the taker's direction + (buy or sell YES). The NO pair sees the same trade at 1 - price in the opposite direction. + """ + market_id = str(raw_message.get("market") or "") + side = str(raw_message.get("side") or "") + if not market_id or side not in ("buy", "sell"): + return + try: + price = Decimal(str(raw_message["price"])) + size = Decimal(str(raw_message["size"])) + except Exception: + return + ts_ms = int(raw_message.get("ts") or self._time() * 1e3) + trade_id = f"{market_id}-{ts_ms}-{next(self._trade_counter)}" + for trading_pair, outcome in await self._tracked_pairs_of_market(market_id): + yes = outcome == "YES" + is_buy = (side == "buy") == yes + message_queue.put_nowait(OrderBookMessage( + message_type=OrderBookMessageType.TRADE, + content={ + "trade_id": trade_id, + "trading_pair": trading_pair, + "trade_type": float(TradeType.BUY.value) if is_buy else float(TradeType.SELL.value), + "update_id": ts_ms, + "price": str(price if yes else ONE - price), + "amount": str(size), + }, + timestamp=ts_ms * 1e-3, + )) diff --git a/hummingbot/connector/exchange/predictasiax/predictasiax_api_user_stream_data_source.py b/hummingbot/connector/exchange/predictasiax/predictasiax_api_user_stream_data_source.py new file mode 100644 index 000000000..0c7929f3e --- /dev/null +++ b/hummingbot/connector/exchange/predictasiax/predictasiax_api_user_stream_data_source.py @@ -0,0 +1,91 @@ +import asyncio +from typing import TYPE_CHECKING, Optional + +from hummingbot.connector.exchange.predictasiax import ( + predictasiax_constants as CONSTANTS, + predictasiax_web_utils as web_utils, +) +from hummingbot.connector.exchange.predictasiax.predictasiax_auth import PredictasiaxAuth +from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSource +from hummingbot.core.web_assistant.connections.data_types import RESTMethod, WSJSONRequest +from hummingbot.core.web_assistant.web_assistants_factory import WebAssistantsFactory +from hummingbot.core.web_assistant.ws_assistant import WSAssistant +from hummingbot.logger import HummingbotLogger + +if TYPE_CHECKING: + from hummingbot.connector.exchange.predictasiax.predictasiax_exchange import PredictasiaxExchange + + +class PredictasiaxAPIUserStreamDataSource(UserStreamTrackerDataSource): + """ + Account events for the API key's account. The socket signs in with a single-use token minted + over REST (POST /v1/ws/token, scope orders:read); a new token is minted for every connection. + """ + _logger: Optional[HummingbotLogger] = None + + def __init__( + self, + auth: PredictasiaxAuth, + connector: 'PredictasiaxExchange', + api_factory: WebAssistantsFactory, + domain: str = CONSTANTS.DEFAULT_DOMAIN, + ): + super().__init__() + self._auth = auth + self._connector = connector + self._api_factory = api_factory + self._domain = domain + + async def _sign_in_token(self) -> str: + rest_assistant = await self._api_factory.get_rest_assistant() + response = await rest_assistant.execute_request( + url=web_utils.private_rest_url(CONSTANTS.WS_TOKEN_PATH_URL, domain=self._domain), + method=RESTMethod.POST, + data={}, + is_auth_required=True, + throttler_limit_id=CONSTANTS.WS_TOKEN_PATH_URL, + ) + token = (web_utils.response_data(response) or {}).get("token") + if not token: + raise IOError(f"No WebSocket sign-in token in response: {response}") + return token + + async def _connected_websocket_assistant(self) -> WSAssistant: + token = await self._sign_in_token() + ws: WSAssistant = await self._api_factory.get_ws_assistant() + await ws.connect(ws_url=web_utils.wss_url(self._domain), ping_timeout=CONSTANTS.WS_PING_INTERVAL) + await ws.send(WSJSONRequest(payload={"method": "AUTH", "token": token})) + await asyncio.wait_for(self._wait_for_sign_in(ws), timeout=CONSTANTS.WS_AUTH_TIMEOUT) + return ws + + async def _wait_for_sign_in(self, ws: WSAssistant): + async for response in ws.iter_messages(): + for message in web_utils.decode_ws_frame(response.data): + message_type = message.get("type") + if message_type == "authenticated": + self.logger().info("PredictAsiaX private WebSocket connection authenticated.") + return + if message_type == "auth_denied": + raise ConnectionError(f"PredictAsiaX WebSocket sign-in refused: {message}") + raise ConnectionError("PredictAsiaX WebSocket closed before sign-in completed.") + + async def _subscribe_channels(self, websocket_assistant: WSAssistant): + # Account events are pushed to a signed-in socket without SUBSCRIBE; drop the default + # price streams this socket does not need. + await websocket_assistant.send(WSJSONRequest( + payload={"method": "UNSUBSCRIBE", "params": CONSTANTS.WS_DEFAULT_CHANNELS})) + + async def _process_websocket_messages(self, websocket_assistant: WSAssistant, queue: asyncio.Queue): + while True: + try: + await asyncio.wait_for(self._dispatch_messages(websocket_assistant, queue), + timeout=CONSTANTS.WS_PING_INTERVAL) + return + except asyncio.TimeoutError: + await websocket_assistant.send(WSJSONRequest(payload={"type": "ping"})) + + async def _dispatch_messages(self, websocket_assistant: WSAssistant, queue: asyncio.Queue): + async for ws_response in websocket_assistant.iter_messages(): + for message in web_utils.decode_ws_frame(ws_response.data): + if message.get("type") in CONSTANTS.WS_ACCOUNT_EVENTS: + queue.put_nowait(message) diff --git a/hummingbot/connector/exchange/predictasiax/predictasiax_auth.py b/hummingbot/connector/exchange/predictasiax/predictasiax_auth.py new file mode 100644 index 000000000..ca52579eb --- /dev/null +++ b/hummingbot/connector/exchange/predictasiax/predictasiax_auth.py @@ -0,0 +1,21 @@ +from hummingbot.core.web_assistant.auth import AuthBase +from hummingbot.core.web_assistant.connections.data_types import RESTRequest, WSRequest + + +class PredictasiaxAuth(AuthBase): + """ + REST requests carry the API key as a bearer token. The key is never sent on the WebSocket: + the user stream mints a single-use sign-in token over REST and sends it in an AUTH message. + """ + + def __init__(self, api_key: str): + self.api_key = api_key + + async def rest_authenticate(self, request: RESTRequest) -> RESTRequest: + headers = dict(request.headers or {}) + headers["Authorization"] = f"Bearer {self.api_key}" + request.headers = headers + return request + + async def ws_authenticate(self, request: WSRequest) -> WSRequest: + return request # pass-through diff --git a/hummingbot/connector/exchange/predictasiax/predictasiax_constants.py b/hummingbot/connector/exchange/predictasiax/predictasiax_constants.py new file mode 100644 index 000000000..207a62f51 --- /dev/null +++ b/hummingbot/connector/exchange/predictasiax/predictasiax_constants.py @@ -0,0 +1,172 @@ +from decimal import Decimal + +from hummingbot.core.api_throttler.data_types import LinkedLimitWeightPair, RateLimit +from hummingbot.core.data_type.in_flight_order import OrderState + +EXCHANGE_NAME = "predictasiax" +DEFAULT_DOMAIN = "predictasiax" + +REST_URL = "https://api.predictasiax.com" +# Market data (order book, trades) is served by the exchange's own web origin. +MARKET_DATA_URL = "https://predictasiax.com" +WSS_URL = "wss://predictasiax.com/ws" + +HBOT_ORDER_ID_PREFIX = "PAX" +# Sent as the Idempotency-Key header too, which accepts 8 to 128 characters of [A-Za-z0-9_-]. +MAX_ORDER_ID_LEN = 40 + +# Every market is a binary YES/NO market settled in USDT. Each outcome is its own trading pair: +# market "btc-200k-2026" gives BTC_200K_2026_YES-USDT and BTC_200K_2026_NO-USDT. +QUOTE_ASSET = "USDT" +OUTCOMES = ("YES", "NO") +SYMBOL_SEPARATOR = ":" + +# Prices are probabilities. Orders that can rest (limit, post-only) must sit on the tick grid: +# 0.01 steps from 0.04 to 0.96, 0.001 steps below 0.04 and above 0.96. +MIN_PRICE = Decimal("0.001") +MAX_PRICE = Decimal("0.999") +FINE_TICK = Decimal("0.001") +COARSE_TICK = Decimal("0.01") +COARSE_TICK_LOW = Decimal("0.04") +COARSE_TICK_HIGH = Decimal("0.96") +# Orders that never rest (ioc, used for market orders) take 4 decimals. +TAKER_PRICE_QUANTUM = Decimal("0.0001") +SIZE_QUANTUM = Decimal("0.000001") +# Order notional (size x price) bounds, lib/orderParams.js. A SELL of the whole sellable +# position is admitted below the minimum. +MIN_ORDER_NOTIONAL = Decimal("1") + +# REST paths +HEALTH_PATH_URL = "/v1/health" +MARKETS_PATH_URL = "/v1/markets" +# Consolidated order book of one market, as the exchange holds it: YES bids include the +# offers implied by NO asks (1 - p), YES asks include those implied by NO bids. The NO book is +# its exact complement. Same snapshot as the WebSocket "book:" channel, same seq. +MARKET_BOOK_PATH_URL = "/api/orderbook/{}?format=l2" +ORDERS_PATH_URL = "/v1/orders" +ORDER_PATH_URL = "/v1/orders/{}" +BALANCE_PATH_URL = "/v1/balance" +POSITIONS_PATH_URL = "/v1/positions" +FEES_ESTIMATE_PATH_URL = "/v1/fees/estimate" +WS_TOKEN_PATH_URL = "/v1/ws/token" +# Fills of the account's orders, newest first; ?order_id= narrows to one order. role maker|taker, +# price per share in the order's outcome, fee_usdt the fee charged. +FILLS_PATH_URL = "/v1/fills" +FILLS_PAGE_LIMIT = 200 +# Fills of an order placed on the WebSocket are read from FILLS_PATH_URL; the trade store can +# trail the order reply by a moment. +FILLS_ATTEMPTS = 4 +FILLS_RETRY_DELAY = 0.5 + +MARKETS_PAGE_LIMIT = 100 +ORDERS_PAGE_LIMIT = 200 +MAX_PAGES = 50 + +# Order states reported by /v1/orders +ORDER_STATE = { + "OPEN": OrderState.OPEN, + "PARTIAL": OrderState.PARTIALLY_FILLED, + "PARTIALLY_FILLED": OrderState.PARTIALLY_FILLED, + "FILLED": OrderState.FILLED, + "CANCELLED": OrderState.CANCELED, + "CANCELED": OrderState.CANCELED, + "EXPIRED": OrderState.CANCELED, + "REJECTED": OrderState.FAILED, +} +OPEN_ORDER_STATUSES = "open,partially_filled" + +# Taker fee curve, published by /v1/fees/estimate ("paf"): clamp(base x 4p(1-p), floor, ceiling) +# basis points of the fill notional at fill price p; a fill between two buyers of opposite +# outcomes (reported in "mint_fills") pays half. Account discounts (VIP / PAX holding) come off it, so it is an upper bound. Resting +# (maker) orders pay no fee. The values below are used until the published ones are read. +PAF_BASE_BPS = Decimal("20") +PAF_FLOOR_BPS = Decimal("8") +PAF_CEILING_BPS = Decimal("25") +TAKER_FEE_CEILING = PAF_CEILING_BPS / Decimal("10000") + +# WebSocket +WS_PING_INTERVAL = 25.0 +WS_AUTH_TIMEOUT = 10.0 +# Order book channel per market: "book:". The server answers a subscription with a +# book_snapshot {seq, epoch, bids, asks}, then sends book_delta {seq, changes: [[bid|ask, price, +# absolute size]]} with seq rising by exactly one per change, and last_trade {price, size, side} +# for every fill (YES terms; side is the taker's direction). A gap in seq means a lost delta: +# BOOK_SNAPSHOT asks for a fresh snapshot. epoch changes when the server restarts. +WS_BOOK_TOPIC = "book:{}" +WS_BOOK_SNAPSHOT_EVENT = "book_snapshot" +WS_BOOK_DELTA_EVENT = "book_delta" +WS_LAST_TRADE_EVENT = "last_trade" +WS_BOOK_ERROR_EVENT = "book_error" +WS_BOOK_RESYNC_METHOD = "BOOK_SNAPSHOT" +# update_id = epoch (ms) x this + seq, so ids keep rising across server restarts. +BOOK_EPOCH_SCALE = 1_000_000 +# Every socket starts subscribed to these busy price streams; the connector does not use them. +WS_DEFAULT_CHANNELS = ["ticker", "fast_tick"] +# Account events delivered to a socket signed in with an API sign-in token. Their payloads are +# not part of the public contract, so they only trigger a REST refresh of orders and balances. +WS_ACCOUNT_EVENTS = { + "user_orders_update", "order_filled", "order_update", "balance_updated", "position_updated", "trade_result", +} + +# Order entry on the signed-in WebSocket (docs.predictasiax.com/rate-limits#ws-orders), for API keys +# of builder accounts at every tier that places real orders. Each request carries a req_id and gets +# one reply with it (order_ack / cancel_ack). It does not use the REST orders:create budget: placing +# and cancelling have per-second token buckets sized by the account's 30-day volume, reported on +# sign-in in "authenticated".order_entry (orders_per_s, cancels_per_s, in_flight); the values below +# are the lowest tier's, used until the reported ones are read. +WS_PLACE_ORDER_LIMIT_ID = "WSPlaceOrder" +WS_CANCEL_ORDER_LIMIT_ID = "WSCancelOrder" +WS_ORDERS_PER_S = 10 +WS_CANCELS_PER_S = 20 +WS_ORDER_IN_FLIGHT = 64 +WS_ORDER_REPLY_TIMEOUT = 10.0 +WS_ORDER_ATTEMPTS = 3 +WS_ORDER_RETRY_DELAY = 0.5 +# The key cannot place orders on the socket: REST is used, and the socket is tried again later. +WS_ORDER_ENTRY_OFF_CODES = {"ORDER_ENTRY_NOT_AVAILABLE", "TIER_NOT_ELIGIBLE", "SCOPE_MISSING"} +WS_ORDER_ENTRY_RETRY_AFTER = 600.0 +WS_ORDER_CONNECT_RETRY_AFTER = 30.0 +# Refused before it was submitted, and not counted: sign in again, then resend. +WS_ORDER_SIGN_IN_CODES = {"SESSION_EXPIRED", "AUTH_REQUIRED"} +# Refused before it was submitted, and not counted: this request goes over REST instead. +WS_ORDER_REST_CODES = {"RATE_LIMITED", "TOO_MANY_IN_FLIGHT"} + +# Rate limits: fixed 60-second windows per API key and scope (docs.predictasiax.com/rate-limits). +ONE_MINUTE = 60 +SCOPE_MARKETS_READ = "markets:read" +SCOPE_ORDERS_READ = "orders:read" +SCOPE_ORDERS_CREATE = "orders:create" +SCOPE_ORDERS_CANCEL = "orders:cancel" +SCOPE_PORTFOLIO_READ = "portfolio:read" +ORDER_CANCEL_LIMIT_ID = "OrderCancel" +MARKET_BOOK_LIMIT_ID = "MarketBook" + +RATE_LIMITS = [ + RateLimit(limit_id=SCOPE_MARKETS_READ, limit=600, time_interval=ONE_MINUTE), + RateLimit(limit_id=SCOPE_ORDERS_READ, limit=300, time_interval=ONE_MINUTE), + RateLimit(limit_id=SCOPE_ORDERS_CREATE, limit=30, time_interval=ONE_MINUTE), + RateLimit(limit_id=SCOPE_ORDERS_CANCEL, limit=60, time_interval=ONE_MINUTE), + RateLimit(limit_id=SCOPE_PORTFOLIO_READ, limit=120, time_interval=ONE_MINUTE), + RateLimit(limit_id=HEALTH_PATH_URL, limit=60, time_interval=ONE_MINUTE), + RateLimit(limit_id=WS_TOKEN_PATH_URL, limit=10, time_interval=ONE_MINUTE), + RateLimit(limit_id=MARKETS_PATH_URL, limit=600, time_interval=ONE_MINUTE, + linked_limits=[LinkedLimitWeightPair(SCOPE_MARKETS_READ)]), + RateLimit(limit_id=MARKET_BOOK_LIMIT_ID, limit=120, time_interval=ONE_MINUTE), + RateLimit(limit_id=FEES_ESTIMATE_PATH_URL, limit=600, time_interval=ONE_MINUTE, + linked_limits=[LinkedLimitWeightPair(SCOPE_MARKETS_READ)]), + RateLimit(limit_id=ORDERS_PATH_URL, limit=300, time_interval=ONE_MINUTE, + linked_limits=[LinkedLimitWeightPair(SCOPE_ORDERS_READ)]), + RateLimit(limit_id="OrderCreate", limit=30, time_interval=ONE_MINUTE, + linked_limits=[LinkedLimitWeightPair(SCOPE_ORDERS_CREATE)]), + RateLimit(limit_id=ORDER_CANCEL_LIMIT_ID, limit=60, time_interval=ONE_MINUTE, + linked_limits=[LinkedLimitWeightPair(SCOPE_ORDERS_CANCEL)]), + RateLimit(limit_id=FILLS_PATH_URL, limit=300, time_interval=ONE_MINUTE, + linked_limits=[LinkedLimitWeightPair(SCOPE_ORDERS_READ)]), + RateLimit(limit_id=WS_PLACE_ORDER_LIMIT_ID, limit=WS_ORDERS_PER_S, time_interval=1), + RateLimit(limit_id=WS_CANCEL_ORDER_LIMIT_ID, limit=WS_CANCELS_PER_S, time_interval=1), + RateLimit(limit_id=BALANCE_PATH_URL, limit=120, time_interval=ONE_MINUTE, + linked_limits=[LinkedLimitWeightPair(SCOPE_PORTFOLIO_READ)]), + RateLimit(limit_id=POSITIONS_PATH_URL, limit=120, time_interval=ONE_MINUTE, + linked_limits=[LinkedLimitWeightPair(SCOPE_PORTFOLIO_READ)]), +] +ORDER_CREATE_LIMIT_ID = "OrderCreate" diff --git a/hummingbot/connector/exchange/predictasiax/predictasiax_exchange.py b/hummingbot/connector/exchange/predictasiax/predictasiax_exchange.py new file mode 100644 index 000000000..e37aeee88 --- /dev/null +++ b/hummingbot/connector/exchange/predictasiax/predictasiax_exchange.py @@ -0,0 +1,777 @@ +import asyncio +import copy +import math +import re +import time +from decimal import ROUND_CEILING, ROUND_FLOOR, Decimal +from typing import Any, Dict, List, Optional, Tuple + +from bidict import bidict + +from hummingbot.connector.constants import s_decimal_0, s_decimal_NaN +from hummingbot.connector.exchange.predictasiax import ( + predictasiax_constants as CONSTANTS, + predictasiax_web_utils as web_utils, +) +from hummingbot.connector.exchange.predictasiax.predictasiax_api_order_book_data_source import ( + PredictasiaxAPIOrderBookDataSource, +) +from hummingbot.connector.exchange.predictasiax.predictasiax_api_user_stream_data_source import ( + PredictasiaxAPIUserStreamDataSource, +) +from hummingbot.connector.exchange.predictasiax.predictasiax_auth import PredictasiaxAuth +from hummingbot.connector.exchange.predictasiax.predictasiax_order_entry import PredictasiaxOrderEntry +from hummingbot.connector.exchange_py_base import ExchangePyBase +from hummingbot.connector.trading_rule import TradingRule +from hummingbot.connector.utils import combine_to_hb_trading_pair +from hummingbot.core.api_throttler.data_types import RateLimit +from hummingbot.core.data_type.common import OrderType, TradeType +from hummingbot.core.data_type.in_flight_order import InFlightOrder, OrderState, OrderUpdate, TradeUpdate +from hummingbot.core.data_type.order_book_tracker_data_source import OrderBookTrackerDataSource +from hummingbot.core.data_type.trade_fee import TokenAmount, TradeFeeBase +from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSource +from hummingbot.core.utils.estimate_fee import build_trade_fee +from hummingbot.core.web_assistant.auth import AuthBase +from hummingbot.core.web_assistant.web_assistants_factory import WebAssistantsFactory + +FILL_EPSILON = Decimal("0.0000001") +ORDER_LOOKBACK_MS = 120_000 +ORDER_ROWS_TTL = 1.0 + + +class PredictasiaxExchange(ExchangePyBase): + """ + PredictAsiaX binary prediction markets. Every market has two outcome shares, YES and NO, each + priced between 0 and 1 USDT and paying 1 USDT if the outcome happens. Each outcome is a spot + trading pair against USDT: buying the base buys shares of that outcome, selling sells shares + the account holds. + """ + + # Account events only trigger a REST refresh, so polling stays frequent while the stream is up. + LONG_POLL_INTERVAL = 15.0 + + web_utils = web_utils + + def __init__( + self, + predictasiax_api_key: str, + balance_asset_limit: Optional[Dict[str, Dict[str, Decimal]]] = None, + rate_limits_share_pct: Decimal = Decimal("100"), + trading_pairs: Optional[List[str]] = None, + trading_required: bool = True, + domain: str = CONSTANTS.DEFAULT_DOMAIN, + ): + self._api_key = predictasiax_api_key + self._domain = domain + self._trading_required = trading_required + self._trading_pairs = trading_pairs + self._order_rows_cache: Dict[str, Tuple[float, int, List[Dict[str, Any]]]] = {} + self._order_rows_lock = asyncio.Lock() + self._paf_bps: Tuple[Decimal, Decimal, Decimal] = ( + CONSTANTS.PAF_BASE_BPS, CONSTANTS.PAF_FLOOR_BPS, CONSTANTS.PAF_CEILING_BPS) + self._placement_reports: Dict[str, Dict[str, Any]] = {} + super().__init__(balance_asset_limit, rate_limits_share_pct) + # Orders and cancels go on the signed-in WebSocket when the key may use it (builder + # accounts), and over REST otherwise; see PredictasiaxOrderEntry. + self._order_entry: Optional[PredictasiaxOrderEntry] = ( + PredictasiaxOrderEntry(self._web_assistants_factory, self._throttler, domain=self._domain) + if trading_required else None) + + @staticmethod + def base_asset_for(market_id: str, outcome: str) -> str: + return re.sub(r"[^A-Za-z0-9]", "_", market_id).upper() + "_" + outcome + + @property + def name(self) -> str: + return CONSTANTS.EXCHANGE_NAME + + @property + def authenticator(self) -> AuthBase: + return PredictasiaxAuth(api_key=self._api_key) + + @property + def rate_limits_rules(self) -> List[RateLimit]: + return CONSTANTS.RATE_LIMITS + + @property + def domain(self) -> str: + return self._domain + + @property + def client_order_id_max_length(self) -> int: + return CONSTANTS.MAX_ORDER_ID_LEN + + @property + def client_order_id_prefix(self) -> str: + return CONSTANTS.HBOT_ORDER_ID_PREFIX + + @property + def trading_rules_request_path(self) -> str: + return CONSTANTS.MARKETS_PATH_URL + + @property + def trading_pairs_request_path(self) -> str: + return CONSTANTS.MARKETS_PATH_URL + + @property + def check_network_request_path(self) -> str: + return CONSTANTS.HEALTH_PATH_URL + + @property + def trading_pairs(self) -> List[str]: + return self._trading_pairs + + @property + def is_cancel_request_in_exchange_synchronous(self) -> bool: + return True + + @property + def is_trading_required(self) -> bool: + return self._trading_required + + def supported_order_types(self) -> List[OrderType]: + return [OrderType.LIMIT, OrderType.LIMIT_MAKER, OrderType.MARKET] + + # ----- symbols and markets ----- + + async def market_and_outcome(self, trading_pair: str) -> Tuple[str, str]: + symbol = await self.exchange_symbol_associated_to_pair(trading_pair=trading_pair) + market_id, outcome = symbol.rsplit(CONSTANTS.SYMBOL_SEPARATOR, 1) + return market_id, outcome + + async def fetch_all_markets(self) -> List[Dict[str, Any]]: + markets: List[Dict[str, Any]] = [] + cursor = None + for _ in range(CONSTANTS.MAX_PAGES): + params = {"limit": CONSTANTS.MARKETS_PAGE_LIMIT} + if cursor: + params["cursor"] = cursor + response = await self._api_get(path_url=CONSTANTS.MARKETS_PATH_URL, params=params, + limit_id=CONSTANTS.MARKETS_PATH_URL) + data = web_utils.response_data(response) or {} + markets.extend(data.get("markets") or []) + cursor = (data.get("page") or {}).get("next_cursor") + if not cursor: + break + return markets + + async def _make_trading_pairs_request(self) -> Any: + return {"markets": await self.fetch_all_markets()} + + async def _make_trading_rules_request(self) -> Any: + return {"markets": await self.fetch_all_markets()} + + async def _make_network_check_request(self): + await self._api_get(path_url=CONSTANTS.HEALTH_PATH_URL, limit_id=CONSTANTS.HEALTH_PATH_URL) + + def _initialize_trading_pair_symbols_from_exchange_info(self, exchange_info: Dict[str, Any]): + mapping = bidict() + for market in exchange_info.get("markets", []): + market_id = str(market.get("id") or "") + if not market_id: + continue + for outcome in CONSTANTS.OUTCOMES: + symbol = f"{market_id}{CONSTANTS.SYMBOL_SEPARATOR}{outcome}" + trading_pair = combine_to_hb_trading_pair(self.base_asset_for(market_id, outcome), + CONSTANTS.QUOTE_ASSET) + if trading_pair in mapping.inverse: + self.logger().warning( + f"Market {market_id} maps to trading pair {trading_pair}, already used by " + f"{mapping.inverse[trading_pair]}. Skipping it.") + continue + mapping[symbol] = trading_pair + self._set_trading_pair_symbol_map(mapping) + + async def _format_trading_rules(self, exchange_info_dict: Dict[str, Any]) -> List[TradingRule]: + rules = [] + for market in exchange_info_dict.get("markets", []): + if str(market.get("status") or "").lower() != "open": + continue + for outcome in CONSTANTS.OUTCOMES: + symbol = f"{market.get('id')}{CONSTANTS.SYMBOL_SEPARATOR}{outcome}" + try: + trading_pair = await self.trading_pair_associated_to_exchange_symbol(symbol=symbol) + except KeyError: + continue + rules.append(TradingRule( + trading_pair, + min_order_size=CONSTANTS.SIZE_QUANTUM, + min_price_increment=CONSTANTS.FINE_TICK, + min_base_amount_increment=CONSTANTS.SIZE_QUANTUM, + min_notional_size=CONSTANTS.MIN_ORDER_NOTIONAL, + )) + return rules + + def get_order_price_quantum(self, trading_pair: str, price: Decimal) -> Decimal: + if CONSTANTS.COARSE_TICK_LOW <= price <= CONSTANTS.COARSE_TICK_HIGH: + return CONSTANTS.COARSE_TICK + return CONSTANTS.FINE_TICK + + def quantize_order_price(self, trading_pair: str, price: Decimal) -> Decimal: + if price.is_nan(): + return price + quantum = self.get_order_price_quantum(trading_pair, price) + quantized = (price / quantum).to_integral_value(rounding=ROUND_FLOOR) * quantum + return min(max(quantized, CONSTANTS.MIN_PRICE), CONSTANTS.MAX_PRICE) + + # ----- errors ----- + + def _is_request_exception_related_to_time_synchronizer(self, request_exception: Exception) -> bool: + return False + + def _is_order_not_found_during_status_update_error(self, status_update_exception: Exception) -> bool: + return "ORDER_NOT_FOUND" in str(status_update_exception) + + def _is_order_not_found_during_cancelation_error(self, cancelation_exception: Exception) -> bool: + return "ORDER_NOT_FOUND" in str(cancelation_exception) + + async def _update_time_synchronizer(self, pass_on_non_cancelled_error: bool = False): + # API keys are sent as bearer tokens; requests carry no client timestamp to synchronize. + pass + + # ----- orders ----- + + def _taker_price(self, trading_pair: str, is_buy: bool, amount: Decimal) -> Decimal: + """Worst price needed to fill `amount` against the local book, as the bound of an ioc order.""" + try: + result = self.get_price_for_volume(trading_pair, is_buy, amount) + price = Decimal(str(result.result_price)) + except Exception: + price = s_decimal_NaN + if not price.is_finite() or price <= 0: + return CONSTANTS.MAX_PRICE if is_buy else CONSTANTS.MIN_PRICE + rounding = ROUND_CEILING if is_buy else ROUND_FLOOR + price = price.quantize(CONSTANTS.TAKER_PRICE_QUANTUM, rounding=rounding) + return min(max(price, CONSTANTS.MIN_PRICE), CONSTANTS.MAX_PRICE) + + def _sells_whole_position(self, trading_pair: str, amount: Decimal) -> bool: + """Same rule as the platform (orderRouter sellsAll): the SELL takes everything sellable.""" + sellable = self.get_available_balance(trading_pair.split("-")[0]) + return sellable > 0 and amount >= sellable - CONSTANTS.SIZE_QUANTUM + + async def _create_order( + self, + trade_type: TradeType, + order_id: str, + trading_pair: str, + amount: Decimal, + order_type: OrderType, + price: Optional[Decimal] = None, + **kwargs, + ): + if order_type is OrderType.MARKET and (price is None or not price.is_finite() or price <= 0): + # The ioc bound a market order is sent with is the price its notional is checked at, + # here and on the platform. + price = self._taker_price(trading_pair, trade_type is TradeType.BUY, amount) + rule = self._trading_rules.get(trading_pair) + if (rule is not None and trade_type is TradeType.SELL and rule.min_notional_size > s_decimal_0 + and self._sells_whole_position(trading_pair, amount)): + # The platform admits a SELL of the whole sellable position below the minimum + # notional; the rule is relaxed for this order's checks only. + relaxed = copy.copy(rule) + relaxed.min_notional_size = s_decimal_0 + self._trading_rules[trading_pair] = relaxed + try: + await super()._create_order(trade_type, order_id, trading_pair, amount, order_type, price, **kwargs) + finally: + if self._trading_rules.get(trading_pair) is relaxed: + self._trading_rules[trading_pair] = rule + return + await super()._create_order(trade_type, order_id, trading_pair, amount, order_type, price, **kwargs) + + async def _place_order( + self, + order_id: str, + trading_pair: str, + amount: Decimal, + trade_type: TradeType, + order_type: OrderType, + price: Decimal, + **kwargs, + ) -> Tuple[str, float]: + market_id, outcome = await self.market_and_outcome(trading_pair) + is_buy = trade_type is TradeType.BUY + body: Dict[str, Any] = { + "market_id": market_id, + "side": outcome.lower(), + "action": "buy" if is_buy else "sell", + "size": str(amount), + "client_order_id": order_id, + } + if order_type is OrderType.MARKET: + # A market order on the platform never funds a new share pair against bids of the + # other outcome; an ioc order with a price bound does, and takes the same liquidity. + body["order_type"] = "ioc" + if price is None or not price.is_finite() or price <= 0: + price = self._taker_price(trading_pair, is_buy, amount) + body["price"] = str(price) + else: + body["order_type"] = "post_only" if order_type is OrderType.LIMIT_MAKER else "limit" + body["price"] = str(price) + ack = await self._order_entry.place(body) if self._order_entry is not None else None + if ack is not None: + report = await self._order_ack_report(order_id, ack) + else: + response = await self._api_post( + path_url=CONSTANTS.ORDERS_PATH_URL, + data=body, + is_auth_required=True, + limit_id=CONSTANTS.ORDER_CREATE_LIMIT_ID, + headers={"Idempotency-Key": order_id}, + ) + report = web_utils.response_data(response) + if not isinstance(report, dict): + raise IOError(f"Error submitting order {order_id}: {response}") + if response.get("ok") is False: + raise IOError(f"Order {order_id} rejected: {report.get('reject_reason') or report}") + status = str(report.get("status") or "").upper() + if report.get("ok") is False or status == "REJECTED": + raise IOError(f"Order {order_id} rejected: {report.get('reject_reason') or report}") + exchange_order_id = report.get("order_id") + if not exchange_order_id and status == "DUPLICATE": + exchange_order_id = await self._find_order_placed_earlier(market_id, outcome, body) + if not exchange_order_id: + raise IOError(f"Error submitting order {order_id}: no order id in {report}") + self._placement_reports[order_id] = report + return str(exchange_order_id), self.current_timestamp + + async def _order_ack_report(self, order_id: str, ack: Dict[str, Any]) -> Dict[str, Any]: + """ + An order_ack as a placement report. The ack gives the size the order filled on arrival and + the trade ids of those fills; their prices and fees are read from the account's fills. + """ + if ack.get("ok") is not True: + error = ack.get("error") or {} + raise IOError(f"Order {order_id} rejected: {error.get('code')}: {error.get('message')}") + report = dict(ack.get("data") or {}) + exchange_order_id = report.get("order_id") + filled = Decimal(str(report.get("filled_size") or 0)) + if exchange_order_id and filled > 0: + trade_ids = [str(t) for t in report.get("trade_ids") or [] if t] + report["fills"] = await self._arrival_fills(str(exchange_order_id), filled, trade_ids) + return report + + async def _arrival_fills(self, exchange_order_id: str, filled: Decimal, + trade_ids: Optional[List[str]] = None) -> List[Dict[str, Any]]: + """ + The fills the order made on arrival, read once each trade id of the order_ack is listed + (or after FILLS_ATTEMPTS reads); the fills list names a fill by the same trade id. An ack + without trade ids falls back to the order's taker fills, read until they add up to `filled` + (an order takes liquidity only when it arrives, so every taker fill of it is one of these). + """ + wanted = set(trade_ids or []) + fills: List[Dict[str, Any]] = [] + for attempt in range(CONSTANTS.FILLS_ATTEMPTS): + if attempt: + await self._sleep(CONSTANTS.FILLS_RETRY_DELAY) + try: + response = await self._api_get( + path_url=CONSTANTS.FILLS_PATH_URL, + params={"order_id": exchange_order_id, "limit": CONSTANTS.FILLS_PAGE_LIMIT}, + is_auth_required=True, + limit_id=CONSTANTS.FILLS_PATH_URL, + ) + except asyncio.CancelledError: + raise + except Exception as e: + self.logger().warning(f"Fills of order {exchange_order_id} not read ({e}).") + continue + rows = (web_utils.response_data(response) or {}).get("fills") or [] + fills = [f for f in rows if str(f.get("role") or "").lower() == "taker" and f.get("trade_id")] + if wanted: + fills = [f for f in fills if str(f["trade_id"]) in wanted] + if {str(f["trade_id"]) for f in fills} >= wanted: + return fills + elif sum(Decimal(str(f.get("size") or 0)) for f in fills) >= filled - FILL_EPSILON: + return fills + # The order list reports the filled size: what is not listed here is taken up from it. + self.logger().warning(f"Fills of order {exchange_order_id} not all listed yet " + f"({len(fills)} listed); the rest follow from the order status.") + return fills + + async def _place_order_and_process_update(self, order: InFlightOrder, **kwargs) -> str: + exchange_order_id, update_timestamp = await self._place_order( + order_id=order.client_order_id, + trading_pair=order.trading_pair, + amount=order.amount, + trade_type=order.trade_type, + order_type=order.order_type, + price=order.price, + **kwargs, + ) + exchange_order_id = str(exchange_order_id) + # The creation is processed before the fills the order made on arrival, so the created + # event always precedes the order's fill events. + if order.is_pending_create: + await self._order_tracker._process_order_update(OrderUpdate( + client_order_id=order.client_order_id, + exchange_order_id=exchange_order_id, + trading_pair=order.trading_pair, + update_timestamp=update_timestamp, + new_state=OrderState.OPEN, + )) + report = self._placement_reports.pop(order.client_order_id, None) + if report is not None: + self._process_placement_report(order, exchange_order_id, report) + return exchange_order_id + + def _process_placement_report(self, order: InFlightOrder, exchange_order_id: str, report: Dict[str, Any]): + """Fills made when the order arrived: it was the taker of each, at the prices reported.""" + fills = ([(fill, False) for fill in report.get("fills") or []] + + [(fill, True) for fill in report.get("mint_fills") or []]) + for fill, is_pair_fill in fills: + size = Decimal(str(fill.get("size") or 0)) + price = Decimal(str(fill.get("price") or 0)) + if size <= 0 or not fill.get("trade_id"): + continue + # Fills read from /v1/fills carry the fee charged; placement reports leave it to the curve. + fee = Decimal(str(fill["fee_usdt"])) if fill.get("fee_usdt") is not None else None + timestamp = fill.get("executed_at_ms") + self._order_tracker.process_trade_update(self._trade_update( + order, exchange_order_id, str(fill["trade_id"]), size, price, is_taker=True, is_pair_fill=is_pair_fill, + fee_amount=fee, timestamp=timestamp * 1e-3 if isinstance(timestamp, (int, float)) else None)) + status = str(report.get("status") or "").upper() + new_state = CONSTANTS.ORDER_STATE.get(status) + if new_state is not None and new_state != OrderState.OPEN: + self._order_tracker.process_order_update(OrderUpdate( + client_order_id=order.client_order_id, + exchange_order_id=exchange_order_id, + trading_pair=order.trading_pair, + update_timestamp=self.current_timestamp, + new_state=new_state, + )) + + async def _find_order_placed_earlier(self, market_id: str, outcome: str, body: Dict[str, Any]) -> Optional[str]: + """An idempotent retry of a placement that already went through: find that order.""" + since_ms = int(self._time() * 1e3) - ORDER_LOOKBACK_MS + rows = await self._order_rows(market_id, since_ms, force=True) + tracked = {o.exchange_order_id for o in self._order_tracker.all_orders.values() if o.exchange_order_id} + size = Decimal(body["size"]) + matches = [ + r for r in rows + if str(r.get("side") or "").upper() == outcome + and str(r.get("action") or "").upper() == body["action"].upper() + and Decimal(str(r.get("size") or 0)) == size + and str(r.get("id")) not in tracked + ] + return str(matches[0]["id"]) if len(matches) == 1 else None + + async def _place_cancel(self, order_id: str, tracked_order: InFlightOrder): + exchange_order_id = await tracked_order.get_exchange_order_id() + ack = await self._order_entry.cancel(exchange_order_id) if self._order_entry is not None else None + if ack is not None: + result = ack.get("data") or {} + if ack.get("ok") is not True and not result: + error = ack.get("error") or {} + raise IOError(f"Cancel of order {order_id} refused: {error.get('code')}: {error.get('message')}") + if result.get("cancelled"): + return True + current = str(result.get("status") or "").upper() + if current in ("CANCELLED", "CANCELED", "EXPIRED"): + return True + if current == "NOT_FOUND": + raise IOError(f"ORDER_NOT_FOUND: order {order_id} ({exchange_order_id}) is unknown to the exchange") + return False + response = await self._api_delete( + path_url=CONSTANTS.ORDER_PATH_URL.format(exchange_order_id), + is_auth_required=True, + limit_id=CONSTANTS.ORDER_CANCEL_LIMIT_ID, + ) + result = web_utils.response_data(response) or {} + if result.get("cancelled"): + return True + current = str(result.get("current_status") or "").upper() + if current in ("CANCELLED", "CANCELED", "EXPIRED"): + return True + if current == "NOT_FOUND": + raise IOError(f"ORDER_NOT_FOUND: order {order_id} ({exchange_order_id}) is unknown to the exchange") + return False + + async def _order_rows(self, market_id: str, since_ms: int, force: bool = False) -> List[Dict[str, Any]]: + """ + The account's orders on one market created since `since_ms`, newest first. One read serves + every order of the market polled within ORDER_ROWS_TTL seconds. + """ + async with self._order_rows_lock: + cached = self._order_rows_cache.get(market_id) + now = self._time() + if not force and cached is not None and now - cached[0] < ORDER_ROWS_TTL and cached[1] <= since_ms: + return cached[2] + rows: List[Dict[str, Any]] = [] + cursor = None + for _ in range(CONSTANTS.MAX_PAGES): + params = {"market_id": market_id, "from_ms": since_ms, "limit": CONSTANTS.ORDERS_PAGE_LIMIT} + if cursor: + params["cursor"] = cursor + response = await self._api_get(path_url=CONSTANTS.ORDERS_PATH_URL, params=params, + is_auth_required=True, limit_id=CONSTANTS.ORDERS_PATH_URL) + data = web_utils.response_data(response) or {} + rows.extend(data.get("orders") or []) + cursor = data.get("next_cursor") + if not cursor: + break + self._order_rows_cache[market_id] = (now, since_ms, rows) + return rows + + async def _order_row(self, order: InFlightOrder) -> Optional[Dict[str, Any]]: + if order.exchange_order_id is None: + return None + market_id, _ = await self.market_and_outcome(order.trading_pair) + created = order.creation_timestamp + if isinstance(created, (int, float)) and math.isfinite(created) and created > 0: + since_ms = max(0, int(created * 1e3) - ORDER_LOOKBACK_MS) + else: + since_ms = 0 # creation time unknown: read the market's whole order list + for row in await self._order_rows(market_id, since_ms): + if str(row.get("id")) == order.exchange_order_id: + return row + return None + + @staticmethod + def _row_timestamp(row: Dict[str, Any], fallback: float) -> float: + for key in ("updated_at_ms", "created_at_ms"): + value = row.get(key) + if isinstance(value, (int, float)) and value > 0: + return value * 1e-3 + return fallback + + async def _request_order_status(self, tracked_order: InFlightOrder) -> OrderUpdate: + if tracked_order.exchange_order_id is None: + return OrderUpdate( + client_order_id=tracked_order.client_order_id, + trading_pair=tracked_order.trading_pair, + update_timestamp=self.current_timestamp, + new_state=tracked_order.current_state, + ) + row = await self._order_row(tracked_order) + if row is None: + raise IOError(f"ORDER_NOT_FOUND: order {tracked_order.client_order_id} " + f"({tracked_order.exchange_order_id}) not in the account's order list") + status = str(row.get("status") or "").upper() + new_state = CONSTANTS.ORDER_STATE.get(status, tracked_order.current_state) + return OrderUpdate( + client_order_id=tracked_order.client_order_id, + exchange_order_id=tracked_order.exchange_order_id, + trading_pair=tracked_order.trading_pair, + update_timestamp=self._row_timestamp(row, self.current_timestamp), + new_state=new_state, + ) + + async def _all_trade_updates_for_order(self, order: InFlightOrder) -> List[TradeUpdate]: + """ + Fills made while the order rested on the book. The order list reports the filled size; + a resting order is always filled at its own price and pays no fee, so each increase of the + filled size is one maker fill. Fills made on arrival come from the placement response. + """ + row = await self._order_row(order) + if row is None: + return [] + filled = Decimal(str(row.get("filled_size") or 0)) + new_fill = filled - order.executed_amount_base + if new_fill <= FILL_EPSILON: + return [] + price = Decimal(str(row.get("price") or order.price)) + return [self._trade_update( + order, order.exchange_order_id, f"{order.exchange_order_id}-{filled.normalize()}", + new_fill, price, is_taker=False, + timestamp=self._row_timestamp(row, self.current_timestamp))] + + def _trade_update(self, order: InFlightOrder, exchange_order_id: str, trade_id: str, size: Decimal, + price: Decimal, is_taker: bool, timestamp: Optional[float] = None, + is_pair_fill: bool = False, fee_amount: Optional[Decimal] = None) -> TradeUpdate: + quote_amount = size * price + flat_fees = [] + if is_taker: + if fee_amount is None: + fee_amount = quote_amount * self.taker_fee_rate(price, is_pair_fill=is_pair_fill) + flat_fees = [TokenAmount(token=CONSTANTS.QUOTE_ASSET, amount=fee_amount)] + fee = TradeFeeBase.new_spot_fee( + fee_schema=self.trade_fee_schema(), + trade_type=order.trade_type, + flat_fees=flat_fees, + ) + return TradeUpdate( + trade_id=trade_id, + client_order_id=order.client_order_id, + exchange_order_id=exchange_order_id, + trading_pair=order.trading_pair, + fee=fee, + fill_base_amount=size, + fill_quote_amount=quote_amount, + fill_price=price, + fill_timestamp=timestamp if timestamp is not None else self.current_timestamp, + ) + + # ----- fees ----- + + def _get_fee( + self, + base_currency: str, + quote_currency: str, + order_type: OrderType, + order_side: TradeType, + amount: Decimal, + price: Decimal = s_decimal_NaN, + is_maker: Optional[bool] = None, + ) -> TradeFeeBase: + is_maker = is_maker or (order_type is OrderType.LIMIT_MAKER) + if is_maker: + return build_trade_fee( + self.name, + is_maker, + base_currency=base_currency, + quote_currency=quote_currency, + order_type=order_type, + order_side=order_side, + amount=amount, + price=price, + ) + return TradeFeeBase.new_spot_fee( + fee_schema=self.trade_fee_schema(), + trade_type=order_side, + percent=self.taker_fee_rate(price), + ) + + def taker_fee_rate(self, price: Decimal, is_pair_fill: bool = False) -> Decimal: + """Taker fee as a fraction of the fill notional at fill price `price`, before account discounts.""" + base, floor, ceiling = self._paf_bps + if price is None or not price.is_finite() or not (s_decimal_0 < price < 1): + bps = ceiling + else: + bps = min(max(base * 4 * price * (1 - price), floor), ceiling) + rate = bps / Decimal("10000") + return rate / 2 if is_pair_fill else rate + + async def _update_trading_fees(self): + """Reads the published taker fee curve; the last values read stay in use if it fails.""" + try: + symbols = list((await self.trading_pair_symbol_map()).keys()) + if not symbols: + return + market_id = symbols[0].rsplit(CONSTANTS.SYMBOL_SEPARATOR, 1)[0] + response = await self._api_get( + path_url=CONSTANTS.FEES_ESTIMATE_PATH_URL, + params={"market_id": market_id, "price": "0.5", "size": "2"}, + is_auth_required=True, + limit_id=CONSTANTS.FEES_ESTIMATE_PATH_URL, + ) + paf = (web_utils.response_data(response) or {}).get("paf") or {} + values = tuple(Decimal(str(paf[k])) for k in ("base_bps", "floor_bps", "ceiling_bps")) + except asyncio.CancelledError: + raise + except Exception: + self.logger().warning("Could not read the platform fee curve; keeping the last values.", exc_info=True) + return + base, floor, ceiling = values + if s_decimal_0 <= floor <= ceiling and base >= 0: + self._paf_bps = (base, floor, ceiling) + + # ----- balances ----- + + async def _open_sell_commitments(self) -> Dict[Tuple[str, str], Decimal]: + """Shares the account has offered in resting sell orders, by (market, outcome).""" + committed: Dict[Tuple[str, str], Decimal] = {} + cursor = None + for _ in range(CONSTANTS.MAX_PAGES): + params = {"status": CONSTANTS.OPEN_ORDER_STATUSES, "limit": CONSTANTS.ORDERS_PAGE_LIMIT} + if cursor: + params["cursor"] = cursor + response = await self._api_get(path_url=CONSTANTS.ORDERS_PATH_URL, params=params, + is_auth_required=True, limit_id=CONSTANTS.ORDERS_PATH_URL) + data = web_utils.response_data(response) or {} + for row in data.get("orders") or []: + if str(row.get("action") or "").upper() != "SELL": + continue + key = (str(row.get("market_id")), str(row.get("side") or "").upper()) + remaining = Decimal(str(row.get("size") or 0)) - Decimal(str(row.get("filled_size") or 0)) + committed[key] = committed.get(key, s_decimal_0) + max(remaining, s_decimal_0) + cursor = data.get("next_cursor") + if not cursor: + break + return committed + + async def _update_balances(self): + balance_response, positions_response, committed = await asyncio.gather( + self._api_get(path_url=CONSTANTS.BALANCE_PATH_URL, is_auth_required=True, + limit_id=CONSTANTS.BALANCE_PATH_URL), + self._api_get(path_url=CONSTANTS.POSITIONS_PATH_URL, is_auth_required=True, + limit_id=CONSTANTS.POSITIONS_PATH_URL), + self._open_sell_commitments(), + ) + available: Dict[str, Decimal] = {} + total: Dict[str, Decimal] = {} + for entry in (web_utils.response_data(balance_response) or {}).get("balances") or []: + asset = str(entry["asset"]).upper() + free = Decimal(str(entry.get("free") or 0)) + reserved = Decimal(str(entry.get("reserved") or 0)) + available[asset] = free + total[asset] = free + reserved + + held: Dict[Tuple[str, str], Decimal] = {} + for position in (web_utils.response_data(positions_response) or {}).get("positions") or []: + key = (str(position.get("market_id")), str(position.get("side") or "").upper()) + if key[1] not in CONSTANTS.OUTCOMES: + continue + held[key] = held.get(key, s_decimal_0) + Decimal(str(position.get("lots") or 0)) + for (market_id, outcome), lots in held.items(): + if lots <= 0: + continue + asset = self.base_asset_for(market_id, outcome) + total[asset] = lots + available[asset] = max(lots - committed.get((market_id, outcome), s_decimal_0), s_decimal_0) + + for asset in set(self._account_balances.keys()) - set(total.keys()): + self._account_balances.pop(asset, None) + self._account_available_balances.pop(asset, None) + self._account_balances.update(total) + self._account_available_balances.update(available) + + # ----- user stream ----- + + async def _user_stream_event_listener(self): + """ + Account events say that orders or balances changed; the REST state is read right away. + """ + async for event_message in self._iter_user_event_queue(): + try: + if event_message.get("type") in CONSTANTS.WS_ACCOUNT_EVENTS: + self._order_rows_cache.clear() + self._poll_notifier.set() + except asyncio.CancelledError: + raise + except Exception: + self.logger().error("Unexpected error in user stream listener loop.", exc_info=True) + await self._sleep(5.0) + + async def stop_network(self): + if self._order_entry is not None: + await self._order_entry.stop() + await super().stop_network() + + # ----- factories ----- + + def _create_web_assistants_factory(self) -> WebAssistantsFactory: + return web_utils.build_api_factory(throttler=self._throttler, auth=self._auth) + + def _create_order_book_data_source(self) -> OrderBookTrackerDataSource: + return PredictasiaxAPIOrderBookDataSource( + trading_pairs=self._trading_pairs, + connector=self, + api_factory=self._web_assistants_factory, + domain=self.domain, + ) + + def _create_user_stream_data_source(self) -> UserStreamTrackerDataSource: + return PredictasiaxAPIUserStreamDataSource( + auth=self._auth, + connector=self, + api_factory=self._web_assistants_factory, + domain=self.domain, + ) + + async def _get_last_traded_price(self, trading_pair: str) -> float: + prices = await self._orderbook_ds.get_last_traded_prices(trading_pairs=[trading_pair]) + return prices[trading_pair] + + def _time(self) -> float: + return time.time() diff --git a/hummingbot/connector/exchange/predictasiax/predictasiax_order_entry.py b/hummingbot/connector/exchange/predictasiax/predictasiax_order_entry.py new file mode 100644 index 000000000..eab09ff79 --- /dev/null +++ b/hummingbot/connector/exchange/predictasiax/predictasiax_order_entry.py @@ -0,0 +1,227 @@ +import asyncio +import itertools +import time +from typing import Any, Dict, Optional + +from hummingbot.connector.exchange.predictasiax import ( + predictasiax_constants as CONSTANTS, + predictasiax_web_utils as web_utils, +) +from hummingbot.core.api_throttler.async_throttler import AsyncThrottler +from hummingbot.core.web_assistant.connections.data_types import RESTMethod, WSJSONRequest +from hummingbot.core.web_assistant.web_assistants_factory import WebAssistantsFactory +from hummingbot.core.web_assistant.ws_assistant import WSAssistant +from hummingbot.logger import HummingbotLogger + + +class PredictasiaxOrderEntry: + """ + Order entry on the signed-in WebSocket (docs.predictasiax.com/rate-limits#ws-orders): + PLACE_ORDER and CANCEL_ORDER on a socket of its own, signed in with a token minted with the + API key. Each request carries a req_id and gets exactly one reply with it. These requests do + not use the REST orders:create budget; they have per-second limits instead. + + `place` and `cancel` return the reply, or None when the caller should send the request over + REST instead: order entry is not available for the key, the socket could not be opened, the + request was refused before it was submitted (RATE_LIMITED, TOO_MANY_IN_FLIGHT), or no answer + came after WS_ORDER_ATTEMPTS tries. A request that may have reached the platform (the socket + closed before the reply, or SERVICE_UNAVAILABLE) is sent again with the same client_order_id, + on the socket and then over REST: the platform never places a second order for it, and + answers a repeat with the first result or with status DUPLICATE. + """ + _logger: Optional[HummingbotLogger] = None + + def __init__(self, api_factory: WebAssistantsFactory, throttler: AsyncThrottler, + domain: str = CONSTANTS.DEFAULT_DOMAIN): + self._api_factory = api_factory + self._throttler = throttler + self._domain = domain + self._ws: Optional[WSAssistant] = None + self._reader: Optional[asyncio.Task] = None + self._pending: Dict[int, asyncio.Future] = {} + self._ids = itertools.count(1) + self._lock = asyncio.Lock() + self._in_flight = asyncio.Semaphore(CONSTANTS.WS_ORDER_IN_FLIGHT) + self._unavailable_until = 0.0 + self.limits: Dict[str, Any] = {} + + @classmethod + def logger(cls) -> HummingbotLogger: + if cls._logger is None: + cls._logger = HummingbotLogger(__name__) + return cls._logger + + # ----- public ----- + + async def place(self, order: Dict[str, Any]) -> Optional[Dict[str, Any]]: + """The order_ack for `order` (the body of POST /v1/orders), or None: send it over REST.""" + return await self._call("PLACE_ORDER", {"order": order}, CONSTANTS.WS_PLACE_ORDER_LIMIT_ID) + + async def cancel(self, exchange_order_id: str) -> Optional[Dict[str, Any]]: + """The cancel_ack for the order, or None: cancel it over REST.""" + return await self._call("CANCEL_ORDER", {"order_id": exchange_order_id}, CONSTANTS.WS_CANCEL_ORDER_LIMIT_ID) + + async def stop(self): + await self._close() + + # ----- requests ----- + + async def _call(self, method: str, params: Dict[str, Any], limit_id: str) -> Optional[Dict[str, Any]]: + for attempt in range(CONSTANTS.WS_ORDER_ATTEMPTS): + last = attempt + 1 >= CONSTANTS.WS_ORDER_ATTEMPTS + ws = await self._socket() + if ws is None: + return None + try: + async with self._throttler.execute_task(limit_id=limit_id): + reply = await self._request(ws, method, params) + except (ConnectionError, asyncio.TimeoutError) as e: + self.logger().warning(f"PredictAsiaX order entry: {method} got no reply ({e}); sending it again.") + await self._close() + continue + code = str((reply.get("error") or {}).get("code") or "") + if code in CONSTANTS.WS_ORDER_ENTRY_OFF_CODES: + self._unavailable_until = time.time() + CONSTANTS.WS_ORDER_ENTRY_RETRY_AFTER + self.logger().info(f"PredictAsiaX order entry not available ({code}); using REST.") + await self._close() + return None + if code in CONSTANTS.WS_ORDER_REST_CODES: + return None + if code in CONSTANTS.WS_ORDER_SIGN_IN_CODES and not last: + await self._close() + continue + if code == "SERVICE_UNAVAILABLE" and not last: + await asyncio.sleep(CONSTANTS.WS_ORDER_RETRY_DELAY) + continue + if code in CONSTANTS.WS_ORDER_SIGN_IN_CODES or code == "SERVICE_UNAVAILABLE": + return None + return reply + return None + + async def _request(self, ws: WSAssistant, method: str, params: Dict[str, Any]) -> Dict[str, Any]: + async with self._in_flight: + req_id = next(self._ids) + future = asyncio.get_running_loop().create_future() + # Each socket has its own pending map: closing one fails only its own requests. + pending = self._pending + pending[req_id] = future + try: + await ws.send(WSJSONRequest(payload={"method": method, "req_id": req_id, **params})) + return await asyncio.wait_for(future, timeout=CONSTANTS.WS_ORDER_REPLY_TIMEOUT) + finally: + pending.pop(req_id, None) + + # ----- connection ----- + + async def _socket(self) -> Optional[WSAssistant]: + if time.time() < self._unavailable_until: + return None + async with self._lock: + if self._ws is not None and self._reader is not None and not self._reader.done(): + return self._ws + await self._close() + try: + return await self._connect() + except asyncio.CancelledError: + raise + except Exception as e: + self.logger().warning(f"PredictAsiaX order entry socket unavailable ({e}); using REST.") + self._unavailable_until = time.time() + CONSTANTS.WS_ORDER_CONNECT_RETRY_AFTER + await self._close() + return None + + async def _connect(self) -> Optional[WSAssistant]: + rest = await self._api_factory.get_rest_assistant() + response = await rest.execute_request( + url=web_utils.private_rest_url(CONSTANTS.WS_TOKEN_PATH_URL, domain=self._domain), + method=RESTMethod.POST, + data={}, + is_auth_required=True, + throttler_limit_id=CONSTANTS.WS_TOKEN_PATH_URL, + ) + token = (web_utils.response_data(response) or {}).get("token") + if not token: + raise IOError(f"no WebSocket sign-in token in {response}") + ws = await self._api_factory.get_ws_assistant() + self._ws = ws + await ws.connect(ws_url=web_utils.wss_url(self._domain), ping_timeout=CONSTANTS.WS_PING_INTERVAL) + await ws.send(WSJSONRequest(payload={"method": "AUTH", "token": token})) + signed_in = await asyncio.wait_for(self._sign_in(ws), timeout=CONSTANTS.WS_AUTH_TIMEOUT) + entry = signed_in.get("order_entry") or {} + if entry.get("available") is not True: + self._unavailable_until = time.time() + CONSTANTS.WS_ORDER_ENTRY_RETRY_AFTER + self.logger().info(f"PredictAsiaX order entry not available for this key " + f"({entry.get('code')}: {entry.get('message')}); using REST.") + await self._close() + return None + self.limits = entry + self._apply_limits(entry) + # Order replies are all this socket needs. + await ws.send(WSJSONRequest(payload={"method": "UNSUBSCRIBE", "params": CONSTANTS.WS_DEFAULT_CHANNELS})) + self._reader = asyncio.get_running_loop().create_task(self._read(ws, self._pending)) + return ws + + def _apply_limits(self, entry: Dict[str, Any]): + """The account's per-second order and cancel budgets, as reported on sign-in.""" + limits = getattr(self._throttler, "_id_to_limit_map", {}) + pct = getattr(self._throttler, "limits_pct", 1) + for limit_id, key in ((CONSTANTS.WS_PLACE_ORDER_LIMIT_ID, "orders_per_s"), + (CONSTANTS.WS_CANCEL_ORDER_LIMIT_ID, "cancels_per_s")): + rate_limit = limits.get(limit_id) + try: + per_s = float(entry.get(key)) + except (TypeError, ValueError): + continue + if rate_limit is not None and per_s >= 1: + rate_limit.limit = max(1, int(per_s * float(pct))) + + async def _sign_in(self, ws: WSAssistant) -> Dict[str, Any]: + async for response in ws.iter_messages(): + for message in web_utils.decode_ws_frame(response.data): + if message.get("type") == "authenticated": + return message + if message.get("type") == "auth_denied": + raise ConnectionError(f"sign-in refused: {message}") + raise ConnectionError("socket closed before sign-in completed") + + async def _read(self, ws: WSAssistant, pending: Dict[int, asyncio.Future]): + try: + while True: + try: + await asyncio.wait_for(self._dispatch(ws, pending), timeout=CONSTANTS.WS_PING_INTERVAL) + return + except asyncio.TimeoutError: + await ws.send(WSJSONRequest(payload={"type": "ping"})) + except asyncio.CancelledError: + raise + except Exception as e: + self.logger().warning(f"PredictAsiaX order entry socket closed ({e}).") + finally: + self._fail_pending(pending) + + @staticmethod + async def _dispatch(ws: WSAssistant, pending: Dict[int, asyncio.Future]): + async for response in ws.iter_messages(): + for message in web_utils.decode_ws_frame(response.data): + future = pending.get(message.get("req_id")) + if future is not None and not future.done(): + future.set_result(message) + + @staticmethod + def _fail_pending(pending: Dict[int, asyncio.Future]): + for future in list(pending.values()): + if not future.done(): + future.set_exception(ConnectionError("order entry socket closed")) + + async def _close(self): + reader, self._reader = self._reader, None + ws, self._ws = self._ws, None + if reader is not None and not reader.done(): + reader.cancel() + pending, self._pending = self._pending, {} + self._fail_pending(pending) + if ws is not None: + try: + await ws.disconnect() + except Exception: + pass diff --git a/hummingbot/connector/exchange/predictasiax/predictasiax_utils.py b/hummingbot/connector/exchange/predictasiax/predictasiax_utils.py new file mode 100644 index 000000000..8fafbc635 --- /dev/null +++ b/hummingbot/connector/exchange/predictasiax/predictasiax_utils.py @@ -0,0 +1,35 @@ +from decimal import Decimal + +from pydantic import ConfigDict, Field, SecretStr + +from hummingbot.client.config.config_data_types import BaseConnectorConfigMap +from hummingbot.connector.exchange.predictasiax import predictasiax_constants as CONSTANTS +from hummingbot.core.data_type.trade_fee import TradeFeeSchema + +CENTRALIZED = True +EXAMPLE_PAIR = "BTC_200000_HIT_2026_YES-USDT" + +# Resting orders pay no fee. Takers pay at most 0.25% of notional in USDT (the platform fee +# curve is lower away from 50c and with discounts); the ceiling is used for estimates. +DEFAULT_FEES = TradeFeeSchema( + maker_percent_fee_decimal=Decimal("0"), + taker_percent_fee_decimal=CONSTANTS.TAKER_FEE_CEILING, + buy_percent_fee_deducted_from_returns=False, +) + + +class PredictasiaxConfigMap(BaseConnectorConfigMap): + connector: str = CONSTANTS.EXCHANGE_NAME + predictasiax_api_key: SecretStr = Field( + default=..., + json_schema_extra={ + "prompt": lambda cm: "Enter your PredictAsiaX API key (sk_live_...)", + "is_secure": True, + "is_connect_key": True, + "prompt_on_new": True, + } + ) + model_config = ConfigDict(title=CONSTANTS.EXCHANGE_NAME) + + +KEYS = PredictasiaxConfigMap.model_construct() diff --git a/hummingbot/connector/exchange/predictasiax/predictasiax_web_utils.py b/hummingbot/connector/exchange/predictasiax/predictasiax_web_utils.py new file mode 100644 index 000000000..656dd6acf --- /dev/null +++ b/hummingbot/connector/exchange/predictasiax/predictasiax_web_utils.py @@ -0,0 +1,81 @@ +import gzip +import json +from typing import Any, Callable, Dict, List, Optional + +import hummingbot.connector.exchange.predictasiax.predictasiax_constants as CONSTANTS +from hummingbot.connector.time_synchronizer import TimeSynchronizer +from hummingbot.core.api_throttler.async_throttler import AsyncThrottler +from hummingbot.core.web_assistant.auth import AuthBase +from hummingbot.core.web_assistant.connections.data_types import RESTMethod +from hummingbot.core.web_assistant.web_assistants_factory import WebAssistantsFactory + + +def public_rest_url(path_url: str, domain: str = CONSTANTS.DEFAULT_DOMAIN) -> str: + return CONSTANTS.REST_URL + path_url + + +def private_rest_url(path_url: str, domain: str = CONSTANTS.DEFAULT_DOMAIN) -> str: + return CONSTANTS.REST_URL + path_url + + +def market_data_url(path_url: str, domain: str = CONSTANTS.DEFAULT_DOMAIN) -> str: + return CONSTANTS.MARKET_DATA_URL + path_url + + +def wss_url(domain: str = CONSTANTS.DEFAULT_DOMAIN) -> str: + return CONSTANTS.WSS_URL + + +def response_data(response: Any) -> Any: + """Most responses are wrapped as {"data": ..., "meta": {...}}; return the payload.""" + if isinstance(response, dict) and "data" in response: + return response["data"] + return response + + +def decode_ws_frame(data: Any) -> List[Dict[str, Any]]: + """ + WebSocket frames are JSON text, or gzip-compressed JSON in binary frames. A frame holds one + message or a list of messages. Returns the messages that are JSON objects. + """ + if isinstance(data, (bytes, bytearray)): + try: + data = json.loads(gzip.decompress(bytes(data))) + except Exception: + return [] + elif isinstance(data, str): + try: + data = json.loads(data) + except Exception: + return [] + items = data if isinstance(data, list) else [data] + return [item for item in items if isinstance(item, dict)] + + +def build_api_factory( + throttler: Optional[AsyncThrottler] = None, + time_synchronizer: Optional[TimeSynchronizer] = None, + time_provider: Optional[Callable] = None, + auth: Optional[AuthBase] = None, +) -> WebAssistantsFactory: + throttler = throttler or create_throttler() + return WebAssistantsFactory(throttler=throttler, auth=auth) + + +def create_throttler() -> AsyncThrottler: + return AsyncThrottler(CONSTANTS.RATE_LIMITS) + + +async def get_current_server_time( + throttler: Optional[AsyncThrottler] = None, + domain: str = CONSTANTS.DEFAULT_DOMAIN, +) -> float: + throttler = throttler or create_throttler() + api_factory = build_api_factory(throttler=throttler) + rest_assistant = await api_factory.get_rest_assistant() + response: Dict[str, Any] = await rest_assistant.execute_request( + url=public_rest_url(path_url=CONSTANTS.HEALTH_PATH_URL, domain=domain), + method=RESTMethod.GET, + throttler_limit_id=CONSTANTS.HEALTH_PATH_URL, + ) + return float(response["meta"]["ts_ms"]) diff --git a/test/hummingbot/connector/exchange/predictasiax/__init__.py b/test/hummingbot/connector/exchange/predictasiax/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_api_order_book_data_source.py b/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_api_order_book_data_source.py new file mode 100644 index 000000000..7a1d2326f --- /dev/null +++ b/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_api_order_book_data_source.py @@ -0,0 +1,365 @@ +import asyncio +import gzip +import json +import re +from test.isolated_asyncio_wrapper_test_case import IsolatedAsyncioWrapperTestCase +from unittest.mock import AsyncMock, MagicMock, patch + +import aiohttp +from aioresponses import aioresponses +from bidict import bidict + +from hummingbot.connector.exchange.predictasiax import ( + predictasiax_constants as CONSTANTS, + predictasiax_web_utils as web_utils, +) +from hummingbot.connector.exchange.predictasiax.predictasiax_api_order_book_data_source import ( + PredictasiaxAPIOrderBookDataSource, + outcome_levels, +) +from hummingbot.connector.exchange.predictasiax.predictasiax_exchange import PredictasiaxExchange +from hummingbot.connector.test_support.network_mocking_assistant import NetworkMockingAssistant +from hummingbot.core.data_type.common import TradeType +from hummingbot.core.data_type.order_book_message import OrderBookMessageType + +MARKET = "btc-200k-2026" +YES_PAIR = "BTC_200K_2026_YES-USDT" +NO_PAIR = "BTC_200K_2026_NO-USDT" +OTHER_PAIR = "OTHER_MARKET_YES-USDT" +EPOCH = 1796286334322 +BOOK_URL = web_utils.market_data_url(CONSTANTS.MARKET_BOOK_PATH_URL.format(MARKET)) + + +def snapshot(seq: int = 7, epoch: int = EPOCH, market: str = MARKET): + return { + "type": "book_snapshot", "channel": f"book:{market}", "market": market, "outcome": 0, + "seq": seq, "epoch": epoch, "ts": 1796290611673, "tick": "0.01", + "bids": [["0.07", "145"], ["0.06", "165"]], + "asks": [["0.09", "127"], ["0.10", "117"]], + "last_trade": {"price": "0.0800", "side": "", "size": "12", "ts": 1796289569963}, + } + + +def delta(seq: int, changes, market: str = MARKET): + return {"type": "book_delta", "channel": f"book:{market}", "market": market, "outcome": 0, "seq": seq, + "ts": 1796290612000, "changes": changes, "best_bid": "0.07", "best_ask": "0.09"} + + +def last_trade(side: str = "buy", price: str = "0.0900", size: str = "13", market: str = MARKET): + return {"type": "last_trade", "channel": f"book:{market}", "market": market, "outcome": 0, + "price": price, "size": size, "side": side, "ts": 1796290613000} + + +class OutcomeLevelsTests(IsolatedAsyncioWrapperTestCase): + def test_yes_levels_are_the_consolidated_book(self): + bids, asks = outcome_levels([["0.06", "165"], ["0.07", "145"]], [["0.10", "117"], ["0.09", "127"]], "YES") + self.assertEqual([["0.07", "145"], ["0.06", "165"]], bids) + self.assertEqual([["0.09", "127"], ["0.10", "117"]], asks) + + def test_no_levels_are_the_complement(self): + bids, asks = outcome_levels([["0.07", "145"], ["0.06", "165"]], [["0.09", "127"], ["0.10", "117"]], "NO") + self.assertEqual([["0.91", "127"], ["0.90", "117"]], bids) + self.assertEqual([["0.93", "145"], ["0.94", "165"]], asks) + + def test_invalid_levels_are_ignored_and_removed_levels_kept(self): + bids, asks = outcome_levels([["x", "1"], ["1.2", "3"], ["0.4", "-1"], ["0.4", "0"], ["0.3"]], None, "YES") + self.assertEqual([["0.4", "0"]], bids) + self.assertEqual([], asks) + + +class PredictasiaxAPIOrderBookDataSourceTests(IsolatedAsyncioWrapperTestCase): + level = 0 + + async def asyncSetUp(self) -> None: + await super().asyncSetUp() + self.log_records = [] + self.mocking_assistant = NetworkMockingAssistant() + await self.mocking_assistant.async_init() + self.connector = PredictasiaxExchange( + predictasiax_api_key="sk_live_test", # noqa: mock + trading_pairs=[YES_PAIR, NO_PAIR], + trading_required=False, + ) + self.data_source = PredictasiaxAPIOrderBookDataSource( + trading_pairs=[YES_PAIR, NO_PAIR], + connector=self.connector, + api_factory=self.connector._web_assistants_factory, + ) + self.data_source.logger().setLevel(1) + self.data_source.logger().addHandler(self) + self.connector._set_trading_pair_symbol_map(bidict({ + f"{MARKET}:YES": YES_PAIR, f"{MARKET}:NO": NO_PAIR, + "other-market:YES": OTHER_PAIR, "other-market:NO": "OTHER_MARKET_NO-USDT", + })) + self.listening_task = None + self.ws = AsyncMock() + + def tearDown(self) -> None: + self.listening_task and self.listening_task.cancel() + super().tearDown() + + def handle(self, record): + self.log_records.append(record) + + def _is_logged(self, level: str, message: str) -> bool: + return any(r.levelname == level and message in r.getMessage() for r in self.log_records) + + def _sent(self): + return [c.args[0].payload for c in self.ws.send.call_args_list] + + @staticmethod + def _drain(queue: asyncio.Queue): + out = [] + while not queue.empty(): + out.append(queue.get_nowait()) + return out + + # ----- REST snapshot + + @aioresponses() + async def test_order_book_snapshot(self, mock_api): + mock_api.get(BOOK_URL, body=json.dumps(snapshot(seq=7))) + message = await self.data_source._order_book_snapshot(NO_PAIR) + self.assertEqual(OrderBookMessageType.SNAPSHOT, message.type) + self.assertEqual(NO_PAIR, message.trading_pair) + self.assertEqual(EPOCH * CONSTANTS.BOOK_EPOCH_SCALE + 7, message.update_id) + self.assertEqual(0.91, message.bids[0].price) + self.assertEqual(127, message.bids[0].amount) + self.assertEqual(0.93, message.asks[0].price) + + @aioresponses() + async def test_order_book_snapshot_unavailable(self, mock_api): + mock_api.get(BOOK_URL, body=json.dumps({"ok": False, "error": {"code": "UNAVAILABLE"}})) + with self.assertRaises(IOError): + await self.data_source._order_book_snapshot(YES_PAIR) + + @aioresponses() + async def test_get_new_order_book(self, mock_api): + mock_api.get(BOOK_URL, body=json.dumps(snapshot())) + order_book = await self.data_source.get_new_order_book(YES_PAIR) + self.assertEqual(0.07, order_book.get_price(False)) + self.assertEqual(0.09, order_book.get_price(True)) + + @aioresponses() + async def test_get_last_traded_prices(self, mock_api): + url = re.compile(r"^https://api\.predictasiax\.com/v1/markets\?") + mock_api.get(url, body=json.dumps({"data": {"markets": [ + {"id": MARKET, "prices": {"yes": 0.08, "no": 0.92}, "status": "open"}, + ], "page": {"next_cursor": None}}})) + prices = await self.data_source.get_last_traded_prices([YES_PAIR, NO_PAIR, OTHER_PAIR]) + self.assertEqual({YES_PAIR: 0.08, NO_PAIR: 0.92}, prices) + + # ----- subscriptions + + async def test_subscribe_channels_subscribes_each_market_once(self): + await self.data_source._subscribe_channels(self.ws) + self.assertEqual([ + {"method": "UNSUBSCRIBE", "params": CONSTANTS.WS_DEFAULT_CHANNELS}, + {"method": "SUBSCRIBE", "params": [f"book:{MARKET}"]}, + ], self._sent()) + self.assertTrue(self._is_logged("INFO", "Subscribed to public order book channels")) + + async def test_subscribe_channels_without_pairs(self): + self.data_source._trading_pairs = [] + await self.data_source._subscribe_channels(self.ws) + self.assertEqual([{"method": "UNSUBSCRIBE", "params": CONSTANTS.WS_DEFAULT_CHANNELS}], self._sent()) + + async def test_subscribe_channels_raises_and_logs(self): + self.ws.send.side_effect = Exception("boom") + with self.assertRaises(Exception): + await self.data_source._subscribe_channels(self.ws) + self.assertTrue(self._is_logged("ERROR", "Unexpected error occurred subscribing")) + self.ws.send.side_effect = asyncio.CancelledError + with self.assertRaises(asyncio.CancelledError): + await self.data_source._subscribe_channels(self.ws) + + async def test_subscribe_and_unsubscribe_trading_pair(self): + await self.data_source._subscribe_channels(self.ws) + self.ws.send.reset_mock() + self.assertTrue(await self.data_source.subscribe_to_trading_pair(OTHER_PAIR)) + self.assertIn(OTHER_PAIR, self.data_source._trading_pairs) + self.assertTrue(await self.data_source.subscribe_to_trading_pair("OTHER_MARKET_NO-USDT")) + self.assertTrue(await self.data_source.subscribe_to_trading_pair(OTHER_PAIR)) + self.assertTrue(self._is_logged("WARNING", "already subscribed")) + self.assertEqual([ + {"method": "SUBSCRIBE", "params": ["book:other-market"]}, + {"method": "BOOK_SNAPSHOT", "params": ["book:other-market"]}, + ], self._sent()) + + self.ws.send.reset_mock() + self.assertTrue(await self.data_source.unsubscribe_from_trading_pair(OTHER_PAIR)) + self.assertEqual([], self._sent()) # the NO pair of that market is still tracked + self.assertTrue(await self.data_source.unsubscribe_from_trading_pair("OTHER_MARKET_NO-USDT")) + self.assertEqual([{"method": "UNSUBSCRIBE", "params": ["book:other-market"]}], self._sent()) + self.assertNotIn(OTHER_PAIR, self.data_source._trading_pairs) + self.assertTrue(await self.data_source.unsubscribe_from_trading_pair(OTHER_PAIR)) + self.assertTrue(self._is_logged("WARNING", "not subscribed")) + + async def test_subscribe_before_connection_only_tracks_the_pair(self): + self.assertTrue(await self.data_source.subscribe_to_trading_pair(OTHER_PAIR)) + self.assertIn(OTHER_PAIR, self.data_source._trading_pairs) + + async def test_subscribe_and_unsubscribe_errors(self): + await self.data_source._subscribe_channels(self.ws) + self.ws.send.side_effect = Exception("boom") + self.assertFalse(await self.data_source.subscribe_to_trading_pair(OTHER_PAIR)) + self.assertTrue(self._is_logged("ERROR", f"Error subscribing to the order book of {OTHER_PAIR}")) + self.assertFalse(await self.data_source.unsubscribe_from_trading_pair(OTHER_PAIR)) + self.assertTrue(self._is_logged("ERROR", f"Error unsubscribing from the order book of {OTHER_PAIR}")) + self.ws.send.side_effect = asyncio.CancelledError + with self.assertRaises(asyncio.CancelledError): + await self.data_source.subscribe_to_trading_pair("OTHER_MARKET_NO-USDT") + self.data_source.add_trading_pair(OTHER_PAIR) + self.data_source.remove_trading_pair("OTHER_MARKET_NO-USDT") + with self.assertRaises(asyncio.CancelledError): + await self.data_source.unsubscribe_from_trading_pair(OTHER_PAIR) + + async def test_stream_interruption_forgets_book_state(self): + await self.data_source._subscribe_channels(self.ws) + self.data_source._book_seq[MARKET] = (EPOCH, 3) + await self.data_source._on_order_stream_interruption(self.ws) + self.assertEqual({}, self.data_source._book_seq) + self.assertIsNone(self.data_source._ws_assistant) + self.ws.disconnect.assert_awaited() + + def test_channel_originating_message(self): + ds = self.data_source + self.assertEqual(ds._snapshot_messages_queue_key, ds._channel_originating_message(snapshot())) + self.assertEqual(ds._diff_messages_queue_key, ds._channel_originating_message(delta(8, []))) + self.assertEqual(ds._trade_messages_queue_key, ds._channel_originating_message(last_trade())) + self.assertEqual("", ds._channel_originating_message(dict(snapshot(), outcome=1))) + self.assertEqual("", ds._channel_originating_message({"type": "subscribed"})) + self.assertEqual("", ds._channel_originating_message({"type": "book_error", "code": "CAPACITY"})) + self.assertTrue(self._is_logged("ERROR", "Error in WS stream")) + + @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) + async def test_listen_for_subscriptions_routes_text_and_gzip_frames(self, ws_connect_mock): + ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() + self.mocking_assistant.add_websocket_aiohttp_message(ws_connect_mock.return_value, json.dumps(snapshot())) + self.mocking_assistant.add_websocket_aiohttp_message( + ws_connect_mock.return_value, + gzip.compress(json.dumps([delta(8, []), last_trade(), {"type": "fast_tick"}]).encode()), + message_type=aiohttp.WSMsgType.BINARY) + self.listening_task = self.local_event_loop.create_task(self.data_source.listen_for_subscriptions()) + await self.mocking_assistant.run_until_all_aiohttp_messages_delivered(ws_connect_mock.return_value) + + sent = self.mocking_assistant.json_messages_sent_through_websocket(ws_connect_mock.return_value) + self.assertEqual({"method": "UNSUBSCRIBE", "params": CONSTANTS.WS_DEFAULT_CHANNELS}, sent[0]) + self.assertEqual({"method": "SUBSCRIBE", "params": [f"book:{MARKET}"]}, sent[1]) + queues = self.data_source._message_queue + self.assertEqual(1, queues[self.data_source._snapshot_messages_queue_key].qsize()) + self.assertEqual(1, queues[self.data_source._diff_messages_queue_key].qsize()) + self.assertEqual(1, queues[self.data_source._trade_messages_queue_key].qsize()) + + @patch.object(CONSTANTS, "WS_PING_INTERVAL", 0.05) + @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) + async def test_quiet_stream_sends_application_ping(self, ws_connect_mock): + ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() + self.listening_task = self.local_event_loop.create_task(self.data_source.listen_for_subscriptions()) + for _ in range(40): + await asyncio.sleep(0.02) + sent = self.mocking_assistant.json_messages_sent_through_websocket(ws_connect_mock.return_value) + if {"type": "ping"} in sent: + break + self.assertIn({"type": "ping"}, sent) + + async def test_process_websocket_messages_returns_when_stream_ends(self): + ws = MagicMock() + + async def no_messages(): + return + yield # pragma: no cover + + ws.iter_messages = no_messages + await self.data_source._process_websocket_messages(ws) + + # ----- book messages + + async def test_snapshot_feeds_both_pairs(self): + queue = asyncio.Queue() + await self.data_source._parse_order_book_snapshot_message(snapshot(seq=7), queue) + yes, no = self._drain(queue) + self.assertEqual((YES_PAIR, OrderBookMessageType.SNAPSHOT), (yes.trading_pair, yes.type)) + self.assertEqual(EPOCH * CONSTANTS.BOOK_EPOCH_SCALE + 7, yes.update_id) + self.assertEqual(0.07, yes.bids[0].price) + self.assertEqual(0.09, yes.asks[0].price) + self.assertEqual(NO_PAIR, no.trading_pair) + self.assertEqual(0.91, no.bids[0].price) + self.assertEqual(0.93, no.asks[0].price) + self.assertEqual(1796290611.673, yes.timestamp) + self.assertEqual((EPOCH, 7), self.data_source._book_seq[MARKET]) + + async def test_snapshot_without_market_is_ignored(self): + queue = asyncio.Queue() + await self.data_source._parse_order_book_snapshot_message(dict(snapshot(), market=""), queue) + self.assertTrue(queue.empty()) + + async def test_contiguous_delta_feeds_both_pairs(self): + queue = asyncio.Queue() + await self.data_source._parse_order_book_snapshot_message(snapshot(seq=7), queue) + self._drain(queue) + await self.data_source._parse_order_book_diff_message( + delta(8, [["bid", "0.08", "20"], ["ask", "0.09", "0"], ["x", "0.5", "1"], ["bid"]]), queue) + yes, no = self._drain(queue) + self.assertEqual(OrderBookMessageType.DIFF, yes.type) + self.assertEqual(EPOCH * CONSTANTS.BOOK_EPOCH_SCALE + 8, yes.update_id) + self.assertEqual([(0.08, 20.0)], [(r.price, r.amount) for r in yes.bids]) + self.assertEqual([(0.09, 0.0)], [(r.price, r.amount) for r in yes.asks]) + self.assertEqual([(0.91, 0.0)], [(r.price, r.amount) for r in no.bids]) + self.assertEqual([(0.92, 20.0)], [(r.price, r.amount) for r in no.asks]) + self.assertEqual((EPOCH, 8), self.data_source._book_seq[MARKET]) + + async def test_delta_before_snapshot_and_stale_delta_are_ignored(self): + queue = asyncio.Queue() + await self.data_source._parse_order_book_diff_message(delta(8, [["bid", "0.08", "20"]]), queue) + self.assertTrue(queue.empty()) + await self.data_source._parse_order_book_snapshot_message(snapshot(seq=7), queue) + self._drain(queue) + await self.data_source._parse_order_book_diff_message(delta(7, [["bid", "0.08", "20"]]), queue) + self.assertTrue(queue.empty()) + + async def test_sequence_gap_requests_a_fresh_snapshot(self): + await self.data_source._subscribe_channels(self.ws) + self.ws.send.reset_mock() + queue = asyncio.Queue() + await self.data_source._parse_order_book_snapshot_message(snapshot(seq=7), queue) + self._drain(queue) + await self.data_source._parse_order_book_diff_message(delta(9, [["bid", "0.08", "20"]]), queue) + self.assertTrue(queue.empty()) + self.assertEqual([{"method": "BOOK_SNAPSHOT", "params": [f"book:{MARKET}"]}], self._sent()) + self.assertTrue(self._is_logged("INFO", "skipped from seq 7 to 9")) + await self.data_source._parse_order_book_diff_message(delta(10, [["bid", "0.08", "20"]]), queue) + self.assertTrue(queue.empty()) + await self.data_source._parse_order_book_snapshot_message(snapshot(seq=10, epoch=EPOCH + 5), queue) + self.assertEqual(2, len(self._drain(queue))) + + # ----- trades + + async def test_taker_buy_of_yes_is_a_sell_of_no(self): + queue = asyncio.Queue() + await self.data_source._parse_trade_message(last_trade("buy", "0.0900", "13"), queue) + yes, no = self._drain(queue) + self.assertEqual((YES_PAIR, float(TradeType.BUY.value), 0.09, 13.0), + (yes.trading_pair, yes.content["trade_type"], float(yes.content["price"]), float(yes.content["amount"]))) + self.assertEqual((NO_PAIR, float(TradeType.SELL.value), 0.91), + (no.trading_pair, no.content["trade_type"], float(no.content["price"]))) + self.assertEqual(yes.trade_id, no.trade_id) + self.assertEqual(1796290613.0, yes.timestamp) + + async def test_taker_sell_of_yes_is_a_buy_of_no(self): + queue = asyncio.Queue() + await self.data_source._parse_trade_message(last_trade("sell", "0.0700", "2"), queue) + yes, no = self._drain(queue) + self.assertEqual(float(TradeType.SELL.value), yes.content["trade_type"]) + self.assertEqual(float(TradeType.BUY.value), no.content["trade_type"]) + await self.data_source._parse_trade_message(last_trade("sell", "0.0700", "2"), queue) + again, _ = self._drain(queue) + self.assertNotEqual(yes.trade_id, again.trade_id) + + async def test_trades_without_direction_or_price_are_ignored(self): + queue = asyncio.Queue() + await self.data_source._parse_trade_message(last_trade(""), queue) + await self.data_source._parse_trade_message(last_trade("buy", "x"), queue) + await self.data_source._parse_trade_message(dict(last_trade(), market=""), queue) + await self.data_source._parse_trade_message(last_trade(market="unknown-market"), queue) + self.assertTrue(queue.empty()) diff --git a/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_auth.py b/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_auth.py new file mode 100644 index 000000000..494746cdc --- /dev/null +++ b/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_auth.py @@ -0,0 +1,26 @@ +from test.isolated_asyncio_wrapper_test_case import IsolatedAsyncioWrapperTestCase + +from hummingbot.connector.exchange.predictasiax.predictasiax_auth import PredictasiaxAuth +from hummingbot.core.web_assistant.connections.data_types import RESTMethod, RESTRequest, WSJSONRequest + + +class PredictasiaxAuthTests(IsolatedAsyncioWrapperTestCase): + async def test_rest_authenticate_adds_bearer_token(self): + auth = PredictasiaxAuth(api_key="sk_live_test") # noqa: mock + request = RESTRequest(method=RESTMethod.GET, url="https://api.predictasiax.com/v1/balance", + headers={"X-Other": "1"}, is_auth_required=True) + authenticated = await auth.rest_authenticate(request) + self.assertEqual("Bearer sk_live_test", authenticated.headers["Authorization"]) + self.assertEqual("1", authenticated.headers["X-Other"]) + + async def test_rest_authenticate_without_headers(self): + auth = PredictasiaxAuth(api_key="sk_live_test") # noqa: mock + request = RESTRequest(method=RESTMethod.POST, url="https://api.predictasiax.com/v1/orders", + is_auth_required=True) + authenticated = await auth.rest_authenticate(request) + self.assertEqual({"Authorization": "Bearer sk_live_test"}, authenticated.headers) + + async def test_ws_authenticate_passes_request_through(self): + auth = PredictasiaxAuth(api_key="sk_live_test") # noqa: mock + request = WSJSONRequest(payload={"method": "AUTH", "token": "wst_x"}) + self.assertIs(request, await auth.ws_authenticate(request)) diff --git a/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_exchange.py b/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_exchange.py new file mode 100644 index 000000000..0481ad13e --- /dev/null +++ b/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_exchange.py @@ -0,0 +1,639 @@ +import asyncio +import json +import re +from decimal import Decimal +from test.isolated_asyncio_wrapper_test_case import IsolatedAsyncioWrapperTestCase +from unittest.mock import AsyncMock, MagicMock, patch + +from aioresponses import aioresponses +from bidict import bidict + +from hummingbot.connector.exchange.predictasiax import ( + predictasiax_constants as CONSTANTS, + predictasiax_web_utils as web_utils, +) +from hummingbot.connector.exchange.predictasiax.predictasiax_exchange import PredictasiaxExchange +from hummingbot.connector.trading_rule import TradingRule +from hummingbot.core.data_type.common import OrderType, TradeType +from hummingbot.core.data_type.in_flight_order import OrderState +from hummingbot.core.data_type.trade_fee import AddedToCostTradeFee + +MARKET = "btc-200k-2026" +YES_PAIR = "BTC_200K_2026_YES-USDT" +NO_PAIR = "BTC_200K_2026_NO-USDT" +ORDERS_URL = re.compile(r"^https://api\.predictasiax\.com/v1/orders(\?.*)?$") +MARKETS_URL = re.compile(r"^https://api\.predictasiax\.com/v1/markets\?.*$") +FILLS_URL = re.compile(r"^https://api\.predictasiax\.com/v1/fills\?.*$") +EXCHANGE_ORDER_ID = "6f1c2a52-4c6e-4a43-9f2f-0d1a1e7b2c11" + + +def env(data): + return json.dumps({"data": data, "meta": {"ts_ms": 1}}) + + +class PredictasiaxExchangeTests(IsolatedAsyncioWrapperTestCase): + level = 0 + + async def asyncSetUp(self) -> None: + await super().asyncSetUp() + self.log_records = [] + self.exchange = PredictasiaxExchange( + predictasiax_api_key="sk_live_test", # noqa: mock + trading_pairs=[YES_PAIR, NO_PAIR], + ) + self.exchange.logger().setLevel(1) + self.exchange.logger().addHandler(self) + # REST order entry; the WebSocket path has its own tests below. + self.ws_entry = self.exchange._order_entry + self.exchange._order_entry = None + self.exchange._set_trading_pair_symbol_map(bidict({f"{MARKET}:YES": YES_PAIR, f"{MARKET}:NO": NO_PAIR})) + for pair in (YES_PAIR, NO_PAIR): + self.exchange._trading_rules[pair] = TradingRule( + pair, min_order_size=CONSTANTS.SIZE_QUANTUM, min_price_increment=CONSTANTS.FINE_TICK, + min_base_amount_increment=CONSTANTS.SIZE_QUANTUM, min_notional_size=CONSTANTS.SIZE_QUANTUM) + + def handle(self, record): + self.log_records.append(record) + + def _is_logged(self, level: str, message: str) -> bool: + return any(r.levelname == level and message in r.getMessage() for r in self.log_records) + + def _track(self, client_id="PAXB1", trade_type=TradeType.BUY, price="0.42", amount="10", + exchange_order_id=EXCHANGE_ORDER_ID, order_type=OrderType.LIMIT, pair=YES_PAIR): + self.exchange.start_tracking_order( + order_id=client_id, exchange_order_id=exchange_order_id, trading_pair=pair, + trade_type=trade_type, price=Decimal(price), amount=Decimal(amount), order_type=order_type) + order = self.exchange.in_flight_orders[client_id] + order.creation_timestamp = 1796278000.0 + return order + + @staticmethod + def _sent_json(mock_api, method="POST", url_part="/v1/orders"): + for (m, url), calls in mock_api.requests.items(): + if m == method and url_part in str(url): + return calls[-1].kwargs + raise AssertionError("request not sent") + + # ----- properties ----- + + def test_properties(self): + ex = self.exchange + self.assertEqual("predictasiax", ex.name) + self.assertEqual(CONSTANTS.DEFAULT_DOMAIN, ex.domain) + self.assertEqual(CONSTANTS.MAX_ORDER_ID_LEN, ex.client_order_id_max_length) + self.assertEqual("PAX", ex.client_order_id_prefix) + self.assertEqual(CONSTANTS.MARKETS_PATH_URL, ex.trading_rules_request_path) + self.assertEqual(CONSTANTS.MARKETS_PATH_URL, ex.trading_pairs_request_path) + self.assertEqual(CONSTANTS.HEALTH_PATH_URL, ex.check_network_request_path) + self.assertEqual([YES_PAIR, NO_PAIR], ex.trading_pairs) + self.assertTrue(ex.is_cancel_request_in_exchange_synchronous) + self.assertTrue(ex.is_trading_required) + self.assertEqual(CONSTANTS.RATE_LIMITS, ex.rate_limits_rules) + self.assertEqual([OrderType.LIMIT, OrderType.LIMIT_MAKER, OrderType.MARKET], ex.supported_order_types()) + self.assertEqual("sk_live_test", ex.authenticator.api_key) + self.assertFalse(ex._is_request_exception_related_to_time_synchronizer(Exception("x"))) + self.assertTrue(ex._is_order_not_found_during_status_update_error(IOError("ORDER_NOT_FOUND: x"))) + self.assertTrue(ex._is_order_not_found_during_cancelation_error(IOError("ORDER_NOT_FOUND: x"))) + self.assertFalse(ex._is_order_not_found_during_cancelation_error(IOError("timeout"))) + self.assertEqual("SEED_POLITICS_6F5_YES", ex.base_asset_for("seed_politics-6f5", "YES")) + + async def test_noop_updates(self): + await self.exchange._update_time_synchronizer() + + # ----- fees ----- + + @aioresponses() + async def test_update_trading_fees_reads_the_published_curve(self, mock_api): + url = re.compile(r"^https://api\.predictasiax\.com/v1/fees/estimate\?.*$") + mock_api.get(url, body=env({"paf": {"base_bps": "30", "floor_bps": "5", "ceiling_bps": "40"}})) + await self.exchange._update_trading_fees() + self.assertEqual((Decimal("30"), Decimal("5"), Decimal("40")), self.exchange._paf_bps) + params = self._sent_json(mock_api, method="GET", url_part="/v1/fees/estimate")["params"] + self.assertEqual(MARKET, params["market_id"]) + mock_api.get(url, body=env({"paf": {"base_bps": "20"}})) + await self.exchange._update_trading_fees() + self.assertEqual((Decimal("30"), Decimal("5"), Decimal("40")), self.exchange._paf_bps) + self.assertTrue(self._is_logged("WARNING", "Could not read the platform fee curve")) + mock_api.get(url, body=env({"paf": {"base_bps": "20", "floor_bps": "9", "ceiling_bps": "8"}})) + await self.exchange._update_trading_fees() + self.assertEqual((Decimal("30"), Decimal("5"), Decimal("40")), self.exchange._paf_bps) + + async def test_update_trading_fees_without_markets(self): + self.exchange._set_trading_pair_symbol_map(bidict()) + with patch.object(self.exchange, "_initialize_trading_pair_symbol_map", return_value=None): + await self.exchange._update_trading_fees() + self.assertEqual((CONSTANTS.PAF_BASE_BPS, CONSTANTS.PAF_FLOOR_BPS, CONSTANTS.PAF_CEILING_BPS), + self.exchange._paf_bps) + + def test_taker_fee_rate_follows_the_curve(self): + rate = self.exchange.taker_fee_rate + self.assertEqual(Decimal("0.002"), rate(Decimal("0.5"))) + self.assertEqual(Decimal("0.0008"), rate(Decimal("0.09"))) # floor + self.assertEqual(Decimal("0.0004"), rate(Decimal("0.09"), is_pair_fill=True)) # fill between two buyers pays half + self.assertEqual(Decimal("0.0019352"), rate(Decimal("0.41"))) + self.assertEqual(CONSTANTS.TAKER_FEE_CEILING, rate(Decimal("NaN"))) + self.assertEqual(CONSTANTS.TAKER_FEE_CEILING, rate(Decimal("1"))) + self.exchange._paf_bps = (Decimal("200"), Decimal("8"), Decimal("25")) + self.assertEqual(Decimal("0.0025"), rate(Decimal("0.5"))) # ceiling + + def test_price_quantization_follows_tick_grid(self): + q = self.exchange.quantize_order_price + self.assertEqual(Decimal("0.039"), q(YES_PAIR, Decimal("0.0395"))) + self.assertEqual(Decimal("0.04"), q(YES_PAIR, Decimal("0.045"))) + self.assertEqual(Decimal("0.55"), q(YES_PAIR, Decimal("0.5555"))) + self.assertEqual(Decimal("0.96"), q(YES_PAIR, Decimal("0.9605"))) + self.assertEqual(Decimal("0.965"), q(YES_PAIR, Decimal("0.965"))) + self.assertEqual(Decimal("0.001"), q(YES_PAIR, Decimal("0.0001"))) + self.assertEqual(Decimal("0.999"), q(YES_PAIR, Decimal("0.9999"))) + self.assertTrue(q(YES_PAIR, Decimal("NaN")).is_nan()) + + def test_get_fee(self): + fee = self.exchange._get_fee("BTC_200K_2026_YES", "USDT", OrderType.LIMIT, TradeType.BUY, + Decimal("10"), Decimal("0.5"), is_maker=False) + self.assertEqual(Decimal("0.002"), fee.percent) + fee = self.exchange._get_fee("BTC_200K_2026_YES", "USDT", OrderType.MARKET, TradeType.SELL, + Decimal("10"), Decimal("NaN")) + self.assertEqual(CONSTANTS.TAKER_FEE_CEILING, fee.percent) + self.assertFalse(isinstance(fee, AddedToCostTradeFee)) + fee = self.exchange._get_fee("BTC_200K_2026_YES", "USDT", OrderType.LIMIT_MAKER, TradeType.BUY, + Decimal("10"), Decimal("0.5")) + self.assertEqual(Decimal("0"), fee.percent) + + # ----- markets ----- + + @aioresponses() + async def test_markets_paginate_and_map_to_pairs(self, mock_api): + mock_api.get(MARKETS_URL, body=env({"markets": [ + {"id": MARKET, "status": "open"}, {"id": "btc_200k_2026", "status": "open"}, + ], "page": {"next_cursor": "c2"}})) + mock_api.get(MARKETS_URL, body=env({"markets": [ + {"id": "old-market", "status": "settled"}, {"id": ""}, + ], "page": {"next_cursor": None}})) + info = await self.exchange._make_trading_pairs_request() + self.assertEqual(4, len(info["markets"])) + self.exchange._initialize_trading_pair_symbols_from_exchange_info(info) + mapping = await self.exchange.trading_pair_symbol_map() + self.assertEqual(YES_PAIR, mapping[f"{MARKET}:YES"]) + self.assertNotIn("btc_200k_2026:YES", mapping) + self.assertTrue(self._is_logged("WARNING", "already used by")) + self.assertEqual(("old-market", "NO"), await self.exchange.market_and_outcome("OLD_MARKET_NO-USDT")) + rules = await self.exchange._format_trading_rules(info) + self.assertEqual({YES_PAIR, NO_PAIR}, {r.trading_pair for r in rules}) + self.assertEqual(CONSTANTS.FINE_TICK, rules[0].min_price_increment) + cursors = [c.kwargs["params"].get("cursor") for calls in mock_api.requests.values() for c in calls] + self.assertEqual([None, "c2"], cursors) + + @aioresponses() + async def test_trading_rules_request(self, mock_api): + mock_api.get(MARKETS_URL, body=env({"markets": [{"id": MARKET, "status": "open"}], "page": {}})) + self.assertEqual({"markets": [{"id": MARKET, "status": "open"}]}, + await self.exchange._make_trading_rules_request()) + + @aioresponses() + async def test_network_check(self, mock_api): + mock_api.get(web_utils.public_rest_url(CONSTANTS.HEALTH_PATH_URL), body=env({"status": "ok"})) + await self.exchange._make_network_check_request() + + # ----- placing orders ----- + + @aioresponses() + async def test_place_limit_order_and_process_taker_fills(self, mock_api): + mock_api.post(ORDERS_URL, body=json.dumps({"ok": True, "data": { + "ok": True, "status": "PARTIAL", "order_id": EXCHANGE_ORDER_ID, "resting_size": 4, + "fills": [{"maker_id": "m1", "size": 5, "price": "0.41", "trade_id": "t1"}], + "mint_fills": [{"counterparty_id": "c1", "size": 1, "price": "0.42", "trade_id": "t2"}, + {"counterparty_id": "c2", "size": 0, "price": "0.42", "trade_id": "t3"}], + }, "attribution": {}})) + order = self._track(exchange_order_id=None) + await self.exchange._place_order_and_process_update(order) + await asyncio.sleep(0.01) + sent = self._sent_json(mock_api) + self.assertEqual("PAXB1", sent["headers"]["Idempotency-Key"]) + self.assertEqual({"market_id": MARKET, "side": "yes", "action": "buy", "size": "10", + "client_order_id": "PAXB1", "order_type": "limit", "price": "0.42"}, + json.loads(sent["data"])) + self.assertEqual(EXCHANGE_ORDER_ID, order.exchange_order_id) + self.assertEqual(Decimal("6"), order.executed_amount_base) + self.assertEqual(OrderState.PARTIALLY_FILLED, order.current_state) + fill = order.order_fills["t1"] + self.assertEqual(Decimal("0.41"), fill.fill_price) + self.assertEqual([("USDT", Decimal("2.05") * Decimal("0.0019352"))], + [(f.token, f.amount) for f in fill.fee.flat_fees]) + pair_fill = order.order_fills["t2"] + self.assertEqual([("USDT", Decimal("0.42") * self.exchange.taker_fee_rate(Decimal("0.42")) / 2)], + [(f.token, f.amount) for f in pair_fill.fee.flat_fees]) + + @aioresponses() + async def test_place_post_only_sell_on_no(self, mock_api): + mock_api.post(ORDERS_URL, body=json.dumps({"ok": True, "data": { + "ok": True, "status": "OPEN", "order_id": EXCHANGE_ORDER_ID}})) + order_id, _ = await self.exchange._place_order( + "PAXS1", NO_PAIR, Decimal("3"), TradeType.SELL, OrderType.LIMIT_MAKER, Decimal("0.6")) + self.assertEqual(EXCHANGE_ORDER_ID, order_id) + body = json.loads(self._sent_json(mock_api)["data"]) + self.assertEqual(("no", "sell", "post_only", "0.6"), + (body["side"], body["action"], body["order_type"], body["price"])) + + @aioresponses() + async def test_market_order_is_sent_as_bounded_ioc(self, mock_api): + mock_api.post(ORDERS_URL, body=json.dumps({"ok": True, "data": { + "ok": True, "status": "FILLED", "order_id": EXCHANGE_ORDER_ID}})) + with patch.object(self.exchange, "get_price_for_volume", + return_value=MagicMock(result_price=0.41234)): + await self.exchange._place_order( + "PAXB2", YES_PAIR, Decimal("3"), TradeType.BUY, OrderType.MARKET, Decimal("NaN")) + body = json.loads(self._sent_json(mock_api)["data"]) + self.assertEqual(("ioc", "0.4124"), (body["order_type"], body["price"])) + + @aioresponses() + async def test_market_order_keeps_the_price_it_was_checked_at(self, mock_api): + mock_api.post(ORDERS_URL, body=json.dumps({"ok": True, "data": { + "ok": True, "status": "FILLED", "order_id": EXCHANGE_ORDER_ID}})) + await self.exchange._place_order( + "PAXB2", YES_PAIR, Decimal("3"), TradeType.BUY, OrderType.MARKET, Decimal("0.4125")) + body = json.loads(self._sent_json(mock_api)["data"]) + self.assertEqual(("ioc", "0.4125"), (body["order_type"], body["price"])) + + def test_taker_price_bounds(self): + with patch.object(self.exchange, "get_price_for_volume", side_effect=Exception("no book")): + self.assertEqual(CONSTANTS.MAX_PRICE, self.exchange._taker_price(YES_PAIR, True, Decimal("1"))) + self.assertEqual(CONSTANTS.MIN_PRICE, self.exchange._taker_price(YES_PAIR, False, Decimal("1"))) + with patch.object(self.exchange, "get_price_for_volume", return_value=MagicMock(result_price=0.33339)): + self.assertEqual(Decimal("0.3333"), self.exchange._taker_price(YES_PAIR, False, Decimal("1"))) + with patch.object(self.exchange, "get_price_for_volume", return_value=MagicMock(result_price=1.5)): + self.assertEqual(CONSTANTS.MAX_PRICE, self.exchange._taker_price(YES_PAIR, True, Decimal("1"))) + + @aioresponses() + async def test_rejected_order_raises(self, mock_api): + mock_api.post(ORDERS_URL, body=json.dumps({"ok": False, "data": { + "ok": False, "status": "REJECTED", "reject_reason": "insufficient_balance"}})) + with self.assertRaisesRegex(IOError, "insufficient_balance"): + await self.exchange._place_order( + "PAXB3", YES_PAIR, Decimal("3"), TradeType.BUY, OrderType.LIMIT, Decimal("0.5")) + + @aioresponses() + async def test_unexpected_placement_responses_raise(self, mock_api): + mock_api.post(ORDERS_URL, body=json.dumps({"ok": True, "data": "oops"})) + with self.assertRaisesRegex(IOError, "Error submitting order"): + await self.exchange._place_order( + "PAXB4", YES_PAIR, Decimal("3"), TradeType.BUY, OrderType.LIMIT, Decimal("0.5")) + mock_api.post(ORDERS_URL, body=json.dumps({"ok": True, "data": {"ok": True, "status": "OPEN"}})) + with self.assertRaisesRegex(IOError, "no order id"): + await self.exchange._place_order( + "PAXB5", YES_PAIR, Decimal("3"), TradeType.BUY, OrderType.LIMIT, Decimal("0.5")) + + @aioresponses() + async def test_duplicate_placement_adopts_the_earlier_order(self, mock_api): + mock_api.post(ORDERS_URL, body=json.dumps({"ok": True, "data": { + "ok": True, "status": "DUPLICATE", "order_id": None, "duplicate": True}})) + mock_api.get(ORDERS_URL, body=env({"orders": [ + {"id": EXCHANGE_ORDER_ID, "side": "YES", "action": "BUY", "size": "3", "status": "OPEN"}, + {"id": "other", "side": "NO", "action": "BUY", "size": "3", "status": "OPEN"}, + ], "next_cursor": None})) + order_id, _ = await self.exchange._place_order( + "PAXB6", YES_PAIR, Decimal("3"), TradeType.BUY, OrderType.LIMIT, Decimal("0.5")) + self.assertEqual(EXCHANGE_ORDER_ID, order_id) + + @aioresponses() + async def test_created_event_precedes_fills_made_on_arrival(self, mock_api): + mock_api.post(ORDERS_URL, body=json.dumps({"ok": True, "data": { + "ok": True, "status": "FILLED", "order_id": EXCHANGE_ORDER_ID, + "fills": [{"maker_id": "m1", "size": 10, "price": "0.42", "trade_id": "t1"}]}})) + events = [] + self.exchange._order_tracker._trigger_created_event = lambda order: events.append("created") + self.exchange._order_tracker._trigger_filled_event = lambda **kw: events.append("filled") + self.exchange._order_tracker._trigger_completed_event = lambda order: events.append("completed") + order = self._track(exchange_order_id=None) + await self.exchange._place_order_and_process_update(order) + await asyncio.sleep(0.01) + self.assertEqual(["created", "filled", "completed"], events) + + async def test_create_order_checks_min_notional(self): + rule = TradingRule(YES_PAIR, min_order_size=CONSTANTS.SIZE_QUANTUM, min_price_increment=CONSTANTS.FINE_TICK, + min_base_amount_increment=CONSTANTS.SIZE_QUANTUM, + min_notional_size=CONSTANTS.MIN_ORDER_NOTIONAL) + self.exchange._trading_rules[YES_PAIR] = rule + placed = [] + + async def place(order, **kwargs): + placed.append((order.client_order_id, order.price)) + return EXCHANGE_ORDER_ID + self.exchange._place_order_and_process_update = place + # below 1 USDT: refused locally + await self.exchange._create_order(TradeType.BUY, "PAXB20", YES_PAIR, Decimal("10"), OrderType.LIMIT, + Decimal("0.05")) + self.assertEqual([], placed) + # a SELL of the whole sellable position is admitted below the minimum + self.exchange._account_available_balances["BTC_200K_2026_YES"] = Decimal("10") + await self.exchange._create_order(TradeType.SELL, "PAXS21", YES_PAIR, Decimal("10"), OrderType.LIMIT, + Decimal("0.05")) + self.assertEqual([("PAXS21", Decimal("0.05"))], placed) + self.assertIs(rule, self.exchange._trading_rules[YES_PAIR]) + # a partial SELL below the minimum is not + await self.exchange._create_order(TradeType.SELL, "PAXS22", YES_PAIR, Decimal("5"), OrderType.LIMIT, + Decimal("0.05")) + self.assertEqual(1, len(placed)) + # a market order is checked, tracked and sent at its ioc bound + with patch.object(self.exchange, "get_price_for_volume", return_value=MagicMock(result_price=0.09)): + await self.exchange._create_order(TradeType.BUY, "PAXB23", YES_PAIR, Decimal("12"), OrderType.MARKET) + self.assertEqual(("PAXB23", Decimal("0.0900")), placed[-1]) + + async def test_order_lookup_without_creation_time(self): + order = self._track() + order.creation_timestamp = float("nan") + seen = [] + + async def rows(market_id, since_ms, force=False): + seen.append(since_ms) + return [{"id": EXCHANGE_ORDER_ID}] + self.exchange._order_rows = rows + self.assertEqual({"id": EXCHANGE_ORDER_ID}, await self.exchange._order_row(order)) + self.assertEqual([0], seen) + + async def test_placement_report_with_final_state(self): + order = self._track(client_id="PAXB7", order_type=OrderType.MARKET) + self.exchange._process_placement_report(order, EXCHANGE_ORDER_ID, { + "status": "CANCELLED", "fills": [{"size": "2", "price": "0.4", "trade_id": "t7"}, + {"size": "1", "price": "0.4"}]}) + await asyncio.sleep(0.01) + self.assertEqual(Decimal("2"), order.executed_amount_base) + self.assertEqual(OrderState.CANCELED, order.current_state) + + # ----- cancel ----- + + @aioresponses() + async def test_cancel_results(self, mock_api): + order = self._track() + url = web_utils.private_rest_url(CONSTANTS.ORDER_PATH_URL.format(EXCHANGE_ORDER_ID)) + mock_api.delete(url, body=env({"ok": True, "cancelled": True, "released_collateral": "4.2"})) + self.assertTrue(await self.exchange._place_cancel("PAXB1", order)) + mock_api.delete(url, body=env({"ok": True, "cancelled": False, "current_status": "CANCELLED"})) + self.assertTrue(await self.exchange._place_cancel("PAXB1", order)) + mock_api.delete(url, body=env({"ok": True, "cancelled": False, "current_status": "FILLED"})) + self.assertFalse(await self.exchange._place_cancel("PAXB1", order)) + mock_api.delete(url, body=env({"ok": True, "cancelled": False, "current_status": "not_found"})) + with self.assertRaisesRegex(IOError, "ORDER_NOT_FOUND"): + await self.exchange._place_cancel("PAXB1", order) + + # ----- order status and fills ----- + + @aioresponses() + async def test_order_status_and_resting_fills(self, mock_api): + order = self._track() + row = {"id": EXCHANGE_ORDER_ID, "market_id": MARKET, "side": "YES", "action": "BUY", "price": "0.42", + "size": "10", "filled_size": "4", "status": "PARTIAL", "updated_at_ms": 1796278100000} + mock_api.get(ORDERS_URL, body=env({"orders": [{"id": "x"}], "next_cursor": "n1"})) + mock_api.get(ORDERS_URL, body=env({"orders": [row], "next_cursor": None})) + update = await self.exchange._request_order_status(order) + self.assertEqual(OrderState.PARTIALLY_FILLED, update.new_state) + self.assertEqual(1796278100.0, update.update_timestamp) + trades = await self.exchange._all_trade_updates_for_order(order) # served from the cache + self.assertEqual(1, len(trades)) + self.assertEqual(f"{EXCHANGE_ORDER_ID}-4", trades[0].trade_id) + self.assertEqual((Decimal("4"), Decimal("0.42")), (trades[0].fill_base_amount, trades[0].fill_price)) + self.assertEqual([], trades[0].fee.flat_fees) + self.exchange._order_tracker.process_trade_update(trades[0]) + self.assertEqual([], await self.exchange._all_trade_updates_for_order(order)) + params = list(mock_api.requests.values())[0][0].kwargs["params"] + self.assertEqual({"market_id": MARKET, "from_ms": 1796278000000 - 120000, "limit": 200}, params) + + @aioresponses() + async def test_order_missing_from_list(self, mock_api): + order = self._track() + mock_api.get(ORDERS_URL, body=env({"orders": [], "next_cursor": None})) + with self.assertRaisesRegex(IOError, "ORDER_NOT_FOUND"): + await self.exchange._request_order_status(order) + self.assertEqual([], await self.exchange._all_trade_updates_for_order(order)) + + async def test_order_without_exchange_id(self): + order = self._track(exchange_order_id=None) + update = await self.exchange._request_order_status(order) + self.assertEqual(OrderState.PENDING_CREATE, update.new_state) + self.assertEqual([], await self.exchange._all_trade_updates_for_order(order)) + + def test_row_timestamp_fallback(self): + self.assertEqual(5.0, self.exchange._row_timestamp({"updated_at_ms": None, "created_at_ms": "x"}, 5.0)) + self.assertEqual(2.0, self.exchange._row_timestamp({"created_at_ms": 2000}, 5.0)) + + # ----- balances ----- + + @aioresponses() + async def test_update_balances(self, mock_api): + self.exchange._account_balances["STALE_YES"] = Decimal("1") + self.exchange._account_available_balances["STALE_YES"] = Decimal("1") + mock_api.get(web_utils.private_rest_url(CONSTANTS.BALANCE_PATH_URL), body=env({"balances": [ + {"asset": "USDT", "free": "90.5", "reserved": "9.5", "total": "100"}]})) + mock_api.get(web_utils.private_rest_url(CONSTANTS.POSITIONS_PATH_URL), body=env({"positions": [ + {"market_id": MARKET, "side": "YES", "type": "normal", "lots": 20}, + {"market_id": MARKET, "side": "YES", "type": "other", "lots": 5}, + {"market_id": MARKET, "side": "NO", "lots": 0}, + {"market_id": MARKET, "side": "MAYBE", "lots": 3}, + ]})) + mock_api.get(ORDERS_URL, body=env({"orders": [ + {"market_id": MARKET, "side": "YES", "action": "SELL", "size": "10", "filled_size": "2"}, + {"market_id": MARKET, "side": "YES", "action": "BUY", "size": "10", "filled_size": "0"}, + ], "next_cursor": "n"})) + mock_api.get(ORDERS_URL, body=env({"orders": [ + {"market_id": MARKET, "side": "YES", "action": "SELL", "size": "1", "filled_size": "0"}, + ], "next_cursor": None})) + await self.exchange._update_balances() + self.assertEqual(Decimal("100.0"), self.exchange.get_balance("USDT")) + self.assertEqual(Decimal("90.5"), self.exchange.get_available_balance("USDT")) + self.assertEqual(Decimal("25"), self.exchange.get_balance("BTC_200K_2026_YES")) + self.assertEqual(Decimal("16"), self.exchange.get_available_balance("BTC_200K_2026_YES")) + self.assertNotIn("STALE_YES", self.exchange._account_balances) + self.assertNotIn("BTC_200K_2026_NO", self.exchange._account_balances) + + # ----- user stream ----- + + async def test_account_event_triggers_poll(self): + queue = asyncio.Queue() + self.exchange._user_stream_tracker._user_stream = queue + self.exchange._order_rows_cache["m"] = (0, 0, []) + queue.put_nowait({"type": "user_orders_update"}) + task = self.local_event_loop.create_task(self.exchange._user_stream_event_listener()) + for _ in range(50): + await asyncio.sleep(0.01) + if self.exchange._poll_notifier.is_set(): + break + task.cancel() + self.assertTrue(self.exchange._poll_notifier.is_set()) + self.assertEqual({}, self.exchange._order_rows_cache) + + async def test_bad_account_event_is_logged(self): + queue = asyncio.Queue() + self.exchange._user_stream_tracker._user_stream = queue + queue.put_nowait(None) + with patch.object(self.exchange, "_sleep", side_effect=asyncio.CancelledError): + with self.assertRaises(asyncio.CancelledError): + await self.exchange._user_stream_event_listener() + self.assertTrue(self._is_logged("ERROR", "Unexpected error in user stream listener loop.")) + + async def test_last_traded_price(self): + with patch.object(self.exchange._orderbook_ds, "get_last_traded_prices", + return_value={YES_PAIR: 0.3}): + self.assertEqual(0.3, await self.exchange._get_last_traded_price(YES_PAIR)) + + # ----- order entry on the WebSocket ----- + + def _ws(self, place=None, cancel=None): + entry = MagicMock() + entry.place = AsyncMock(return_value=place) + entry.cancel = AsyncMock(return_value=cancel) + entry.stop = AsyncMock() + self.exchange._order_entry = entry + return entry + + def test_order_entry_only_when_trading(self): + self.assertIsNotNone(self.ws_entry) + self.assertIsNone(PredictasiaxExchange(predictasiax_api_key="sk_live_test", # noqa: mock + trading_pairs=[], trading_required=False)._order_entry) + + @patch.object(CONSTANTS, "FILLS_RETRY_DELAY", 0) + @aioresponses() + async def test_ws_placement_reads_fills_made_on_arrival(self, mock_api): + entry = self._ws(place={"type": "order_ack", "ok": True, "data": { + "order_id": EXCHANGE_ORDER_ID, "client_order_id": "PAXB1", "status": "PARTIAL", + "filled_size": "6", "resting_size": "4", "trade_ids": ["t1", "t2"], "reject_reason": None}}) + t1 = {"trade_id": "t1", "order_id": EXCHANGE_ORDER_ID, "role": "taker", "price": "0.41", "size": "5", + "fee_usdt": "0.004", "executed_at_ms": 1796278001000} + mock_api.get(FILLS_URL, body=env({"fills": [t1], "next_cursor": None})) + mock_api.get(FILLS_URL, body=env({"fills": [ + t1, {"trade_id": "t2", "role": "taker", "price": "0.42", "size": "1", "fee_usdt": "0.0002"}, + {"trade_id": "t0", "role": "maker", "price": "0.42", "size": "2", "fee_usdt": "0"}], "next_cursor": None})) + order = self._track(exchange_order_id=None) + await self.exchange._place_order_and_process_update(order) + await asyncio.sleep(0.01) + sent = entry.place.call_args.args[0] + self.assertEqual({"market_id": MARKET, "side": "yes", "action": "buy", "size": "10", + "client_order_id": "PAXB1", "order_type": "limit", "price": "0.42"}, sent) + self.assertFalse(any(m == "POST" for m, _ in mock_api.requests)) + params = self._sent_json(mock_api, method="GET", url_part="/v1/fills")["params"] + self.assertEqual({"order_id": EXCHANGE_ORDER_ID, "limit": CONSTANTS.FILLS_PAGE_LIMIT}, params) + self.assertEqual(Decimal("6"), order.executed_amount_base) + self.assertEqual(OrderState.PARTIALLY_FILLED, order.current_state) + self.assertEqual(["t1", "t2"], sorted(order.order_fills)) + fill = order.order_fills["t1"] + self.assertEqual((Decimal("0.41"), 1796278001.0), (fill.fill_price, fill.fill_timestamp)) + self.assertEqual([("USDT", Decimal("0.004"))], [(f.token, f.amount) for f in fill.fee.flat_fees]) + + @patch.object(CONSTANTS, "FILLS_RETRY_DELAY", 0) + @aioresponses() + async def test_ws_placement_fills_matched_by_trade_id(self, mock_api): + # The fills list and the order_ack name a fill by the same trade id: a listing whose sizes + # already add up is not taken until every acked id is in it, and nothing else is taken. + self._ws(place={"ok": True, "data": {"order_id": EXCHANGE_ORDER_ID, "status": "FILLED", "filled_size": "6", + "trade_ids": ["t_7939ab21c73c4c539683ae1858f9e0e0_1", + "t_7939ab21c73c4c539683ae1858f9e0e0_2"]}}) + first = {"trade_id": "t_7939ab21c73c4c539683ae1858f9e0e0_1", "role": "taker", "price": "0.08", "size": "5", + "fee_usdt": "0.0007"} + other = {"trade_id": "t_0000_1", "role": "taker", "price": "0.08", "size": "1", "fee_usdt": "0.0001"} + second = {"trade_id": "t_7939ab21c73c4c539683ae1858f9e0e0_2", "role": "taker", "price": "0.07", "size": "1", + "fee_usdt": "0.00005"} + mock_api.get(FILLS_URL, body=env({"fills": [first, other], "next_cursor": None})) + mock_api.get(FILLS_URL, body=env({"fills": [second, other, first], "next_cursor": None})) + order = self._track(exchange_order_id=None) + await self.exchange._place_order_and_process_update(order) + await asyncio.sleep(0.01) + self.assertEqual(2, sum(len(calls) for (m, _), calls in mock_api.requests.items() if m == "GET")) + self.assertEqual(sorted([first["trade_id"], second["trade_id"]]), sorted(order.order_fills)) + self.assertEqual(Decimal("6"), order.executed_amount_base) + + @patch.object(CONSTANTS, "FILLS_RETRY_DELAY", 0) + @aioresponses() + async def test_ws_placement_without_trade_ids_matches_by_size(self, mock_api): + self._ws(place={"ok": True, "data": {"order_id": EXCHANGE_ORDER_ID, "status": "FILLED", "filled_size": "6"}}) + t1 = {"trade_id": "a1", "role": "taker", "price": "0.41", "size": "6", "fee_usdt": "0.004"} + mock_api.get(FILLS_URL, body=env({"fills": [t1], "next_cursor": None})) + order = self._track(exchange_order_id=None) + await self.exchange._place_order_and_process_update(order) + await asyncio.sleep(0.01) + self.assertEqual(["a1"], sorted(order.order_fills)) + + @patch.object(CONSTANTS, "FILLS_RETRY_DELAY", 0) + @patch.object(CONSTANTS, "FILLS_ATTEMPTS", 2) + @aioresponses() + async def test_ws_placement_fills_not_listed_yet(self, mock_api): + self._ws(place={"ok": True, "data": {"order_id": EXCHANGE_ORDER_ID, "status": "FILLED", + "filled_size": "10", "trade_ids": ["t1"]}}) + mock_api.get(FILLS_URL, status=503, body=json.dumps({"ok": False})) + mock_api.get(FILLS_URL, body=env({"fills": [], "next_cursor": None})) + order = self._track(exchange_order_id=None) + await self.exchange._place_order_and_process_update(order) + await asyncio.sleep(0.01) + # Filled, but not complete until the fills are known: the order status poll supplies them. + self.assertEqual({}, order.order_fills) + self.assertNotEqual(OrderState.FILLED, order.current_state) + self.assertTrue(self._is_logged("WARNING", f"Fills of order {EXCHANGE_ORDER_ID} not read")) + self.assertTrue(self._is_logged("WARNING", "not all listed yet (0 listed)")) + + async def test_ws_placement_without_fills_or_rejected(self): + self._ws(place={"ok": True, "data": {"order_id": EXCHANGE_ORDER_ID, "status": "OPEN", "filled_size": "0"}}) + order_id, _ = await self.exchange._place_order( + "PAXS1", NO_PAIR, Decimal("3"), TradeType.SELL, OrderType.LIMIT_MAKER, Decimal("0.6")) + self.assertEqual(EXCHANGE_ORDER_ID, order_id) + self._ws(place={"ok": False, "data": {"status": "REJECTED", "reject_reason": "insufficient_balance"}, + "error": {"code": "ORDER_REJECTED", "message": "insufficient_balance: free=0"}}) + with self.assertRaisesRegex(IOError, "ORDER_REJECTED: insufficient_balance"): + await self.exchange._place_order( + "PAXB3", YES_PAIR, Decimal("3"), TradeType.BUY, OrderType.LIMIT, Decimal("0.5")) + self._ws(place={"ok": False, "error": {"code": "TIER_LIMIT_EXCEEDED", "message": "daily notional cap"}}) + with self.assertRaisesRegex(IOError, "TIER_LIMIT_EXCEEDED"): + await self.exchange._place_order( + "PAXB4", YES_PAIR, Decimal("3"), TradeType.BUY, OrderType.LIMIT, Decimal("0.5")) + + @aioresponses() + async def test_ws_duplicate_adopts_the_earlier_order(self, mock_api): + self._ws(place={"ok": True, "data": {"order_id": None, "status": "DUPLICATE", "filled_size": "0"}}) + mock_api.get(ORDERS_URL, body=env({"orders": [ + {"id": EXCHANGE_ORDER_ID, "side": "YES", "action": "BUY", "size": "3", "status": "OPEN"}], + "next_cursor": None})) + order_id, _ = await self.exchange._place_order( + "PAXB6", YES_PAIR, Decimal("3"), TradeType.BUY, OrderType.LIMIT, Decimal("0.5")) + self.assertEqual(EXCHANGE_ORDER_ID, order_id) + + @aioresponses() + async def test_ws_unavailable_places_over_rest(self, mock_api): + entry = self._ws(place=None) + mock_api.post(ORDERS_URL, body=json.dumps({"ok": True, "data": { + "ok": True, "status": "OPEN", "order_id": EXCHANGE_ORDER_ID}})) + order_id, _ = await self.exchange._place_order( + "PAXB7", YES_PAIR, Decimal("3"), TradeType.BUY, OrderType.LIMIT, Decimal("0.5")) + self.assertEqual(EXCHANGE_ORDER_ID, order_id) + entry.place.assert_awaited_once() + self.assertEqual("PAXB7", self._sent_json(mock_api)["headers"]["Idempotency-Key"]) + + @aioresponses() + async def test_ws_cancel_results(self, mock_api): + order = self._track() + entry = self._ws(cancel={"ok": True, "data": {"order_id": EXCHANGE_ORDER_ID, "cancelled": True}}) + self.assertTrue(await self.exchange._place_cancel("PAXB1", order)) + entry.cancel.assert_awaited_once_with(EXCHANGE_ORDER_ID) + self._ws(cancel={"ok": True, "data": {"cancelled": False, "status": "CANCELLED"}}) + self.assertTrue(await self.exchange._place_cancel("PAXB1", order)) + self._ws(cancel={"ok": True, "data": {"cancelled": False, "status": "FILLED"}}) + self.assertFalse(await self.exchange._place_cancel("PAXB1", order)) + self._ws(cancel={"ok": False, "data": {"cancelled": False, "status": "not_found"}}) + with self.assertRaisesRegex(IOError, "ORDER_NOT_FOUND"): + await self.exchange._place_cancel("PAXB1", order) + self._ws(cancel={"ok": False, "error": {"code": "VALIDATION_FAILED", "message": "order_id"}}) + with self.assertRaisesRegex(IOError, "VALIDATION_FAILED"): + await self.exchange._place_cancel("PAXB1", order) + self._ws(cancel=None) + url = web_utils.private_rest_url(CONSTANTS.ORDER_PATH_URL.format(EXCHANGE_ORDER_ID)) + mock_api.delete(url, body=env({"ok": True, "cancelled": True})) + self.assertTrue(await self.exchange._place_cancel("PAXB1", order)) + + async def test_stop_network_closes_the_order_socket(self): + entry = self._ws() + await self.exchange.stop_network() + entry.stop.assert_awaited_once() + self.exchange._order_entry = None + await self.exchange.stop_network() + + def test_fee_type(self): + trade = self.exchange._trade_update(self._track(client_id="PAXB9"), EXCHANGE_ORDER_ID, "t", Decimal("1"), + Decimal("0.5"), is_taker=True, timestamp=3.0) + self.assertIsInstance(trade.fee, AddedToCostTradeFee) + self.assertEqual(3.0, trade.fill_timestamp) + self.assertGreater(self.exchange._time(), 1_700_000_000) diff --git a/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_order_entry.py b/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_order_entry.py new file mode 100644 index 000000000..7e1c7a3fb --- /dev/null +++ b/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_order_entry.py @@ -0,0 +1,255 @@ +import asyncio +import json +from test.isolated_asyncio_wrapper_test_case import IsolatedAsyncioWrapperTestCase +from unittest.mock import AsyncMock, patch + +import aiohttp +from aioresponses import aioresponses + +from hummingbot.connector.exchange.predictasiax import ( + predictasiax_constants as CONSTANTS, + predictasiax_web_utils as web_utils, +) +from hummingbot.connector.exchange.predictasiax.predictasiax_order_entry import PredictasiaxOrderEntry +from hummingbot.connector.test_support.network_mocking_assistant import NetworkMockingAssistant +from hummingbot.core.api_throttler.async_throttler import AsyncThrottler + +ORDER = {"market_id": "btc-200k-2026", "side": "yes", "action": "buy", "size": "10", + "client_order_id": "PAXB1", "order_type": "limit", "price": "0.42"} +AVAILABLE = {"available": True, "rate_tier": "t1", "orders_per_s": 25, "orders_burst": 50, + "cancels_per_s": 50, "cancels_burst": 100, "open_orders": 500, "batch_max": 20, "in_flight": 64} + + +class PredictasiaxOrderEntryTests(IsolatedAsyncioWrapperTestCase): + level = 0 + + async def asyncSetUp(self) -> None: + await super().asyncSetUp() + self.log_records = [] + self.mocking_assistant = NetworkMockingAssistant() + await self.mocking_assistant.async_init() + self.throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS) + self.factory = web_utils.build_api_factory(throttler=self.throttler) + self.entry = PredictasiaxOrderEntry(self.factory, self.throttler) + self.entry.logger().setLevel(1) + self.entry.logger().addHandler(self) + self.token_url = web_utils.private_rest_url(CONSTANTS.WS_TOKEN_PATH_URL) + + async def asyncTearDown(self) -> None: + await self.entry.stop() + await super().asyncTearDown() + + def handle(self, record): + self.log_records.append(record) + + def _is_logged(self, level: str, message: str) -> bool: + return any(r.levelname == level and message in r.getMessage() for r in self.log_records) + + @staticmethod + def _token(token="wst_abc"): + return json.dumps({"ok": True, "data": {"token": token, "expires_in": 900}}) + + def _socket(self, order_entry=None): + ws = self.mocking_assistant.create_websocket_mock() + self.mocking_assistant.add_websocket_aiohttp_message(ws, json.dumps({"type": "welcome"})) + self.mocking_assistant.add_websocket_aiohttp_message(ws, json.dumps( + {"type": "authenticated", "order_entry": AVAILABLE if order_entry is None else order_entry})) + return ws + + def _requests(self, ws, method): + return [m for m in self.mocking_assistant.json_messages_sent_through_websocket(ws) if m.get("method") == method] + + async def _reply(self, ws, method, count, reply): + """Once the count-th `method` request is sent, answer it with `reply` and its req_id.""" + for _ in range(200): + sent = self._requests(ws, method) + if len(sent) >= count: + self.mocking_assistant.add_websocket_aiohttp_message( + ws, json.dumps({**reply, "req_id": sent[count - 1]["req_id"]})) + return sent[count - 1] + await asyncio.sleep(0.005) + raise AssertionError(f"{method} #{count} not sent") + + @aioresponses() + @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) + async def test_place_and_cancel_on_one_socket(self, mock_api, ws_connect_mock): + mock_api.post(self.token_url, body=self._token()) + ws = self._socket() + ws_connect_mock.return_value = ws + ack = {"type": "order_ack", "ok": True, "data": {"order_id": "o1", "status": "OPEN"}} + task = asyncio.ensure_future(self.entry.place(ORDER)) + sent = await self._reply(ws, "PLACE_ORDER", 1, ack) + self.assertEqual("o1", (await task)["data"]["order_id"]) + self.assertEqual(ORDER, sent["order"]) + messages = self.mocking_assistant.json_messages_sent_through_websocket(ws) + self.assertEqual({"method": "AUTH", "token": "wst_abc"}, messages[0]) + self.assertEqual({"method": "UNSUBSCRIBE", "params": CONSTANTS.WS_DEFAULT_CHANNELS}, messages[1]) + self.assertEqual(AVAILABLE, self.entry.limits) + self.assertEqual(25, self.throttler._id_to_limit_map[CONSTANTS.WS_PLACE_ORDER_LIMIT_ID].limit) + self.assertEqual(50, self.throttler._id_to_limit_map[CONSTANTS.WS_CANCEL_ORDER_LIMIT_ID].limit) + + task = asyncio.ensure_future(self.entry.cancel("o1")) + sent = await self._reply(ws, "CANCEL_ORDER", 1, {"type": "cancel_ack", "ok": True, + "data": {"order_id": "o1", "cancelled": True}}) + self.assertTrue((await task)["data"]["cancelled"]) + self.assertEqual("o1", sent["order_id"]) + self.assertNotEqual(self._requests(ws, "PLACE_ORDER")[0]["req_id"], sent["req_id"]) + self.assertEqual(1, ws_connect_mock.call_count) + # Frames without a pending req_id are ignored. + self.mocking_assistant.add_websocket_aiohttp_message(ws, json.dumps({"type": "pong", "req_id": 99})) + await asyncio.sleep(0.01) + + @aioresponses() + @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) + async def test_key_without_order_entry_uses_rest(self, mock_api, ws_connect_mock): + mock_api.post(self.token_url, body=self._token()) + ws_connect_mock.return_value = self._socket( + {"available": False, "code": "ORDER_ENTRY_NOT_AVAILABLE", "message": "builder accounts only"}) + self.assertIsNone(await self.entry.place(ORDER)) + self.assertTrue(self._is_logged("INFO", "order entry not available for this key (ORDER_ENTRY_NOT_AVAILABLE")) + self.assertIsNone(await self.entry.cancel("o1")) + self.assertEqual(1, ws_connect_mock.call_count) + + @aioresponses() + @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) + async def test_refusals_before_submission(self, mock_api, ws_connect_mock): + mock_api.post(self.token_url, body=self._token()) + ws = self._socket({"available": True, "orders_per_s": "x"}) + ws_connect_mock.return_value = ws + refused = {"type": "order_ack", "ok": False, "error": {"code": "RATE_LIMITED", "retry_after_ms": 50}} + task = asyncio.ensure_future(self.entry.place(ORDER)) + await self._reply(ws, "PLACE_ORDER", 1, refused) + self.assertIsNone(await task) + self.assertEqual(CONSTANTS.WS_ORDERS_PER_S, + self.throttler._id_to_limit_map[CONSTANTS.WS_PLACE_ORDER_LIMIT_ID].limit) + # The socket stays in use; a key-level refusal turns it off. + task = asyncio.ensure_future(self.entry.place(ORDER)) + await self._reply(ws, "PLACE_ORDER", 2, {"type": "order_ack", "ok": False, + "error": {"code": "TIER_NOT_ELIGIBLE", "message": "sandbox"}}) + self.assertIsNone(await task) + self.assertTrue(self._is_logged("INFO", "order entry not available (TIER_NOT_ELIGIBLE)")) + self.assertIsNone(await self.entry.place(ORDER)) + self.assertEqual(2, len(self._requests(ws, "PLACE_ORDER"))) + + @patch.object(CONSTANTS, "WS_ORDER_RETRY_DELAY", 0) + @aioresponses() + @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) + async def test_unknown_outcome_is_resent_with_the_same_order(self, mock_api, ws_connect_mock): + mock_api.post(self.token_url, body=self._token(), repeat=True) + ws1, ws2 = self._socket(), self._socket() + ws_connect_mock.side_effect = [ws1, ws2] + task = asyncio.ensure_future(self.entry.place(ORDER)) + await self._reply(ws1, "PLACE_ORDER", 1, {"ok": False, "error": {"code": "SERVICE_UNAVAILABLE"}}) + await self._reply(ws1, "PLACE_ORDER", 2, {"ok": False, "error": {"code": "SESSION_EXPIRED"}}) + await self._reply(ws2, "PLACE_ORDER", 1, {"ok": True, "data": {"order_id": "o1", "replay": True}}) + self.assertTrue((await task)["data"]["replay"]) + self.assertEqual([ORDER, ORDER], [m["order"] for m in self._requests(ws1, "PLACE_ORDER")]) + self.assertEqual(2, ws_connect_mock.call_count) + + @patch.object(CONSTANTS, "WS_ORDER_RETRY_DELAY", 0) + @aioresponses() + @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) + async def test_no_answer_after_every_attempt_uses_rest(self, mock_api, ws_connect_mock): + mock_api.post(self.token_url, body=self._token()) + ws = self._socket() + ws_connect_mock.return_value = ws + task = asyncio.ensure_future(self.entry.place(ORDER)) + for n in range(1, CONSTANTS.WS_ORDER_ATTEMPTS + 1): + await self._reply(ws, "PLACE_ORDER", n, {"ok": False, "error": {"code": "SERVICE_UNAVAILABLE"}}) + self.assertIsNone(await task) + + @patch.object(CONSTANTS, "WS_ORDER_RETRY_DELAY", 0) + @aioresponses() + @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) + async def test_expired_sign_in_on_the_last_attempt_uses_rest(self, mock_api, ws_connect_mock): + mock_api.post(self.token_url, body=self._token(), repeat=True) + sockets = [self._socket() for _ in range(CONSTANTS.WS_ORDER_ATTEMPTS)] + ws_connect_mock.side_effect = sockets + task = asyncio.ensure_future(self.entry.place(ORDER)) + for ws in sockets: + await self._reply(ws, "PLACE_ORDER", 1, {"ok": False, "error": {"code": "AUTH_REQUIRED"}}) + self.assertIsNone(await task) + + @aioresponses() + @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) + async def test_socket_closed_before_the_reply(self, mock_api, ws_connect_mock): + mock_api.post(self.token_url, body=self._token(), repeat=True) + ws1, ws2 = self._socket(), self._socket() + ws_connect_mock.side_effect = [ws1, ws2] + task = asyncio.ensure_future(self.entry.place(ORDER)) + for _ in range(200): + if self._requests(ws1, "PLACE_ORDER"): + break + await asyncio.sleep(0.005) + self.mocking_assistant.add_websocket_aiohttp_message(ws1, "", message_type=aiohttp.WSMsgType.CLOSE) + await self._reply(ws2, "PLACE_ORDER", 1, {"ok": True, "data": {"order_id": "o1"}}) + self.assertEqual("o1", (await task)["data"]["order_id"]) + self.assertTrue(self._is_logged("WARNING", "PLACE_ORDER got no reply")) + + @patch.object(CONSTANTS, "WS_ORDER_REPLY_TIMEOUT", 0.05) + @aioresponses() + @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) + async def test_reply_timeout_is_resent(self, mock_api, ws_connect_mock): + mock_api.post(self.token_url, body=self._token(), repeat=True) + ws1, ws2 = self._socket(), self._socket() + ws_connect_mock.side_effect = [ws1, ws2] + task = asyncio.ensure_future(self.entry.place(ORDER)) + await self._reply(ws2, "PLACE_ORDER", 1, {"ok": True, "data": {"order_id": "o1"}}) + self.assertEqual("o1", (await task)["data"]["order_id"]) + self.assertEqual(1, len(self._requests(ws1, "PLACE_ORDER"))) + + @aioresponses() + async def test_socket_that_cannot_open_uses_rest(self, mock_api): + mock_api.post(self.token_url, body=json.dumps({"ok": True, "data": {}})) + self.assertIsNone(await self.entry.place(ORDER)) + self.assertTrue(self._is_logged("WARNING", "order entry socket unavailable")) + self.assertIsNone(await self.entry.cancel("o1")) + self.assertEqual(1, len(mock_api.requests)) + + @aioresponses() + @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) + async def test_sign_in_refused_or_cut_off(self, mock_api, ws_connect_mock): + mock_api.post(self.token_url, body=self._token(), repeat=True) + ws = self.mocking_assistant.create_websocket_mock() + self.mocking_assistant.add_websocket_aiohttp_message(ws, json.dumps({"type": "auth_denied", "code": "x"})) + ws_connect_mock.return_value = ws + self.assertIsNone(await self.entry.place(ORDER)) + self.assertTrue(self._is_logged("WARNING", "sign-in refused")) + + closed = AsyncMock() + + async def frames(): + yield type("R", (), {"data": "not json"})() + + closed.iter_messages = frames + with self.assertRaises(ConnectionError): + await self.entry._sign_in(closed) + + @patch.object(CONSTANTS, "WS_PING_INTERVAL", 0.05) + @aioresponses() + @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) + async def test_quiet_socket_is_pinged_and_errors_close_it(self, mock_api, ws_connect_mock): + mock_api.post(self.token_url, body=self._token()) + ws = self._socket() + ws_connect_mock.return_value = ws + self.assertIsNotNone(await self.entry._socket()) + for _ in range(100): + if {"type": "ping"} in self.mocking_assistant.json_messages_sent_through_websocket(ws): + break + await asyncio.sleep(0.01) + self.assertIn({"type": "ping"}, self.mocking_assistant.json_messages_sent_through_websocket(ws)) + self.mocking_assistant.add_websocket_aiohttp_exception(ws, RuntimeError("boom")) + reader = self.entry._reader + await asyncio.wait_for(asyncio.shield(reader), timeout=1) + self.assertTrue(self._is_logged("WARNING", "order entry socket closed (boom)")) + + async def test_stop_tolerates_a_failing_disconnect(self): + ws = AsyncMock() + ws.disconnect.side_effect = RuntimeError("gone") + self.entry._ws = ws + await self.entry.stop() + self.assertIsNone(self.entry._ws) + + def test_logger(self): + PredictasiaxOrderEntry._logger = None + self.assertIs(PredictasiaxOrderEntry.logger(), PredictasiaxOrderEntry.logger()) diff --git a/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_user_stream_data_source.py b/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_user_stream_data_source.py new file mode 100644 index 000000000..52378e31b --- /dev/null +++ b/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_user_stream_data_source.py @@ -0,0 +1,134 @@ +import asyncio +import gzip +import json +from test.isolated_asyncio_wrapper_test_case import IsolatedAsyncioWrapperTestCase +from unittest.mock import AsyncMock, patch + +import aiohttp +from aioresponses import aioresponses + +from hummingbot.connector.exchange.predictasiax import ( + predictasiax_constants as CONSTANTS, + predictasiax_web_utils as web_utils, +) +from hummingbot.connector.exchange.predictasiax.predictasiax_api_user_stream_data_source import ( + PredictasiaxAPIUserStreamDataSource, +) +from hummingbot.connector.exchange.predictasiax.predictasiax_auth import PredictasiaxAuth +from hummingbot.connector.exchange.predictasiax.predictasiax_exchange import PredictasiaxExchange +from hummingbot.connector.test_support.network_mocking_assistant import NetworkMockingAssistant + + +class PredictasiaxUserStreamDataSourceTests(IsolatedAsyncioWrapperTestCase): + level = 0 + + async def asyncSetUp(self) -> None: + await super().asyncSetUp() + self.log_records = [] + self.mocking_assistant = NetworkMockingAssistant() + await self.mocking_assistant.async_init() + self.auth = PredictasiaxAuth(api_key="sk_live_test") # noqa: mock + self.connector = PredictasiaxExchange(predictasiax_api_key="sk_live_test", # noqa: mock + trading_pairs=[], trading_required=False) + self.connector._web_assistants_factory._auth = self.auth + self.data_source = PredictasiaxAPIUserStreamDataSource( + auth=self.auth, connector=self.connector, api_factory=self.connector._web_assistants_factory) + self.data_source.logger().setLevel(1) + self.data_source.logger().addHandler(self) + self.listening_task = None + self.token_url = web_utils.private_rest_url(CONSTANTS.WS_TOKEN_PATH_URL) + + def tearDown(self) -> None: + self.listening_task and self.listening_task.cancel() + super().tearDown() + + def handle(self, record): + self.log_records.append(record) + + def _is_logged(self, level: str, message: str) -> bool: + return any(r.levelname == level and message in r.getMessage() for r in self.log_records) + + def _token_response(self, token="wst_abc"): + return json.dumps({"ok": True, "data": {"token": token, "expires_in": 900, "expires_at_ms": 1}}) + + @aioresponses() + @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) + async def test_signs_in_and_forwards_account_events(self, mock_api, ws_connect_mock): + mock_api.post(self.token_url, body=self._token_response()) + ws = self.mocking_assistant.create_websocket_mock() + ws_connect_mock.return_value = ws + self.mocking_assistant.add_websocket_aiohttp_message(ws, json.dumps({"type": "welcome"})) + self.mocking_assistant.add_websocket_aiohttp_message(ws, json.dumps({"type": "authenticated"})) + self.mocking_assistant.add_websocket_aiohttp_message( + ws, json.dumps({"type": "user_orders_update", "event": "filled"})) + self.mocking_assistant.add_websocket_aiohttp_message( + ws, gzip.compress(json.dumps([{"type": "fast_tick"}, {"type": "balance_updated"}]).encode()), + message_type=aiohttp.WSMsgType.BINARY) + queue = asyncio.Queue() + self.listening_task = self.local_event_loop.create_task(self.data_source.listen_for_user_stream(queue)) + first = await asyncio.wait_for(queue.get(), timeout=2) + second = await asyncio.wait_for(queue.get(), timeout=2) + self.assertEqual("user_orders_update", first["type"]) + self.assertEqual("balance_updated", second["type"]) + sent = self.mocking_assistant.json_messages_sent_through_websocket(ws) + self.assertEqual({"method": "AUTH", "token": "wst_abc"}, sent[0]) + self.assertEqual({"method": "UNSUBSCRIBE", "params": CONSTANTS.WS_DEFAULT_CHANNELS}, sent[1]) + self.assertTrue(self._is_logged("INFO", "private WebSocket connection authenticated")) + self.assertEqual("Bearer sk_live_test", + list(mock_api.requests.values())[0][0].kwargs["headers"]["Authorization"]) + + @aioresponses() + @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) + async def test_sign_in_refused(self, mock_api, ws_connect_mock): + mock_api.post(self.token_url, body=self._token_response()) + ws = self.mocking_assistant.create_websocket_mock() + ws_connect_mock.return_value = ws + self.mocking_assistant.add_websocket_aiohttp_message( + ws, json.dumps({"type": "auth_denied", "code": "invalid_token"})) + with self.assertRaises(ConnectionError): + await self.data_source._connected_websocket_assistant() + + @aioresponses() + async def test_missing_token_raises(self, mock_api): + mock_api.post(self.token_url, body=json.dumps({"ok": True, "data": {}})) + with self.assertRaises(IOError): + await self.data_source._sign_in_token() + + async def test_wait_for_sign_in_when_socket_closes(self): + ws = AsyncMock() + + async def frames(): + yield type("R", (), {"data": "not json"})() + + ws.iter_messages = frames + with self.assertRaises(ConnectionError): + await self.data_source._wait_for_sign_in(ws) + + @patch.object(CONSTANTS, "WS_PING_INTERVAL", 0.05) + @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) + async def test_quiet_stream_sends_application_ping(self, ws_connect_mock): + ws = self.mocking_assistant.create_websocket_mock() + ws_connect_mock.return_value = ws + await ws_connect_mock.return_value.__aenter__() + assistant = await self.connector._web_assistants_factory.get_ws_assistant() + await assistant.connect(ws_url="wss://predictasiax.com/ws") + task = self.local_event_loop.create_task( + self.data_source._process_websocket_messages(assistant, asyncio.Queue())) + sent = [] + for _ in range(40): + await asyncio.sleep(0.02) + sent = self.mocking_assistant.json_messages_sent_through_websocket(ws) + if {"type": "ping"} in sent: + break + task.cancel() + self.assertIn({"type": "ping"}, sent) + + async def test_process_websocket_messages_returns_when_stream_ends(self): + ws = AsyncMock() + + async def no_messages(): + return + yield # pragma: no cover + + ws.iter_messages = no_messages + await self.data_source._process_websocket_messages(ws, asyncio.Queue()) diff --git a/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_web_utils.py b/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_web_utils.py new file mode 100644 index 000000000..b3ffeeae7 --- /dev/null +++ b/test/hummingbot/connector/exchange/predictasiax/test_predictasiax_web_utils.py @@ -0,0 +1,41 @@ +import gzip +import json +from test.isolated_asyncio_wrapper_test_case import IsolatedAsyncioWrapperTestCase + +from aioresponses import aioresponses + +from hummingbot.connector.exchange.predictasiax import ( + predictasiax_constants as CONSTANTS, + predictasiax_web_utils as web_utils, +) +from hummingbot.core.web_assistant.web_assistants_factory import WebAssistantsFactory + + +class PredictasiaxWebUtilsTests(IsolatedAsyncioWrapperTestCase): + def test_urls(self): + self.assertEqual("https://api.predictasiax.com/v1/markets", web_utils.public_rest_url("/v1/markets")) + self.assertEqual("https://api.predictasiax.com/v1/orders", web_utils.private_rest_url("/v1/orders")) + self.assertEqual("wss://predictasiax.com/ws", web_utils.wss_url()) + + def test_response_data_unwraps_envelope(self): + self.assertEqual({"a": 1}, web_utils.response_data({"data": {"a": 1}, "meta": {}})) + self.assertEqual({"a": 1}, web_utils.response_data({"a": 1})) + self.assertEqual([1], web_utils.response_data([1])) + + def test_decode_ws_frame(self): + self.assertEqual([{"type": "x"}], web_utils.decode_ws_frame({"type": "x"})) + self.assertEqual([{"type": "x"}], web_utils.decode_ws_frame('{"type": "x"}')) + packed = gzip.compress(json.dumps([{"type": "a"}, 3, {"type": "b"}]).encode()) + self.assertEqual([{"type": "a"}, {"type": "b"}], web_utils.decode_ws_frame(packed)) + self.assertEqual([], web_utils.decode_ws_frame(b"not gzip")) + self.assertEqual([], web_utils.decode_ws_frame("not json")) + self.assertEqual([], web_utils.decode_ws_frame(None)) + + def test_build_api_factory(self): + self.assertIsInstance(web_utils.build_api_factory(), WebAssistantsFactory) + + @aioresponses() + async def test_get_current_server_time(self, mock_api): + mock_api.get(web_utils.public_rest_url(CONSTANTS.HEALTH_PATH_URL), + body=json.dumps({"data": {"status": "ok"}, "meta": {"ts_ms": 1796278837912}})) + self.assertEqual(1796278837912.0, await web_utils.get_current_server_time()) -- 2.54.0