deep_extend(parent::describe(), array( 'has' => array( 'ws' => true, 'watchBalance' => true, 'watchFundingRate' => true, 'watchFundingRates' => false, 'watchMyTrades' => true, 'watchOHLCV' => true, 'watchOrderBook' => true, 'watchOrders' => true, 'watchTicker' => true, 'watchTickers' => true, 'watchBidsAsks' => true, 'watchTrades' => true, 'watchTradesForSymbols' => false, 'watchPositions' => true, 'unWatchTicker' => true, 'unWatchTickers' => true, 'unWatchOrderBook' => true, 'unWatchOHLCV' => true, 'unWatchTrades' => true, ), 'urls' => array( 'api' => array( 'ws' => array( 'public' => 'wss://wss.woox.io/ws/stream', 'private' => 'wss://wss.woox.io/v2/ws/private/stream', ), ), 'test' => array( 'ws' => array( 'public' => 'wss://wss.staging.woox.io/ws/stream', 'private' => 'wss://wss.staging.woox.io/v2/ws/private/stream', ), ), ), 'requiredCredentials' => array( 'apiKey' => true, 'secret' => true, 'uid' => true, ), 'options' => array( 'tradesLimit' => 1000, 'ordersLimit' => 1000, 'requestId' => array(), 'watchPositions' => array( 'fetchPositionsSnapshot' => true, // or false 'awaitPositionsSnapshot' => true, // whether to wait for the positions snapshot before providing updates ), ), 'streaming' => array( 'ping' => array($this, 'ping'), 'keepAlive' => 9000, ), 'exceptions' => array( 'ws' => array( 'exact' => array( 'Auth is needed.' => '\\ccxt\\AuthenticationError', ), ), ), )); } public function request_id(string $url): int { $options = $this->safe_dict($this->options, 'requestId', array()); $previousValue = $this->safe_integer($options, $url, 0); $newValue = $this->sum($previousValue, 1); $entry = array(); $entry[$url] = $newValue; $this->options['requestId'] = $this->extend($this->safe_dict($this->options, 'requestId', array()), $entry); return $newValue; } public function watch_public(string $messageHash, array $message) { return Async\async(self::do_watch_public(...))($messageHash, $message); } private function do_watch_public(string $messageHash, array $message) { $urlUid = ''; if (($this->uid !== null) && ($this->uid !== '')) { $urlUid = '/' . $this->uid; } $apiUrl = $this->safe_string($this->urls['api']['ws'], 'public', ''); $url = $apiUrl . $urlUid; $requestId = $this->request_id($url); $subscribe = array( 'id' => $requestId, ); $request = $this->extend($subscribe, $message); return Async\await($this->watch($url, $messageHash, $request, $messageHash, $subscribe)); } public function unwatch_public(string $subHash, ?string $symbol, string $topic, $params = array()): PromiseInterface { return Async\async(self::do_unwatch_public(...))($subHash, $symbol, $topic, $params); } private function do_unwatch_public(string $subHash, ?string $symbol, string $topic, $params = array()) { $urlUid = ''; if (($this->uid !== null) && ($this->uid !== '')) { $urlUid = '/' . $this->uid; } $apiUrl = $this->safe_string($this->urls['api']['ws'], 'public', ''); $url = $apiUrl . $urlUid; $requestId = $this->request_id($url); $unsubHash = 'unsubscribe::' . $subHash; $message = array( 'id' => $requestId, 'event' => 'unsubscribe', 'topic' => $subHash, ); $subscription = array( 'id' => (string) $requestId, 'unsubscribe' => true, 'symbols' => array( $symbol ), 'topic' => $topic, 'subMessageHashes' => array( $subHash ), 'unsubMessageHashes' => array( $unsubHash ), ); $symbolsAndTimeframes = $this->safe_list($params, 'symbolsAndTimeframes'); $paramsOmitted = ($symbolsAndTimeframes !== null) ? $this->omit($params, 'symbolsAndTimeframes') : $params; if ($symbolsAndTimeframes !== null) { $subscription['symbolsAndTimeframes'] = $symbolsAndTimeframes; } return Async\await($this->watch($url, $unsubHash, $this->extend($message, $paramsOmitted), $unsubHash, $subscription)); } public function watch_order_book(string $symbol, ?int $limit = null, $params = array()): PromiseInterface { return Async\async(self::do_watch_order_book(...))($symbol, $limit, $params); } private function do_watch_order_book(string $symbol, ?int $limit = null, $params = array()) { /** * * @see https://docs.woox.io/#orderbookupdate * @see https://docs.woox.io/#$orderbook * * watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data * @param {string} $symbol unified $symbol of the $market to fetch the order book for * @param {int} [$limit] the maximum amount of order book entries to return. * @param {array} [$params] extra parameters specific to the exchange API endpoint * @param {string} [$params->method] either (default) 'orderbook' or 'orderbookupdate', default is 'orderbook' * @return {array} an ~@link https://docs.ccxt.com/?id=order-book-structure order book structure~ */ if ($this->markets === null) { Async\await($this->load_markets()); } list($method, $paramsMethod) = $this->handle_option_string_and_params($params, 'watchOrderBook', 'method', 'orderbook'); $market = $this->market($symbol); $marketId = $this->safe_string($market, 'id', ''); $topic = $marketId . '@' . $method; $urlUid = ''; if (($this->uid !== null) && ($this->uid !== '')) { $urlUid = '/' . $this->uid; } $apiUrl = $this->safe_string($this->urls['api']['ws'], 'public', ''); $url = $apiUrl . $urlUid; $requestId = $this->request_id($url); $request = array( 'event' => 'subscribe', 'topic' => $topic, 'id' => $requestId, ); $subscription = array( 'id' => (string) $requestId, 'name' => $method, 'symbol' => $market['symbol'], 'limit' => $limit, 'params' => $paramsMethod, ); if ($method === 'orderbookupdate') { $subscription['method'] = array($this, 'handle_order_book_subscription'); } $orderbook = Async\await($this->watch($url, $topic, $this->extend($request, $paramsMethod), $topic, $subscription)); return $orderbook->limit(); } public function un_watch_order_book(string $symbol, $params = array()): PromiseInterface { return Async\async(self::do_un_watch_order_book(...))($symbol, $params); } private function do_un_watch_order_book(string $symbol, $params = array()) { /** * unWatches information on open orders with bid (buy) and ask (sell) prices, volumes and other data * * @see https://docs.woox.io/#orderbookupdate * @see https://docs.woox.io/#orderbook * * @param {string} $symbol unified $symbol of the $market * @param {array} [$params] extra parameters specific to the exchange API endpoint * @return {array} A dictionary of ~@link https://docs.ccxt.com/?id=order-book-structure order book structures~ */ if ($this->markets === null) { Async\await($this->load_markets()); } list($method, $paramsMethod) = $this->handle_option_string_and_params($params, 'watchOrderBook', 'method', 'orderbook'); $market = $this->market($symbol); $marketId = $this->safe_string($market, 'id', ''); $subHash = $marketId . '@' . $method; $topic = 'orderbook'; return Async\await($this->unwatch_public($subHash, $market['symbol'], $topic, $paramsMethod)); } public function handle_order_book(Client $client, array $message) { // // { // "topic": "PERP_BTC_USDT@orderbookupdate", // "ts": 1722500373999, // "data": { // "symbol": "PERP_BTC_USDT", // "prevTs": 1722500373799, // "bids": [ // [ // 0.30891, // 2469.98 // ] // ], // "asks": [ // [ // 0.31075, // 2379.63 // ] // ] // } // } // $data = $this->safe_dict($message, 'data'); $marketId = $this->safe_string($data, 'symbol'); $market = $this->safe_market($marketId); $symbol = $market['symbol']; $topic = $this->safe_string($message, 'topic'); if ($topic === null) { return; } $method = $this->safe_string(explode('@', $topic), 1); if ($method === 'orderbookupdate') { if (!(is_array($this->orderbooks) && array_key_exists($symbol ?? '', $this->orderbooks))) { return; } $orderbook = $this->orderbooks[$symbol]; $timestamp = $this->safe_integer($orderbook, 'timestamp'); if ($timestamp === null) { $orderbook->cache[] = $message; } else { try { $ts = $this->safe_integer($message, 'ts'); if ($ts === null) { return; } if ($ts > $timestamp) { $this->handle_order_book_message($client, $message, $orderbook); $client->resolve($orderbook, $topic); } } catch (Exception $e) { unset($this->orderbooks[$symbol]); if ($topic !== null) { unset($client->subscriptions[$topic]); } $client->reject($e, $topic); } } } else { if (!(is_array($this->orderbooks) && array_key_exists($symbol ?? '', $this->orderbooks))) { $defaultLimit = $this->safe_integer($this->options, 'watchOrderBookLimit', 1000); $subscription = $this->safe_dict($client->subscriptions, $topic); $limit = $this->safe_integer($subscription, 'limit', $defaultLimit); $this->orderbooks[$symbol] = $this->order_book(array(), $limit); } $orderbook = $this->orderbooks[$symbol]; $timestamp = $this->safe_integer($message, 'ts'); $snapshot = $this->parse_order_book($data, $symbol, $timestamp, 'bids', 'asks'); $orderbook->reset($snapshot); $client->resolve($orderbook, $topic); } } public function handle_order_book_subscription(Client $client, array $message, array $subscription) { $defaultLimit = $this->safe_integer($this->options, 'watchOrderBookLimit', 1000); $limit = $this->safe_integer($subscription, 'limit', $defaultLimit); $symbol = $this->safe_string($subscription, 'symbol'); // watchOrderBook if ($symbol === null) { return; } if (!(is_array($this->orderbooks) && array_key_exists($symbol ?? '', $this->orderbooks))) { $this->orderbooks[$symbol] = $this->order_book(array(), $limit); } $orderbook = $this->orderbooks[$symbol]; // handleOrderBook queues deltas while timestamp is undefined, until the REST snapshot lands $orderbook['timestamp'] = null; $orderbook['datetime'] = null; $orderbook->cache = array(); $this->spawn(array($this, 'fetch_order_book_snapshot'), $client, $message, $subscription); } public function fetch_order_book_snapshot(Client $client, array $message, array $subscription) { return Async\async(self::do_fetch_order_book_snapshot(...))($client, $message, $subscription); } private function do_fetch_order_book_snapshot(Client $client, array $message, array $subscription) { $symbol = $this->safe_string($subscription, 'symbol'); $messageHash = $this->safe_string($message, 'topic'); try { $defaultLimit = $this->safe_integer($this->options, 'watchOrderBookLimit', 1000); $limit = $this->safe_integer($subscription, 'limit', $defaultLimit); $params = $this->safe_dict($subscription, 'params'); $snapshot = Async\await($this->fetch_rest_order_book_safe($symbol, $limit, $params)); if ($this->safe_dict($this->orderbooks, $symbol) === null) { // if the orderbook is dropped before the snapshot is received return; } $orderbook = $this->safe_value($this->orderbooks, $symbol); $orderbook->reset($snapshot); $messages = $orderbook->cache; for ($i = 0; $i < count($messages); $i++) { $messageItem = $messages[$i]; $ts = $this->safe_integer($messageItem, 'ts'); if ($ts === null) { continue; } $orderbookTimestamp = $this->safe_integer($orderbook, 'timestamp'); if (($orderbookTimestamp !== null) && ($ts < $orderbookTimestamp)) { continue; } else { $this->handle_order_book_message($client, $messageItem, $orderbook); } } if ($symbol !== null) { $this->orderbooks[$symbol] = $orderbook; } $client->resolve($orderbook, $messageHash); } catch (Exception $e) { if ($messageHash !== null) { unset($client->subscriptions[$messageHash]); } $client->reject($e, $messageHash); } } public function handle_order_book_message(Client $client, array $message, mixed $orderbook) { $data = $this->safe_dict($message, 'data'); $this->handle_deltas($orderbook['asks'], $this->safe_list($data, 'asks', array())); $this->handle_deltas($orderbook['bids'], $this->safe_list($data, 'bids', array())); $timestamp = $this->safe_integer($message, 'ts'); $orderbook['timestamp'] = $timestamp; $orderbook['datetime'] = $this->iso8601($timestamp); return $orderbook; } public function handle_delta(mixed $bookside, mixed $delta) { $price = $this->safe_float_2($delta, 'price', 0); $amount = $this->safe_float_2($delta, 'quantity', 1); $bookside->store($price, $amount); } public function handle_deltas(mixed $bookside, array $deltas) { for ($i = 0; $i < count($deltas); $i++) { $this->handle_delta($bookside, $deltas[$i]); } } public function watch_ticker(string $symbol, $params = array()): PromiseInterface { return Async\async(self::do_watch_ticker(...))($symbol, $params); } private function do_watch_ticker(string $symbol, $params = array()) { /** * watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific $market * @param {string} $symbol unified $symbol of the $market to fetch the ticker for * @param {array} [$params] extra parameters specific to the exchange API endpoint * @return {array} a ~@link https://docs.ccxt.com/?id=ticker-structure ticker structure~ */ if ($this->markets === null) { Async\await($this->load_markets()); } $name = 'ticker'; $market = $this->market($symbol); $marketId = $this->safe_string($market, 'id', ''); $topic = $marketId . '@' . $name; $request = array( 'event' => 'subscribe', 'topic' => $topic, ); $message = $this->extend($request, $params); return Async\await($this->watch_public($topic, $message)); } public function un_watch_ticker(string $symbol, $params = array()): PromiseInterface { return Async\async(self::do_un_watch_ticker(...))($symbol, $params); } private function do_un_watch_ticker(string $symbol, $params = array()) { /** * unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific $market * @param {string} $symbol unified $symbol of the $market to fetch the ticker for * @param {array} [$params] extra parameters specific to the exchange API endpoint * @return {array} a ~@link https://docs.ccxt.com/?id=ticker-structure ticker structure~ */ if ($this->markets === null) { Async\await($this->load_markets()); } list($method, $paramsMethod) = $this->handle_option_string_and_params($params, 'watchTicker', 'method', 'ticker'); $market = $this->market($symbol); $marketId = $this->safe_string($market, 'id', ''); $subHash = $marketId . '@' . $method; $topic = 'ticker'; return Async\await($this->unwatch_public($subHash, $market['symbol'], $topic, $paramsMethod)); } public function parse_ws_ticker(array $ticker, ?array $market = null): array { // // { // "symbol": "PERP_BTC_USDT", // "open": 19441.5, // "close": 20147.07, // "high": 20761.87, // "low": 19320.54, // "volume": 2481.103, // "amount": 50037935.0286, // "count": 3689 // } // return $this->safe_ticker(array( 'symbol' => $this->safe_symbol(null, $market), 'timestamp' => null, 'datetime' => null, 'high' => $this->safe_string($ticker, 'high'), 'low' => $this->safe_string($ticker, 'low'), 'bid' => null, 'bidVolume' => null, 'ask' => null, 'askVolume' => null, 'vwap' => null, 'open' => $this->safe_string($ticker, 'open'), 'close' => $this->safe_string($ticker, 'close'), 'last' => null, 'previousClose' => null, 'change' => null, 'percentage' => null, 'average' => null, 'baseVolume' => $this->safe_string($ticker, 'volume'), 'quoteVolume' => $this->safe_string($ticker, 'amount'), 'info' => $ticker, ), $market); } public function handle_ticker(Client $client, array $message): array { // // { // "topic": "PERP_BTC_USDT@ticker", // "ts": 1657120017000, // "data": { // "symbol": "PERP_BTC_USDT", // "open": 19441.5, // "close": 20147.07, // "high": 20761.87, // "low": 19320.54, // "volume": 2481.103, // "amount": 50037935.0286, // "count": 3689 // } // } // $data = $this->safe_dict($message, 'data', array()); $topic = $this->safe_string($message, 'topic'); $marketId = $this->safe_string($data, 'symbol'); $market = $this->safe_market($marketId); $timestamp = $this->safe_integer($message, 'ts'); $data['date'] = $timestamp; $ticker = $this->parse_ws_ticker($data, $market); $ticker['symbol'] = $market['symbol']; $this->tickers[$market['symbol']] = $ticker; $client->resolve($ticker, $topic); return $message; } public function watch_tickers(?array $symbols = null, $params = array()): PromiseInterface { return Async\async(self::do_watch_tickers(...))($symbols, $params); } private function do_watch_tickers(?array $symbols = null, $params = array()) { /** * * @see https://docs.woox.io/#24h-$tickers * * watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list * @param {string[]} $symbols unified symbol of the market to fetch the ticker for * @param {array} [$params] extra parameters specific to the exchange API endpoint * @return {array} a ~@link https://docs.ccxt.com/?id=ticker-structure ticker structure~ */ if ($this->markets === null) { Async\await($this->load_markets()); } $symbolsNormalized = $this->market_symbols($symbols); $name = 'tickers'; $topic = $name; $request = array( 'event' => 'subscribe', 'topic' => $topic, ); $message = $this->extend($request, $params); $tickers = Async\await($this->watch_public($topic, $message)); return $this->filter_by_array($tickers, 'symbol', $symbolsNormalized); } public function un_watch_tickers(?array $symbols = null, $params = array()) { return Async\async(self::do_un_watch_tickers(...))($symbols, $params); } private function do_un_watch_tickers(?array $symbols = null, $params = array()) { /** * * @see https://docs.woox.io/#24h-tickers * * stops watching a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list * @param {string[]} $symbols unified symbol of the market to stop fetching the ticker for * @param {array} [$params] extra parameters specific to the exchange API endpoint * @return {array} a ~@link https://docs.ccxt.com/?id=ticker-structure ticker structure~ */ if ($this->markets === null) { Async\await($this->load_markets()); } if ($symbols !== null) { throw new NotSupported($this->id . ' unWatchTickers() does not support a symbols argument. Only unwatch all tickers at once'); } $topic = 'ticker'; $subHash = 'tickers'; return Async\await($this->unwatch_public($subHash, null, $topic, $params)); } public function handle_tickers(Client $client, array $message) { // // { // "topic":"tickers", // "ts":1618820615000, // "data":[ // { // "symbol":"SPOT_OKB_USDT", // "open":16.297, // "close":17.183, // "high":24.707, // "low":11.997, // "volume":0, // "amount":0, // "count":0 // }, // { // "symbol":"SPOT_XRP_USDT", // "open":1.3515, // "close":1.43794, // "high":1.96674, // "low":0.39264, // "volume":750127.1, // "amount":985440.5122, // "count":396 // }, // ... // ] // } // $topic = $this->safe_string($message, 'topic'); $data = $this->safe_list($message, 'data', array()); $timestamp = $this->safe_integer($message, 'ts'); $result = array(); for ($i = 0; $i < count($data); $i++) { $marketId = $this->safe_string($data[$i], 'symbol'); $market = $this->safe_market($marketId); $ticker = $this->parse_ws_ticker($this->extend($data[$i], array( 'date' => $timestamp )), $market); $this->tickers[$market['symbol']] = $ticker; $result[] = $ticker; } $client->resolve($result, $topic); } public function watch_bids_asks(?array $symbols = null, $params = array()): PromiseInterface { return Async\async(self::do_watch_bids_asks(...))($symbols, $params); } private function do_watch_bids_asks(?array $symbols = null, $params = array()) { /** * * @see https://docs.woox.io/#bbos * * watches best bid & ask for $symbols * @param {string[]} [$symbols] unified symbol of the market to fetch the ticker for * @param {array} [$params] extra parameters specific to the exchange API endpoint * @return {array} a ~@link https://docs.ccxt.com/?id=ticker-structure ticker structure~ */ if ($this->markets === null) { Async\await($this->load_markets()); } $symbolsNormalized = $this->market_symbols($symbols); $name = 'bbos'; $topic = $name; $request = array( 'event' => 'subscribe', 'topic' => $topic, ); $message = $this->extend($request, $params); $bidsasks = Async\await($this->watch_public($topic, $message)); if ($this->newUpdates) { return $bidsasks; } return $this->filter_by_array($this->bidsasks, 'symbol', $symbolsNormalized); } public function un_watch_bids_asks(?array $symbols = null, $params = array()): PromiseInterface { return Async\async(self::do_un_watch_bids_asks(...))($symbols, $params); } private function do_un_watch_bids_asks(?array $symbols = null, $params = array()) { /** * * @see https://docs.woox.io/#bbos * * unWatches best bid & ask for $symbols * @param {string[]} [$symbols] unified symbol of the market to fetch the ticker for (not used by woo) * @param {array} [$params] extra parameters specific to the exchange API endpoint * @return {array} a ~@link https://docs.ccxt.com/?id=ticker-structure ticker structure~ */ if ($this->markets === null) { Async\await($this->load_markets()); } if ($symbols !== null) { throw new NotSupported($this->id . ' unWatchBidsAsks() does not support a symbols argument. Only unwatch all bidsAsks at once'); } $subHash = 'bbos'; $topic = 'bidsasks'; return Async\await($this->unwatch_public($subHash, null, $topic, $params)); } public function handle_bid_ask(Client $client, array $message) { // // { // "topic": "bbos", // "ts": 1618822376000, // "data": [ // { // "symbol": "SPOT_FIL_USDT", // "ask": 159.0318, // "askSize": 370.43, // "bid": 158.9158, // "bidSize": 16 // } // ] // } // $topic = $this->safe_string($message, 'topic'); $data = $this->safe_list($message, 'data', array()); $timestamp = $this->safe_integer($message, 'ts'); $result = array(); for ($i = 0; $i < count($data); $i++) { $ticker = $this->safe_dict($data, $i); if ($ticker === null) { continue; } $ticker['ts'] = $timestamp; $parsedTicker = $this->parse_ws_bid_ask($ticker); $symbol = $this->safe_string($parsedTicker, 'symbol'); if ($symbol !== null) { $this->bidsasks[$symbol] = $parsedTicker; } if ($symbol !== null) { $result[$symbol] = $parsedTicker; } } $client->resolve($result, $topic); } public function parse_ws_bid_ask(array $ticker, ?array $market = null): array { $marketId = $this->safe_string($ticker, 'symbol'); $marketResolved = $this->safe_market($marketId, $market); $symbol = $this->safe_string($marketResolved, 'symbol'); $timestamp = $this->safe_integer($ticker, 'ts'); return $this->safe_ticker(array( 'symbol' => $symbol, 'timestamp' => $timestamp, 'datetime' => $this->iso8601($timestamp), 'ask' => $this->safe_string($ticker, 'ask'), 'askVolume' => $this->safe_string($ticker, 'askSize'), 'bid' => $this->safe_string($ticker, 'bid'), 'bidVolume' => $this->safe_string($ticker, 'bidSize'), 'info' => $ticker, ), $marketResolved); } public function watch_ohlcv(string $symbol, string $timeframe = '1m', ?int $since = null, ?int $limit = null, $params = array()): PromiseInterface { return Async\async(self::do_watch_ohlcv(...))($symbol, $timeframe, $since, $limit, $params); } private function do_watch_ohlcv(string $symbol, string $timeframe = '1m', ?int $since = null, ?int $limit = null, $params = array()) { /** * watches historical candlestick data containing the open, high, low, and close price, and the volume of a $market * * @see https://docs.woox.io/#k-line * * @param {string} $symbol unified $symbol of the $market to fetch OHLCV data for * @param {string} $timeframe the length of time each candle represents * @param {int} [$since] timestamp in ms of the earliest candle to fetch * @param {int} [$limit] the maximum amount of candles to fetch * @param {array} [$params] extra parameters specific to the exchange API endpoint * @return {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume */ if ($this->markets === null) { Async\await($this->load_markets()); } if (($timeframe !== '1m') && ($timeframe !== '5m') && ($timeframe !== '15m') && ($timeframe !== '30m') && ($timeframe !== '1h') && ($timeframe !== '1d') && ($timeframe !== '1w') && ($timeframe !== '1M')) { throw new ExchangeError($this->id . ' watchOHLCV timeframe argument must be 1m, 5m, 15m, 30m, 1h, 1d, 1w, 1M'); } $market = $this->market($symbol); $marketId = $this->safe_string($market, 'id', ''); $interval = $this->safe_string($this->timeframes, $timeframe, $timeframe); $name = 'kline'; $topic = $marketId . '@' . $name . '_' . $interval; $request = array( 'event' => 'subscribe', 'topic' => $topic, ); $message = $this->extend($request, $params); $ohlcv = Async\await($this->watch_public($topic, $message)); $limitResolved = $limit; if ($this->newUpdates) { $limitResolved = $ohlcv->getLimit($market['symbol'], $limit); } return $this->filter_by_since_limit($ohlcv, $since, $limitResolved, 0, true); } public function un_watch_ohlcv(string $symbol, string $timeframe = '1m', $params = array()): PromiseInterface { return Async\async(self::do_un_watch_ohlcv(...))($symbol, $timeframe, $params); } private function do_un_watch_ohlcv(string $symbol, string $timeframe = '1m', $params = array()) { /** * unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a $market * * @see https://docs.woox.io/#k-line * * @param {string} $symbol unified $symbol of the $market * @param {string} $timeframe the length of time each candle represents * @param {array} [$params] extra parameters specific to the exchange API endpoint * @param {array} [$params->timezone] if provided, kline intervals are interpreted in that timezone instead of UTC, example '+08:00' * @return {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume */ if ($this->markets === null) { Async\await($this->load_markets()); } $market = $this->market($symbol); $marketId = $this->safe_string($market, 'id', ''); $interval = $this->safe_string($this->timeframes, $timeframe, $timeframe); $topic = 'ohlcv'; $name = 'kline'; $subHash = $marketId . '@' . $name . '_' . $interval; $params['symbolsAndTimeframes'] = array( array( $market['symbol'], $timeframe ) ); return Async\await($this->unwatch_public($subHash, $market['symbol'], $topic, $params)); } public function handle_ohlcv(Client $client, array $message) { // // { // "topic":"SPOT_BTC_USDT@kline_1m", // "ts":1618822432146, // "data":{ // "symbol":"SPOT_BTC_USDT", // "type":"1m", // "open":56948.97, // "close":56891.76, // "high":56948.97, // "low":56889.06, // "volume":44.00947568, // "amount":2504584.9, // "startTime":1618822380000, // "endTime":1618822440000 // } // } // $data = $this->safe_dict($message, 'data'); $topic = $this->safe_string($message, 'topic'); $marketId = $this->safe_string($data, 'symbol'); $market = $this->safe_market($marketId); $symbol = $market['symbol']; $interval = $this->safe_string($data, 'type'); $timeframe = $this->find_timeframe($interval); $parsed = array( $this->safe_integer($data, 'startTime'), $this->safe_float($data, 'open'), $this->safe_float($data, 'high'), $this->safe_float($data, 'low'), $this->safe_float($data, 'close'), $this->safe_float($data, 'volume'), ); $this->ohlcvs[$symbol] = $this->safe_dict($this->ohlcvs, $symbol, array()); $stored = $this->safe_value($this->safe_dict($this->ohlcvs, $symbol), $timeframe); if ($stored === null) { $limit = $this->safe_integer($this->options, 'OHLCVLimit', 1000); $stored = new ArrayCacheByTimestamp($limit); if ($symbol !== null && $timeframe !== null) { $this->ohlcvs[$symbol][$timeframe] = $stored; } } $stored->append($parsed); $client->resolve($stored, $topic); } public function watch_trades(string $symbol, ?int $since = null, ?int $limit = null, $params = array()): PromiseInterface { return Async\async(self::do_watch_trades(...))($symbol, $since, $limit, $params); } private function do_watch_trades(string $symbol, ?int $since = null, ?int $limit = null, $params = array()) { /** * watches information on multiple $trades made in a $market * * @see https://docs.woox.io/#trade * * @param {string} $symbol unified $market $symbol of the $market $trades were made in * @param {int} [$since] the earliest time in ms to fetch $trades for * @param {int} [$limit] the maximum number of trade structures to retrieve * @param {array} [$params] extra parameters specific to the exchange API endpoint * @return {array[]} a list of ~@link https://docs.ccxt.com/?id=trade-structure trade structures~ */ if ($this->markets === null) { Async\await($this->load_markets()); } $market = $this->market($symbol); $symbolValue = $this->safe_string($market, 'symbol'); $marketId = $this->safe_string($market, 'id', ''); $topic = $marketId . '@trade'; $request = array( 'event' => 'subscribe', 'topic' => $topic, ); $message = $this->extend($request, $params); $trades = Async\await($this->watch_public($topic, $message)); $limitResolved = $limit; if ($this->newUpdates) { $limitResolved = $trades->getLimit($market['symbol'], $limit); } return $this->filter_by_symbol_since_limit($trades, $symbolValue, $since, $limitResolved, true); } public function un_watch_trades(string $symbol, $params = array()): PromiseInterface { return Async\async(self::do_un_watch_trades(...))($symbol, $params); } private function do_un_watch_trades(string $symbol, $params = array()) { /** * unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list * * @see https://docs.woox.io/#trade * * @param {string} $symbol unified $symbol of the $market to fetch the ticker for * @param {array} [$params] extra parameters specific to the exchange API endpoint * @return {array} a ~@link https://docs.ccxt.com/?id=ticker-structure ticker structure~ */ if ($this->markets === null) { Async\await($this->load_markets()); } $market = $this->market($symbol); $marketId = $this->safe_string($market, 'id', ''); $topic = 'trades'; $subHash = $marketId . '@trade'; return Async\await($this->unwatch_public($subHash, $market['symbol'], $topic, $params)); } public function handle_trade(Client $client, array $message) { // // { // "topic":"SPOT_ADA_USDT@trade", // "ts":1618820361552, // "data":{ // "symbol":"SPOT_ADA_USDT", // "price":1.27988, // "size":300, // "side":"BUY", // "source":0 // } // } // $topic = $this->safe_string($message, 'topic'); $timestamp = $this->safe_integer($message, 'ts'); $data = $this->safe_dict($message, 'data'); $marketId = $this->safe_string($data, 'symbol'); $market = $this->safe_market($marketId); $symbol = $market['symbol']; $trade = $this->parse_ws_trade($this->extend($data, array( 'timestamp' => $timestamp )), $market); $tradesArray = $this->safe_value($this->trades, $symbol); if ($tradesArray === null) { $limit = $this->safe_integer($this->options, 'tradesLimit', 1000); $tradesArray = new ArrayCache($limit); } $tradesArray->append($trade); $this->trades[$symbol] = $tradesArray; $client->resolve($tradesArray, $topic); } public function parse_ws_trade(array $trade, ?array $market = null): array { // // { // "symbol":"SPOT_ADA_USDT", // "timestamp":1618820361552, // "price":1.27988, // "size":300, // "side":"BUY", // "source":0 // } // private trade // { // "msgType": 0, // execution report // "symbol": "SPOT_BTC_USDT", // "clientOrderId": 0, // "orderId": 54774393, // "type": "MARKET", // "side": "BUY", // "quantity": 0.0, // "price": 0.0, // "tradeId": 56201985, // "executedPrice": 23534.06, // "executedQuantity": 0.00040791, // "fee": 2.1E-7, // "feeAsset": "BTC", // "totalExecutedQuantity": 0.00040791, // "avgPrice": 23534.06, // "status": "FILLED", // "reason": "", // "orderTag": "default", // "totalFee": 2.1E-7, // "feeCurrency": "BTC", // "totalRebate": 0, // "rebateCurrency": "USDT", // "visible": 0.0, // "timestamp": 1675406261689, // "reduceOnly": false, // "maker": false // } // $marketId = $this->safe_string($trade, 'symbol'); $marketResolved = $this->safe_market($marketId, $market); $symbol = $this->safe_string($marketResolved, 'symbol'); $price = $this->safe_string_2($trade, 'executedPrice', 'price'); $amount = $this->safe_string_2($trade, 'executedQuantity', 'size'); $cost = Precise::string_mul($price, $amount); $side = $this->safe_string_lower($trade, 'side'); $timestamp = $this->safe_integer($trade, 'timestamp'); $maker = $this->safe_bool($trade, 'maker'); $takerOrMaker = null; if ($maker !== null) { $takerOrMaker = $maker ? 'maker' : 'taker'; } $type = $this->safe_string_lower($trade, 'type'); $fee = null; $feeCost = $this->safe_number($trade, 'fee'); if ($feeCost !== null) { $fee = array( 'cost' => $feeCost, 'currency' => $this->safe_currency_code($this->safe_string($trade, 'feeCurrency')), ); } return $this->safe_trade(array( 'id' => $this->safe_string($trade, 'tradeId'), 'timestamp' => $timestamp, 'datetime' => $this->iso8601($timestamp), 'symbol' => $symbol, 'side' => $side, 'price' => $price, 'amount' => $amount, 'cost' => $cost, 'order' => $this->safe_string($trade, 'orderId'), 'takerOrMaker' => $takerOrMaker, 'type' => $type, 'fee' => $fee, 'info' => $trade, ), $marketResolved); } public function check_required_uid($error = true): bool { if (($this->uid === null) || ($this->uid === '')) { if ($error) { throw new AuthenticationError($this->id . ' requires `uid` credential (woox calls it `application_id`)'); } else { return false; } } return true; } public function authenticate($params = array()) { return Async\async(self::do_authenticate(...))($params); } private function do_authenticate($params = array()) { $this->check_required_credentials(); $apiUrl = $this->safe_string($this->urls['api']['ws'], 'private', ''); $url = $apiUrl . '/' . $this->uid; $client = $this->client($url); $messageHash = 'authenticated'; $event = 'auth'; $future = $client->reusableFuture($messageHash); $authenticated = $this->safe_value($client->subscriptions, $messageHash); if ($authenticated === null) { $ts = (string) $this->nonce(); $auth = '|' . $ts; $signature = $this->hmac($this->encode($auth), $this->encode($this->secret), 'sha256'); $request = array( 'event' => $event, 'params' => array( 'apikey' => $this->apiKey, 'sign' => $signature, 'timestamp' => $ts, ), ); $message = $this->extend($request, $params); $this->watch($url, $messageHash, $message, $messageHash, $message); } return Async\await($future); } public function watch_private(string $messageHash, array $message, $params = array()) { return Async\async(self::do_watch_private(...))($messageHash, $message, $params); } private function do_watch_private(string $messageHash, array $message, $params = array()) { Async\await($this->authenticate($params)); $apiUrl = $this->safe_string($this->urls['api']['ws'], 'private', ''); $url = $apiUrl . '/' . $this->uid; $requestId = $this->request_id($url); $subscribe = array( 'id' => $requestId, ); $request = $this->extend($subscribe, $message); return Async\await($this->watch($url, $messageHash, $request, $messageHash, $subscribe)); } public function watch_private_multiple(array $messageHashes, array $message, $params = array()) { return Async\async(self::do_watch_private_multiple(...))($messageHashes, $message, $params); } private function do_watch_private_multiple(array $messageHashes, array $message, $params = array()) { Async\await($this->authenticate($params)); $apiUrl = $this->safe_string($this->urls['api']['ws'], 'private', ''); $url = $apiUrl . '/' . $this->uid; $requestId = $this->request_id($url); $subscribe = array( 'id' => $requestId, ); $request = $this->extend($subscribe, $message); return Async\await($this->watch_multiple($url, $messageHashes, $request, $messageHashes, $subscribe)); } public function watch_orders(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array()): PromiseInterface { return Async\async(self::do_watch_orders(...))($symbol, $since, $limit, $params); } private function do_watch_orders(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array()) { /** * * @see https://docs.woox.io/#executionreport * @see https://docs.woox.io/#algoexecutionreportv2 * * watches information on multiple $orders made by the user * @param {string} $symbol unified market $symbol of the market $orders were made in * @param {int} [$since] the earliest time in ms to fetch $orders for * @param {int} [$limit] the maximum number of order structures to retrieve * @param {array} [$params] extra parameters specific to the exchange API endpoint * @param {bool} [$params->trigger] true if $trigger order * @return {array[]} a list of ~@link https://docs.ccxt.com/?id=order-structure order structures~ */ if ($this->markets === null) { Async\await($this->load_markets()); } $trigger = $this->safe_bool_2($params, 'stop', 'trigger', false); $topic = 'executionreport'; if ($trigger) { $topic = 'algoexecutionreportv2'; } $paramsOmitted = $this->omit($params, array( 'stop', 'trigger' )); $messageHash = $topic; $symbolResolved = null; if ($symbol !== null) { $symbolResolved = $this->symbol($symbol); $messageHash = $topic . ':' . $symbolResolved; } $request = array( 'event' => 'subscribe', 'topic' => $topic, ); $message = $this->extend($request, $paramsOmitted); $orders = Async\await($this->watch_private($messageHash, $message)); $limitResolved = $limit; if ($this->newUpdates) { $limitResolved = $orders->getLimit($symbolResolved, $limit); } return $this->filter_by_symbol_since_limit($orders, $symbolResolved, $since, $limitResolved, true); } public function watch_my_trades(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array()): PromiseInterface { return Async\async(self::do_watch_my_trades(...))($symbol, $since, $limit, $params); } private function do_watch_my_trades(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array()) { /** * * @see https://docs.woox.io/#executionreport * @see https://docs.woox.io/#algoexecutionreportv2 * * watches information on multiple $trades made by the user * @param {string} $symbol unified market $symbol of the market orders were made in * @param {int} [$since] the earliest time in ms to fetch orders for * @param {int} [$limit] the maximum number of order structures to retrieve * @param {array} [$params] extra parameters specific to the exchange API endpoint * @param {bool} [$params->trigger] true if $trigger order * @return {array[]} a list of ~@link https://docs.ccxt.com/?id=trade-structure trade structures~ */ if ($this->markets === null) { Async\await($this->load_markets()); } $trigger = $this->safe_bool_2($params, 'stop', 'trigger', false); $topic = 'executionreport'; if ($trigger) { $topic = 'algoexecutionreportv2'; } $paramsOmitted = $this->omit($params, array( 'stop', 'trigger' )); $messageHash = 'myTrades'; $symbolResolved = null; if ($symbol !== null) { $symbolResolved = $this->symbol($symbol); $messageHash = 'myTrades' . ':' . $symbolResolved; } $request = array( 'event' => 'subscribe', 'topic' => $topic, ); $message = $this->extend($request, $paramsOmitted); $trades = Async\await($this->watch_private($messageHash, $message)); $limitResolved = $limit; if ($this->newUpdates) { $limitResolved = $trades->getLimit($symbolResolved, $limit); } return $this->filter_by_symbol_since_limit($trades, $symbolResolved, $since, $limitResolved, true); } public function parse_ws_order(array $order, ?array $market = null): array { // // { // "symbol": "PERP_BTC_USDT", // "clientOrderId": 0, // "orderId": 52952826, // "type": "LIMIT", // "side": "SELL", // "quantity": 0.01, // "price": 22000, // "tradeId": 0, // "executedPrice": 0, // "executedQuantity": 0, // "fee": 0, // "feeAsset": "USDT", // "totalExecutedQuantity": 0, // "status": "NEW", // "reason": '', // "orderTag": "default", // "totalFee": 0, // "visible": 0.01, // "timestamp": 1657515556798, // "reduceOnly": false, // "maker": false // } // { // "symbol": "SPOT_BTC_USDT", // "rootAlgoOrderId": 2573778, // "parentAlgoOrderId": 0, // "algoOrderId": 2573778, // "clientOrderId": 0, // "orderTag": "default", // "algoType": "STOP_LOSS", // "side": "SELL", // "quantity": 0.00011, // "triggerPrice": 98566.67, // "triggerStatus": "USELESS", // "price": 0, // "type": "MARKET", // "triggerTradePrice": 0, // "triggerTime": 0, // "tradeId": 0, // "executedPrice": 0, // "executedQuantity": 0, // "fee": 0, // "reason": "", // "feeAsset": "", // "totalExecutedQuantity": 0, // "averageExecutedPrice": 0, // "totalFee": 0, // "timestamp": 1761030467426, // "visibleQuantity": 0, // "reduceOnly": false, // "triggerPriceType": "MARKET_PRICE", // "positionSide": "BOTH", // "feeCurrency": "", // "totalRebate": 0.0, // "rebateCurrency": "", // "triggered": false, // "maker": false, // "activated": false, // "isTriggered": false, // "isMaker": false, // "isActivated": false, // "rootAlgoStatus": "NEW", // "algoStatus": "NEW" // } // $orderId = $this->safe_string_2($order, 'orderId', 'algoOrderId'); $marketId = $this->safe_string($order, 'symbol'); $marketResolved = $this->market($marketId); $symbol = $this->safe_string($marketResolved, 'symbol'); $timestamp = $this->safe_integer($order, 'timestamp'); $fee = array( 'cost' => $this->safe_string($order, 'totalFee'), 'currency' => $this->safe_string($order, 'feeAsset'), ); $priceString = $this->safe_string($order, 'price'); $price = $this->safe_number($order, 'price'); $avgPrice = $this->safe_number($order, 'avgPrice'); if (Precise::string_eq($priceString, '0') && ($avgPrice !== null)) { $price = $avgPrice; } $amount = $this->safe_string($order, 'quantity'); $side = $this->safe_string_lower($order, 'side'); $type = $this->safe_string_lower($order, 'type'); $filled = $this->safe_string_2($order, 'totalExecutedQuantity', 'executed'); $rawStatus = $this->safe_string_2($order, 'status', 'algoStatus'); $status = $this->parse_order_status($rawStatus); $trades = null; $clientOrderId = $this->safe_string($order, 'clientOrderId'); $triggerPrice = $this->safe_string($order, 'triggerPrice'); return $this->safe_order(array( 'info' => $order, 'symbol' => $symbol, 'id' => $orderId, 'clientOrderId' => $clientOrderId, 'timestamp' => $timestamp, 'datetime' => $this->iso8601($timestamp), 'lastTradeTimestamp' => $timestamp, 'type' => $type, 'timeInForce' => null, 'postOnly' => null, 'side' => $side, 'price' => $price, 'stopPrice' => $triggerPrice, 'triggerPrice' => $triggerPrice, 'reduceOnly' => $this->safe_bool($order, 'reduceOnly'), 'amount' => $amount, 'cost' => null, 'average' => $avgPrice, 'filled' => $filled, 'remaining' => null, 'status' => $status, 'fee' => $fee, 'trades' => $trades, )); } public function handle_order_update(Client $client, array $message) { // // { // "topic": "executionreport", // "ts": 1657515556799, // "data": { // "symbol": "PERP_BTC_USDT", // "clientOrderId": 0, // "orderId": 52952826, // "type": "LIMIT", // "side": "SELL", // "quantity": 0.01, // "price": 22000, // "tradeId": 0, // "executedPrice": 0, // "executedQuantity": 0, // "fee": 0, // "feeAsset": "USDT", // "totalExecutedQuantity": 0, // "status": "NEW", // "reason": '', // "orderTag": "default", // "totalFee": 0, // "visible": 0.01, // "timestamp": 1657515556799, // "reduceOnly": false, // "maker": false // } // } // $topic = $this->safe_string($message, 'topic'); $data = $this->safe_value($message, 'data'); if ((gettype($data) === 'array' && array_keys($data) === array_keys(array_keys($data)))) { // algoexecutionreportv2 for ($i = 0; $i < count($data); $i++) { $order = $data[$i]; $tradeId = $this->omit_zero($this->safe_string($data, 'tradeId')); if ($tradeId !== null) { $this->handle_my_trade($client, $order); } $this->handle_order($client, $order, $topic); } } else { // executionreport $tradeId = $this->omit_zero($this->safe_string($data, 'tradeId')); if ($tradeId !== null) { $this->handle_my_trade($client, $data); } $this->handle_order($client, $data, $topic); } } public function handle_order(Client $client, array $message, ?string $topic) { $parsed = $this->parse_ws_order($message); $symbol = $this->safe_string($parsed, 'symbol'); $orderId = $this->safe_string($parsed, 'id'); if ($symbol !== null) { if ($this->orders === null) { $limit = $this->safe_integer($this->options, 'ordersLimit', 1000); $this->orders = new ArrayCacheBySymbolById($limit); } $cachedOrders = $this->orders; $orders = $this->safe_dict($cachedOrders->hashmap, $symbol, array()); $order = $this->safe_dict($orders, $orderId); if ($order !== null) { $fee = $this->safe_value($order, 'fee'); if ($fee !== null) { $parsed['fee'] = $fee; } $fees = $this->safe_list($order, 'fees'); if ($fees !== null) { $parsed['fees'] = $fees; } $parsed['trades'] = $this->safe_value($order, 'trades'); $parsed['timestamp'] = $this->safe_integer($order, 'timestamp'); $parsed['datetime'] = $this->safe_string($order, 'datetime'); } $cachedOrders->append($parsed); $client->resolve($this->orders, $topic); $messageHashSymbol = $topic . ':' . $symbol; $client->resolve($this->orders, $messageHashSymbol); } } public function handle_my_trade(Client $client, array $message) { // // { // "msgType": 0, // execution report // "symbol": "SPOT_BTC_USDT", // "clientOrderId": 0, // "orderId": 54774393, // "type": "MARKET", // "side": "BUY", // "quantity": 0.0, // "price": 0.0, // "tradeId": 56201985, // "executedPrice": 23534.06, // "executedQuantity": 0.00040791, // "fee": 2.1E-7, // "feeAsset": "BTC", // "totalExecutedQuantity": 0.00040791, // "avgPrice": 23534.06, // "status": "FILLED", // "reason": "", // "orderTag": "default", // "totalFee": 2.1E-7, // "feeCurrency": "BTC", // "totalRebate": 0, // "rebateCurrency": "USDT", // "visible": 0.0, // "timestamp": 1675406261689, // "reduceOnly": false, // "maker": false // } // $myTrades = $this->myTrades; if ($myTrades === null) { $limit = $this->safe_integer($this->options, 'tradesLimit', 1000); $myTrades = new ArrayCacheBySymbolById($limit); } $trade = $this->parse_ws_trade($message); $myTrades->append($trade); $tradeSymbol = $this->safe_string($trade, 'symbol', ''); $messageHash = 'myTrades:' . $tradeSymbol; $client->resolve($myTrades, $messageHash); $messageHash = 'myTrades'; $client->resolve($myTrades, $messageHash); } public function watch_positions(?array $symbols = null, ?int $since = null, ?int $limit = null, $params = array()): PromiseInterface { return Async\async(self::do_watch_positions(...))($symbols, $since, $limit, $params); } private function do_watch_positions(?array $symbols = null, ?int $since = null, ?int $limit = null, $params = array()) { /** * * @see https://docs.woox.io/#position-push * * watch all open positions * @param {string[]} [$symbols] list of unified market $symbols * @param {int} [$since] timestamp in ms of the earliest position to fetch * @param {int} [$limit] the maximum number of positions to fetch * @param {array} [$params] extra parameters specific to the exchange API endpoint * @return {array[]} a list of {@link https://docs.ccxt.com/en/latest/manual.html#position-structure position structure} */ if ($this->markets === null) { Async\await($this->load_markets()); } $messageHashes = array(); $symbolsNormalized = $this->market_symbols($symbols); if (!$this->is_empty($symbolsNormalized)) { if ($symbolsNormalized === null) { throw new ArgumentsRequired($this->id . ' watchPositions() symbols is required'); } for ($i = 0; $i < count($symbolsNormalized); $i++) { if ($symbolsNormalized === null) { throw new ArgumentsRequired($this->id . ' watchPositions() symbols is required'); } $symbol = $symbolsNormalized[$i]; $messageHashes[] = 'positions::' . $symbol; } } else { $messageHashes[] = 'positions'; } $apiUrl = $this->safe_string($this->urls['api']['ws'], 'private', ''); $url = $apiUrl . '/' . $this->uid; $client = $this->client($url); $this->set_positions_cache($client, $symbolsNormalized); $fetchPositionsSnapshot = $this->handle_option('watchPositions', 'fetchPositionsSnapshot', true); $awaitPositionsSnapshot = $this->handle_option('watchPositions', 'awaitPositionsSnapshot', true); if (($fetchPositionsSnapshot === true) && ($awaitPositionsSnapshot === true) && ($this->positions === null)) { $snapshot = Async\await($client->future('fetchPositionsSnapshot')); return $this->filter_by_symbols_since_limit($snapshot, $symbolsNormalized, $since, $limit, true); } $request = array( 'event' => 'subscribe', 'topic' => 'position', ); $newPositions = Async\await($this->watch_private_multiple($messageHashes, $request, $params)); if ($this->newUpdates) { return $newPositions; } return $this->filter_by_symbols_since_limit($this->positions, $symbolsNormalized, $since, $limit, true); } public function set_positions_cache(Client $client, mixed $type, ?array $symbols = null) { $fetchPositionsSnapshot = $this->handle_option('watchPositions', 'fetchPositionsSnapshot', false); if ($fetchPositionsSnapshot === true) { $messageHash = 'fetchPositionsSnapshot'; if (!(is_array($client->futures) && array_key_exists($messageHash ?? '', $client->futures))) { $client->future($messageHash); $this->spawn(array($this, 'load_positions_snapshot'), $client, $messageHash); } } else { $this->positions = new ArrayCacheBySymbolBySide(); } } public function load_positions_snapshot(Client $client, string $messageHash) { return Async\async(self::do_load_positions_snapshot(...))($client, $messageHash); } private function do_load_positions_snapshot(Client $client, string $messageHash) { $positions = Async\await($this->fetch_positions()); $this->positions = new ArrayCacheBySymbolBySide(); $cache = $this->positions; for ($i = 0; $i < count($positions); $i++) { $position = $positions[$i]; $contracts = $this->safe_number($position, 'contracts', 0); if (($contracts !== null) && ($contracts > 0)) { $cache->append($position); } } // don't remove the future from the .futures cache if (is_array($client->futures) && array_key_exists($messageHash ?? '', $client->futures)) { $future = $client->futures[$messageHash]; $future->resolve($cache); $client->resolve($cache, 'positions'); } } public function handle_positions(Client $client, array $message) { // // { // "topic":"position", // "ts":1705292345255, // "data":{ // "positions":{ // "PERP_LTC_USDT":{ // "holding":1, // "pendingLongQty":0, // "pendingShortQty":0, // "averageOpenPrice":71.53, // "pnl24H":0, // "fee24H":0.07153, // "settlePrice":71.53, // "markPrice":71.32098452065145, // "version":7886, // "openingTime":1705292304267, // "pnl24HPercentage":0, // "adlQuantile":1, // "positionSide":"BOTH" // } // } // } // } // $data = $this->safe_dict($message, 'data', array()); $rawPositions = $this->safe_dict($data, 'positions', array()); $postitionsIds = is_array($rawPositions) ? array_keys($rawPositions) : array(); if ($this->positions === null) { $this->positions = new ArrayCacheBySymbolBySide(); } $cache = $this->positions; $newPositions = array(); for ($i = 0; $i < count($postitionsIds); $i++) { $marketId = $postitionsIds[$i]; $market = $this->safe_market($marketId); $rawPosition = $rawPositions[$marketId]; $position = $this->parse_position($rawPosition, $market); $newPositions[] = $position; $cache->append($position); $marketSymbol = $this->safe_string($market, 'symbol', ''); $messageHash = 'positions::' . $marketSymbol; $client->resolve($position, $messageHash); } $client->resolve($newPositions, 'positions'); } public function watch_balance($params = array()): PromiseInterface { return Async\async(self::do_watch_balance(...))($params); } private function do_watch_balance($params = array()) { /** * * @see https://docs.woox.io/#balance * * watch balance and get the amount of funds available for trading or funds locked in orders * @param {array} [$params] extra parameters specific to the exchange API endpoint * @return {array} a ~@link https://docs.ccxt.com/?id=balance-structure balance structure~ */ if ($this->markets === null) { Async\await($this->load_markets()); } $topic = 'balance'; $messageHash = $topic; $request = array( 'event' => 'subscribe', 'topic' => $topic, ); $message = $this->extend($request, $params); return Async\await($this->watch_private($messageHash, $message)); } public function handle_balance(Client $client, array $message) { // // { // "topic": "balance", // "ts": 1695716888789, // "data": { // "balances": { // "USDT": { // "holding": 266.56059176, // "frozen": 0, // "interest": 0, // "pendingShortQty": 0, // "pendingExposure": 0, // "pendingLongQty": 0, // "pendingLongExposure": 0, // "version": 37, // "staked": 0, // "unbonding": 0, // "vault": 0, // "averageOpenPrice": 0, // "pnl24H": 0, // "fee24H": 0, // "markPrice": 1, // "pnl24HPercentage": 0 // } // } // // } // $data = $this->safe_dict($message, 'data'); $balances = $this->safe_dict($data, 'balances', array()); $keys = is_array($balances) ? array_keys($balances) : array(); $ts = $this->safe_integer($message, 'ts'); $this->balance['info'] = $data; $this->balance['timestamp'] = $ts; $this->balance['datetime'] = $this->iso8601($ts); for ($i = 0; $i < count($keys); $i++) { $key = $keys[$i]; $value = $this->safe_dict($balances, $key); $code = $this->safe_currency_code($key); $account = $this->account(); $total = $this->safe_string($value, 'holding'); $used = $this->safe_string($value, 'frozen'); $account['total'] = $total; $account['used'] = $used; $account['free'] = Precise::string_sub($total, $used); if ($code !== null) { $this->balance[$code] = $this->extend($this->safe_dict($this->balance, $code, array()), $account); } } $this->balance = $this->safe_balance($this->balance); $client->resolve($this->balance, 'balance'); } public function watch_funding_rate(string $symbol, $params = array()): PromiseInterface { return Async\async(self::do_watch_funding_rate(...))($symbol, $params); } private function do_watch_funding_rate(string $symbol, $params = array()) { /** * watch the current funding rate * * @see https://docs.woox.io/#estfundingrate * * @param {string} $symbol unified $market $symbol * @param {array} [$params] extra parameters specific to the exchange API endpoint * @return {array} a ~@link https://docs.ccxt.com/?id=funding-rate-structure funding rate structure~ */ if ($this->markets === null) { Async\await($this->load_markets()); } $market = $this->market($symbol); $marketId = $this->safe_string($market, 'id', ''); $topic = $marketId . '@estfundingrate'; $request = array( 'event' => 'subscribe', 'topic' => $topic, ); $message = $this->extend($request, $params); return Async\await($this->watch_public($topic, $message)); } public function handle_funding_rate(Client $client, array $message) { // // { // "topic": "PERP_BTC_USDT@estfundingrate", // "ts": 1771484159016, // "data": { // "symbol": "PERP_BTC_USDT", // "fundingRate": 0.0001, // "fundingTs": 1771488000000 // } // } // $data = $this->safe_dict($message, 'data', array()); $fundingRate = $this->parse_funding_rate($data); $symbol = $this->safe_string($fundingRate, 'symbol'); if ($symbol !== null) { $this->fundingRates[$symbol] = $fundingRate; } $messageHash = $this->safe_string($message, 'topic'); $client->resolve($fundingRate, $messageHash); } public function handle_error_message(Client $client, array $message): ?bool { // // {"id":"1","event":"subscribe","success":false,"ts":1710780997216,"errorMsg":"Auth is needed."} // if (!(is_array($message) && array_key_exists('success' ?? '', $message))) { return false; } $success = $this->safe_bool($message, 'success', false); if ($success) { return false; } $errorMessage = $this->safe_string($message, 'errorMsg'); try { if ($errorMessage !== null) { $feedback = $this->id . ' ' . $this->json($message); $this->throw_exactly_matched_exception($this->exceptions['exact'], $errorMessage, $feedback); } return false; } catch (Exception $error) { if ($error instanceof AuthenticationError) { $messageHash = 'authenticated'; $client->reject($error, $messageHash); if (is_array($client->subscriptions) && array_key_exists($messageHash ?? '', $client->subscriptions)) { unset($client->subscriptions[$messageHash]); } } else { $client->reject($error); } return true; } } public function handle_un_subscription(Client $client, array $message) { // // { // "id": "2", // "event": "unsubscribe", // "success": true, // "ts": 1759568478343, // "data": "SPOT_BTC_USDT@orderbook" // } // $subscribeHash = $this->safe_string($message, 'data', ''); $unsubscribeHash = 'unsubscribe::' . $subscribeHash; $subscription = $this->safe_dict($client->subscriptions, $unsubscribeHash, array()); $subMessageHashes = $this->safe_list($subscription, 'subMessageHashes', array()); $unsubMessageHashes = $this->safe_list($subscription, 'unsubMessageHashes', array()); for ($i = 0; $i < count($subMessageHashes); $i++) { $subHash = $subMessageHashes[$i]; $unsubHash = $unsubMessageHashes[$i]; $this->clean_unsubscription($client, $subHash, $unsubHash); } $this->clean_cache($subscription); } public function handle_message(Client $client, array $message) { if ($this->handle_error_message($client, $message) === true) { return; } $methods = array( 'ping' => array($this, 'handle_ping'), 'pong' => array($this, 'handle_pong'), 'subscribe' => array($this, 'handle_subscribe'), 'unsubscribe' => array($this, 'handle_un_subscription'), 'orderbook' => array($this, 'handle_order_book'), 'orderbookupdate' => array($this, 'handle_order_book'), 'ticker' => array($this, 'handle_ticker'), 'tickers' => array($this, 'handle_tickers'), 'kline' => array($this, 'handle_ohlcv'), 'auth' => array($this, 'handle_auth'), 'executionreport' => array($this, 'handle_order_update'), 'algoexecutionreportv2' => array($this, 'handle_order_update'), 'trade' => array($this, 'handle_trade'), 'balance' => array($this, 'handle_balance'), 'position' => array($this, 'handle_positions'), 'bbos' => array($this, 'handle_bid_ask'), 'estfundingrate' => array($this, 'handle_funding_rate'), ); $event = $this->safe_string($message, 'event'); $method = $this->safe_value($methods, $event); if ($method !== null) { $method($client, $message); return; } $topic = $this->safe_string($message, 'topic'); if ($topic !== null) { $method = $this->safe_value($methods, $topic); if ($method !== null) { $method($client, $message); return; } $splitTopic = explode('@', $topic); $splitLength = count($splitTopic); if ($splitLength === 2) { $name = $this->safe_string($splitTopic, 1); if ($name === null) { return; } $method = $this->safe_value($methods, $name); if ($method !== null) { $method($client, $message); return; } $splitName = explode('_', $name); $splitNameLength = count($splitTopic); if ($splitNameLength === 2) { $method = $this->safe_value($methods, $this->safe_string($splitName, 0)); if ($method !== null) { $method($client, $message); } } } } } public function ping(Client $client): array { return array( 'event' => 'ping' ); } public function pong(Client $client, array $message) { return Async\async(self::do_pong(...))($client, $message); } private function do_pong(Client $client, array $message) { Async\await($client->send(array( 'event' => 'pong' ))); } public function handle_ping(Client $client, array $message) { $this->spawn(array($this, 'pong'), $client, $message); } public function handle_pong(Client $client, array $message): array { // // { event: "pong", ts: 1657117026090 } // $client->lastPong = $this->milliseconds(); return $message; } public function handle_subscribe(Client $client, array $message): array { // // { // "id": "666888", // "event": "subscribe", // "success": true, // "ts": 1657117712212 // } // $id = $this->safe_string($message, 'id'); $subscriptionsById = $this->index_by($client->subscriptions, 'id'); $subscription = $this->safe_dict($subscriptionsById, $id, array()); $method = $this->safe_value($subscription, 'method'); if ($method !== null) { $method($client, $message, $subscription); } return $message; } public function handle_auth(Client $client, array $message) { // // { // "event": "auth", // "success": true, // "ts": 1657463158812 // } // $messageHash = 'authenticated'; $success = $this->safe_bool($message, 'success', false); if ($success) { // client.resolve (message, messageHash); $future = $this->safe_value($client->futures, 'authenticated'); $future->resolve(true); } else { $error = new AuthenticationError($this->json($message)); $client->reject($error, $messageHash); // allows further authentication attempts if (is_array($client->subscriptions) && array_key_exists($messageHash ?? '', $client->subscriptions)) { unset($client->subscriptions['authenticated']); } } } }