# -*- coding: utf-8 -*-

# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code

import ccxt.async_support
from ccxt.async_support.base.ws.cache import ArrayCache, ArrayCacheBySymbolById, ArrayCacheByTimestamp
from ccxt.base.types import Any, Balances, Int, Order, OrderBook, Position, Str, Strings, Ticker, Tickers, Trade
from ccxt.async_support.base.ws.client import Client
from typing import List
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import ArgumentsRequired


class defx(ccxt.async_support.defx):

    def describe(self) -> Any:
        return self.deep_extend(super(defx, self).describe(), {
            'has': {
                'ws': True,
                'watchBalance': True,
                'watchTicker': True,
                'watchTickers': True,
                'watchBidsAsks': True,
                'watchTrades': True,
                'watchTradesForSymbols': True,
                'watchMyTrades': False,
                'watchOrders': True,
                'watchOrderBook': True,
                'watchOrderBookForSymbols': True,
                'watchOHLCV': True,
                'watchOHLCVForSymbols': True,
            },
            'urls': {
                'test': {
                    'ws': {
                        'public': 'wss://stream.testnet.defx.com/pricefeed',
                        'private': 'wss://ws.testnet.defx.com/user',
                    },
                },
                'api': {
                    'ws': {
                        'public': 'wss://marketfeed.api.defx.com/pricefeed',
                        'private': 'wss://userfeed.api.defx.com/user',
                    },
                },
            },
            'options': {
                'listenKeyRefreshRate': 3540000,  # 1 hour(59 mins so we have 1min to renew the token)
                'ws': {
                    'timeframes': {
                        '1m': '1m',
                        '3m': '3m',
                        '5m': '5m',
                        '15m': '15m',
                        '30m': '30m',
                        '1h': '1h',
                        '2h': '2h',
                        '4h': '4h',
                        '12h': '12h',
                        '1d': '1d',
                        '1w': '1w',
                        '1M': '1M',
                    },
                },
            },
            'streaming': {
            },
            'exceptions': {
            },
        })

    async def watch_public(self, topics, messageHashes, params={}):
        await self.load_markets()
        url = self.urls['api']['ws']['public']
        request: dict = {
            'method': 'SUBSCRIBE',
            'topics': topics,
        }
        message = self.extend(request, params)
        return await self.watch_multiple(url, messageHashes, message, messageHashes)

    async def un_watch_public(self, topics, messageHashes, params={}):
        await self.load_markets()
        url = self.urls['api']['ws']['public']
        request: dict = {
            'method': 'UNSUBSCRIBE',
            'topics': topics,
        }
        message = self.extend(request, params)
        return await self.watch_multiple(url, messageHashes, message, messageHashes)

    async def watch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
        """
        watches historical candlestick data containing the open, high, low, close price, and the volume of a market

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str 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 dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        result = await self.watch_ohlcv_for_symbols([[symbol, timeframe]], since, limit, params)
        return result[symbol][timeframe]

    async def un_watch_ohlcv(self, symbol: str, timeframe='1m', params={}) -> Any:
        """
        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        return await self.un_watch_ohlcv_for_symbols([[symbol, timeframe]], params)

    async def watch_ohlcv_for_symbols(self, symbolsAndTimeframes: List[List[str]], since: Int = None, limit: Int = None, params={}):
        """
        watches historical candlestick data containing the open, high, low, close price, and the volume of a market

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str[][] symbolsAndTimeframes: array of arrays containing unified symbols and timeframes to fetch OHLCV data for, example [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        symbolsLength = len(symbolsAndTimeframes)
        if symbolsLength == 0 or not isinstance(symbolsAndTimeframes[0], list):
            raise ArgumentsRequired(self.id + " watchOHLCVForSymbols() requires a an array of symbols and timeframes, like  [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]")
        await self.load_markets()
        topics = []
        messageHashes = []
        for i in range(0, len(symbolsAndTimeframes)):
            symbolAndTimeframe = symbolsAndTimeframes[i]
            marketId = self.safe_string(symbolAndTimeframe, 0)
            market = self.market(marketId)
            tf = self.safe_string(symbolAndTimeframe, 1)
            interval = self.safe_string(self.timeframes, tf, tf)
            topics.append('symbol:' + market['id'] + ':ohlc:' + interval)
            messageHashes.append('candles:' + interval + ':' + market['symbol'])
        symbol, timeframe, candles = await self.watch_public(topics, messageHashes, params)
        if self.newUpdates:
            limit = candles.getLimit(symbol, limit)
        filtered = self.filter_by_since_limit(candles, since, limit, 0, True)
        return self.create_ohlcv_object(symbol, timeframe, filtered)

    async def un_watch_ohlcv_for_symbols(self, symbolsAndTimeframes: List[List[str]], params={}) -> Any:
        """
        unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str[][] symbolsAndTimeframes: array of arrays containing unified symbols and timeframes to fetch OHLCV data for, example [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        symbolsLength = len(symbolsAndTimeframes)
        if symbolsLength == 0 or not isinstance(symbolsAndTimeframes[0], list):
            raise ArgumentsRequired(self.id + " unWatchOHLCVForSymbols() requires a an array of symbols and timeframes, like  [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]")
        await self.load_markets()
        topics = []
        messageHashes = []
        for i in range(0, len(symbolsAndTimeframes)):
            symbolAndTimeframe = symbolsAndTimeframes[i]
            marketId = self.safe_string(symbolAndTimeframe, 0)
            market = self.market(marketId)
            tf = self.safe_string(symbolAndTimeframe, 1)
            interval = self.safe_string(self.timeframes, tf, tf)
            topics.append('symbol:' + market['id'] + ':ohlc:' + interval)
            messageHashes.append('candles:' + interval + ':' + market['symbol'])
        return await self.un_watch_public(topics, messageHashes, params)

    def handle_ohlcv(self, client: Client, message):
        #
        # {
        #     "topic": "symbol:BTC_USDC:ohlc:3m",
        #     "event": "ohlc",
        #     "timestamp": 1730794277104,
        #     "data": {
        #         "symbol": "BTC_USDC",
        #         "window": "3m",
        #         "open": "57486.90000000",
        #         "high": "57486.90000000",
        #         "low": "57486.90000000",
        #         "close": "57486.90000000",
        #         "volume": "0.000",
        #         "quoteAssetVolume": "0.00000000",
        #         "takerBuyAssetVolume": "0.000",
        #         "takerBuyQuoteAssetVolume": "0.00000000",
        #         "numberOfTrades": 0,
        #         "start": 1730794140000,
        #         "end": 1730794320000,
        #         "isClosed": False
        #     }
        # }
        #
        data = self.safe_dict(message, 'data', {})
        marketId = self.safe_string(data, 'symbol')
        market = self.market(marketId)
        symbol = market['symbol']
        timeframe = self.safe_string(data, 'window')
        if not (symbol in self.ohlcvs):
            self.ohlcvs[symbol] = {}
        if not (timeframe in self.ohlcvs[symbol]):
            limit = self.safe_integer(self.options, 'OHLCVLimit', 1000)
            stored = ArrayCacheByTimestamp(limit)
            self.ohlcvs[symbol][timeframe] = stored
        ohlcv = self.ohlcvs[symbol][timeframe]
        parsed = self.parse_ohlcv(data)
        ohlcv.append(parsed)
        messageHash = 'candles:' + timeframe + ':' + symbol
        client.resolve([symbol, timeframe, ohlcv], messageHash)

    async def watch_ticker(self, symbol: str, params={}) -> Ticker:
        """
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        symbol = market['symbol']
        topic = 'symbol:' + market['id'] + ':24hrTicker'
        messageHash = 'ticker:' + symbol
        return await self.watch_public([topic], [messageHash], params)

    async def un_watch_ticker(self, symbol: str, params={}) -> Any:
        """
        unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.channel]: the channel to subscribe to, tickers by default. Can be tickers, sprd-tickers, index-tickers, block-tickers
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        return await self.un_watch_tickers([symbol], params)

    async def watch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
        """
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str[] [symbols]: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        await self.load_markets()
        symbols = self.market_symbols(symbols, None, False)
        topics = []
        messageHashes = []
        for i in range(0, len(symbols)):
            symbol = symbols[i]
            marketId = self.market_id(symbol)
            topics.append('symbol:' + marketId + ':24hrTicker')
            messageHashes.append('ticker:' + symbol)
        await self.watch_public(topics, messageHashes, params)
        return self.filter_by_array(self.tickers, 'symbol', symbols)

    async def un_watch_tickers(self, symbols: Strings = None, params={}) -> Any:
        """
        unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str[] [symbols]: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        await self.load_markets()
        symbols = self.market_symbols(symbols, None, False)
        topics = []
        messageHashes = []
        for i in range(0, len(symbols)):
            symbol = symbols[i]
            marketId = self.market_id(symbol)
            topics.append('symbol:' + marketId + ':24hrTicker')
            messageHashes.append('ticker:' + symbol)
        return await self.un_watch_public(topics, messageHashes, params)

    def handle_ticker(self, client: Client, message):
        #
        # {
        #     "topic": "symbol:BTC_USDC:24hrTicker",
        #     "event": "24hrTicker",
        #     "timestamp": 1730862543095,
        #     "data": {
        #         "symbol": "BTC_USDC",
        #         "priceChange": "17114.70000000",
        #         "priceChangePercent": "29.77",
        #         "weightedAvgPrice": "6853147668",
        #         "lastPrice": "74378.90000000",
        #         "lastQty": "0.107",
        #         "bestBidPrice": "61987.60000000",
        #         "bestBidQty": "0.005",
        #         "bestAskPrice": "84221.60000000",
        #         "bestAskQty": "0.015",
        #         "openPrice": "57486.90000000",
        #         "highPrice": "88942.60000000",
        #         "lowPrice": "47364.20000000",
        #         "volume": "28.980",
        #         "quoteVolume": "1986042.19424035",
        #         "openTime": 1730776080000,
        #         "closeTime": 1730862540000,
        #         "openInterestBase": "67.130",
        #         "openInterestQuote": "5008005.40800000"
        #     }
        # }
        #
        self.handle_bid_ask(client, message)
        data = self.safe_dict(message, 'data', {})
        parsedTicker = self.parse_ticker(data)
        symbol = parsedTicker['symbol']
        timestamp = self.safe_integer(message, 'timestamp')
        parsedTicker['timestamp'] = timestamp
        parsedTicker['datetime'] = self.iso8601(timestamp)
        self.tickers[symbol] = parsedTicker
        messageHash = 'ticker:' + symbol
        client.resolve(parsedTicker, messageHash)

    async def watch_bids_asks(self, symbols: Strings = None, params={}) -> Tickers:
        """
        watches best bid & ask for symbols

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str[] symbols: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        await self.load_markets()
        symbols = self.market_symbols(symbols, None, False)
        topics = []
        messageHashes = []
        for i in range(0, len(symbols)):
            symbol = symbols[i]
            marketId = self.market_id(symbol)
            topics.append('symbol:' + marketId + ':24hrTicker')
            messageHashes.append('bidask:' + symbol)
        await self.watch_public(topics, messageHashes, params)
        return self.filter_by_array(self.bidsasks, 'symbol', symbols)

    def handle_bid_ask(self, client: Client, message):
        data = self.safe_dict(message, 'data', {})
        parsedTicker = self.parse_ws_bid_ask(data)
        symbol = parsedTicker['symbol']
        timestamp = self.safe_integer(message, 'timestamp')
        parsedTicker['timestamp'] = timestamp
        parsedTicker['datetime'] = self.iso8601(timestamp)
        self.bidsasks[symbol] = parsedTicker
        messageHash = 'bidask:' + symbol
        client.resolve(parsedTicker, messageHash)

    def parse_ws_bid_ask(self, ticker, market=None):
        marketId = self.safe_string(ticker, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = self.safe_string(market, 'symbol')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': None,
            'datetime': None,
            'ask': self.safe_string(ticker, 'bestAskPrice'),
            'askVolume': self.safe_string(ticker, 'bestAskQty'),
            'bid': self.safe_string(ticker, 'bestBidPrice'),
            'bidVolume': self.safe_string(ticker, 'bestBidQty'),
            'info': ticker,
        }, market)

    async def watch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
        """
        watches information on multiple trades made in a market

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trade structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        return await self.watch_trades_for_symbols([symbol], since, limit, params)

    async def un_watch_trades(self, symbol: str, params={}) -> Any:
        """
        unWatches from the stream channel

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str symbol: unified symbol of the market to fetch trades for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        """
        return await self.un_watch_trades_for_symbols([symbol], params)

    async def watch_trades_for_symbols(self, symbols: List[str], since: Int = None, limit: Int = None, params={}) -> List[Trade]:
        """
        watches information on multiple trades made in a market

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str[] symbols: unified symbol of the market to fetch trades for
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trade structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        await self.load_markets()
        symbols = self.market_symbols(symbols)
        symbolsLength = len(symbols)
        if symbolsLength == 0:
            raise ArgumentsRequired(self.id + ' watchTradesForSymbols() requires a non-empty array of symbols')
        topics = []
        messageHashes = []
        for i in range(0, len(symbols)):
            symbol = symbols[i]
            marketId = self.market_id(symbol)
            topics.append('symbol:' + marketId + ':trades')
            messageHashes.append('trade:' + symbol)
        trades = await self.watch_public(topics, messageHashes, params)
        if self.newUpdates:
            first = self.safe_value(trades, 0)
            tradeSymbol = self.safe_string(first, 'symbol')
            limit = trades.getLimit(tradeSymbol, limit)
        return self.filter_by_since_limit(trades, since, limit, 'timestamp', True)

    async def un_watch_trades_for_symbols(self, symbols: List[str], params={}) -> Any:
        """
        unWatches from the stream channel

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str[] symbols: unified symbol of the market to fetch trades for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        """
        await self.load_markets()
        symbols = self.market_symbols(symbols)
        symbolsLength = len(symbols)
        if symbolsLength == 0:
            raise ArgumentsRequired(self.id + ' unWatchTradesForSymbols() requires a non-empty array of symbols')
        topics = []
        messageHashes = []
        for i in range(0, len(symbols)):
            symbol = symbols[i]
            marketId = self.market_id(symbol)
            topics.append('symbol:' + marketId + ':trades')
            messageHashes.append('trade:' + symbol)
        return await self.un_watch_public(topics, messageHashes, params)

    def handle_trades(self, client: Client, message):
        #
        # {
        #     "topic": "symbol:SOL_USDC:trades",
        #     "event": "trades",
        #     "timestamp": 1730967426331,
        #     "data": {
        #         "buyerMaker": True,
        #         "price": "188.38700000",
        #         "qty": "1.00",
        #         "symbol": "SOL_USDC",
        #         "timestamp": 1730967426328
        #     }
        # }
        #
        data = self.safe_dict(message, 'data', {})
        parsedTrade = self.parse_trade(data)
        symbol = parsedTrade['symbol']
        if not (symbol in self.trades):
            limit = self.safe_integer(self.options, 'tradesLimit', 1000)
            stored = ArrayCache(limit)
            self.trades[symbol] = stored
        trades = self.trades[symbol]
        trades.append(parsedTrade)
        messageHash = 'trade:' + symbol
        client.resolve(trades, messageHash)

    async def watch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
        """
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str 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 dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        """
        return await self.watch_order_book_for_symbols([symbol], limit, params)

    async def un_watch_order_book(self, symbol: str, params={}) -> Any:
        """
        unWatches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str symbol: unified array of symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        """
        return await self.un_watch_order_book_for_symbols([symbol], params)

    async def watch_order_book_for_symbols(self, symbols: List[str], limit: Int = None, params={}) -> OrderBook:
        """
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str[] symbols: unified array of symbols
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        """
        await self.load_markets()
        symbolsLength = len(symbols)
        if symbolsLength == 0:
            raise ArgumentsRequired(self.id + ' watchOrderBookForSymbols() requires a non-empty array of symbols')
        symbols = self.market_symbols(symbols)
        topics = []
        messageHashes = []
        for i in range(0, len(symbols)):
            symbol = symbols[i]
            marketId = self.market_id(symbol)
            topics.append('symbol:' + marketId + ':depth:20:0.001')
            messageHashes.append('orderbook:' + symbol)
        orderbook = await self.watch_public(topics, messageHashes, params)
        return orderbook.limit()

    async def un_watch_order_book_for_symbols(self, symbols: List[str], params={}) -> Any:
        """
        unWatches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://www.postman.com/defxcode/defx-public-apis/collection/667939a1b5d8069c13d614e9

        :param str[] symbols: unified array of symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        """
        await self.load_markets()
        symbolsLength = len(symbols)
        if symbolsLength == 0:
            raise ArgumentsRequired(self.id + ' unWatchOrderBookForSymbols() requires a non-empty array of symbols')
        symbols = self.market_symbols(symbols)
        topics = []
        messageHashes = []
        for i in range(0, len(symbols)):
            symbol = symbols[i]
            marketId = self.market_id(symbol)
            topics.append('symbol:' + marketId + ':depth:20:0.001')
            messageHashes.append('orderbook:' + symbol)
        return await self.un_watch_public(topics, messageHashes, params)

    def handle_order_book(self, client: Client, message):
        #
        # {
        #     "topic": "symbol:SOL_USDC:depth:20:0.01",
        #     "event": "depth",
        #     "timestamp": 1731030695319,
        #     "data": {
        #         "symbol": "SOL_USDC",
        #         "timestamp": 1731030695319,
        #         "lastTradeTimestamp": 1731030275258,
        #         "level": "20",
        #         "slab": "0.01",
        #         "bids": [
        #             {
        #                 "price": "198.27000000",
        #                 "qty": "1.52"
        #             }
        #         ],
        #         "asks": [
        #             {
        #                 "price": "198.44000000",
        #                 "qty": "6.61"
        #             }
        #         ]
        #     }
        # }
        #
        data = self.safe_dict(message, 'data', {})
        marketId = self.safe_string(data, 'symbol')
        market = self.market(marketId)
        symbol = market['symbol']
        timestamp = self.safe_integer(data, 'timestamp')
        snapshot = self.parse_order_book(data, symbol, timestamp, 'bids', 'asks', 'price', 'qty')
        if not (symbol in self.orderbooks):
            ob = self.order_book(snapshot)
            self.orderbooks[symbol] = ob
        orderbook = self.orderbooks[symbol]
        orderbook.reset(snapshot)
        messageHash = 'orderbook:' + symbol
        client.resolve(orderbook, messageHash)

    async def keep_alive_listen_key(self, params={}):
        listenKey = self.safe_string(self.options, 'listenKey')
        if listenKey is None:
            # A network error happened: we can't renew a listen key that does not exist.
            return
        try:
            await self.v1PrivatePutApiUsersSocketListenKeysListenKey({'listenKey': listenKey})  # self.extend the expiry
        except Exception as error:
            url = self.urls['api']['ws']['private'] + '?listenKey=' + listenKey
            client = self.client(url)
            messageHashes = list(client.futures.keys())
            for j in range(0, len(messageHashes)):
                messageHash = messageHashes[j]
                client.reject(error, messageHash)
            self.options['listenKey'] = None
            self.options['lastAuthenticatedTime'] = 0
            return
        # whether or not to schedule another listenKey keepAlive request
        listenKeyRefreshRate = self.safe_integer(self.options, 'listenKeyRefreshRate', 3540000)
        self.delay(listenKeyRefreshRate, self.keep_alive_listen_key, params)

    async def authenticate(self, params={}):
        time = self.milliseconds()
        lastAuthenticatedTime = self.safe_integer(self.options, 'lastAuthenticatedTime', 0)
        listenKeyRefreshRate = self.safe_integer(self.options, 'listenKeyRefreshRate', 3540000)  # 1 hour
        if time - lastAuthenticatedTime > listenKeyRefreshRate:
            response = await self.v1PrivatePostApiUsersSocketListenKeys()
            self.options['listenKey'] = self.safe_string(response, 'listenKey')
            self.options['lastAuthenticatedTime'] = time
            self.delay(listenKeyRefreshRate, self.keep_alive_listen_key, params)

    async def watch_balance(self, params={}) -> Balances:
        """
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://www.postman.com/defxcode/defx-public-apis/ws-raw-request/667939b2f00f79161bb47809

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        """
        await self.load_markets()
        await self.authenticate()
        baseUrl = self.urls['api']['ws']['private']
        messageHash = 'WALLET_BALANCE_UPDATE'
        url = baseUrl + '?listenKey=' + self.options['listenKey']
        return await self.watch(url, messageHash, None, messageHash)

    def handle_balance(self, client: Client, message):
        #
        # {
        #     "event": "WALLET_BALANCE_UPDATE",
        #     "timestamp": 1711015961397,
        #     "data": {
        #         "asset": "USDC", "balance": "27.64712963"
        #     }
        # }
        #
        messageHash = self.safe_string(message, 'event')
        data = self.safe_dict(message, 'data', [])
        timestamp = self.safe_integer(message, 'timestamp')
        if self.balance is None:
            self.balance = {}
        self.balance['info'] = data
        self.balance['timestamp'] = timestamp
        self.balance['datetime'] = self.iso8601(timestamp)
        currencyId = self.safe_string(data, 'asset')
        code = self.safe_currency_code(currencyId)
        account = self.balance[code] if (code in self.balance) else self.account()
        account['free'] = self.safe_string(data, 'balance')
        self.balance[code] = account
        self.balance = self.safe_balance(self.balance)
        client.resolve(self.balance, messageHash)

    async def watch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
        watches information on multiple orders made by the user

        https://www.postman.com/defxcode/defx-public-apis/ws-raw-request/667939b2f00f79161bb47809

        :param str [symbol]: unified market symbol of the market the 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 dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        await self.authenticate()
        baseUrl = self.urls['api']['ws']['private']
        messageHash = 'orders'
        if symbol is not None:
            market = self.market(symbol)
            messageHash += ':' + market['symbol']
        url = baseUrl + '?listenKey=' + self.options['listenKey']
        orders = await self.watch(url, messageHash, None, messageHash)
        if self.newUpdates:
            limit = orders.getLimit(symbol, limit)
        return self.filter_by_symbol_since_limit(orders, symbol, since, limit, True)

    def handle_order(self, client: Client, message):
        #
        # {
        #     "event": "ORDER_UPDATE",
        #     "timestamp": 1731417961446,
        #     "data": {
        #         "orderId": "766738557656630928",
        #         "symbol": "SOL_USDC",
        #         "side": "SELL",
        #         "type": "MARKET",
        #         "status": "FILLED",
        #         "clientOrderId": "0193208d-717b-7811-a80e-c036e220ad9b",
        #         "reduceOnly": False,
        #         "postOnly": False,
        #         "timeInForce": "GTC",
        #         "isTriggered": False,
        #         "createdAt": "2024-11-12T13:26:00.829Z",
        #         "updatedAt": "2024-11-12T13:26:01.436Z",
        #         "avgPrice": "209.60000000",
        #         "cumulativeQuote": "104.80000000",
        #         "totalFee": "0.05764000",
        #         "executedQty": "0.50",
        #         "origQty": "0.50",
        #         "role": "TAKER",
        #         "pnl": "0.00000000",
        #         "lastFillPnL": "0.00000000",
        #         "lastFillPrice": "209.60000000",
        #         "lastFillQty": "0.50",
        #         "linkedOrderParentType": null,
        #         "workingType": null
        #     }
        # }
        #
        channel = 'orders'
        data = self.safe_dict(message, 'data', {})
        if self.orders is None:
            limit = self.safe_integer(self.options, 'ordersLimit', 1000)
            self.orders = ArrayCacheBySymbolById(limit)
        orders = self.orders
        parsedOrder = self.parse_order(data)
        orders.append(parsedOrder)
        messageHash = channel + ':' + parsedOrder['symbol']
        client.resolve(orders, channel)
        client.resolve(orders, messageHash)

    async def watch_positions(self, symbols: Strings = None, since: Int = None, limit: Int = None, params={}) -> List[Position]:
        """
        watch all open positions

        https://www.postman.com/defxcode/defx-public-apis/ws-raw-request/667939b2f00f79161bb47809

        :param str[]|None symbols: list of unified market symbols
        :param number [since]: since timestamp
        :param number [limit]: limit
        :param dict params: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        """
        await self.load_markets()
        await self.authenticate()
        symbols = self.market_symbols(symbols)
        baseUrl = self.urls['api']['ws']['private']
        channel = 'positions'
        url = baseUrl + '?listenKey=' + self.options['listenKey']
        newPosition = None
        if symbols is not None:
            messageHashes = []
            for i in range(0, len(symbols)):
                symbol = symbols[i]
                messageHashes.append(channel + ':' + symbol)
            newPosition = await self.watch_multiple(url, messageHashes, None, messageHashes)
        else:
            newPosition = await self.watch(url, channel, None, channel)
        if self.newUpdates:
            return newPosition
        return self.filter_by_symbols_since_limit(self.positions, symbols, since, limit, True)

    def handle_positions(self, client, message):
        #
        # {
        #     "event": "POSITION_UPDATE",
        #     "timestamp": 1731417961456,
        #     "data": {
        #         "positionId": "0193208d-735d-7fe9-90bd-8bc6d6bc1eda",
        #         "createdAt": 1289847904328,
        #         "symbol": "SOL_USDC",
        #         "positionSide": "SHORT",
        #         "entryPrice": "209.60000000",
        #         "quantity": "0.50",
        #         "status": "ACTIVE",
        #         "marginAsset": "USDC",
        #         "marginAmount": "15.17475649",
        #         "realizedPnL": "0.00000000"
        #     }
        # }
        #
        channel = 'positions'
        data = self.safe_dict(message, 'data', {})
        if self.positions is None:
            self.positions = ArrayCacheBySymbolById()
        cache = self.positions
        parsedPosition = self.parse_position(data)
        timestamp = self.safe_integer(message, 'timestamp')
        parsedPosition['timestamp'] = timestamp
        parsedPosition['datetime'] = self.iso8601(timestamp)
        cache.append(parsedPosition)
        messageHash = channel + ':' + parsedPosition['symbol']
        client.resolve([parsedPosition], channel)
        client.resolve([parsedPosition], messageHash)

    def handle_message(self, client: Client, message):
        error = self.safe_string(message, 'code')
        if error is not None:
            errorMsg = self.safe_string(message, 'msg')
            raise ExchangeError(self.id + ' ' + errorMsg)
        event = self.safe_string(message, 'event')
        if event is not None:
            methods: dict = {
                'ohlc': self.handle_ohlcv,
                '24hrTicker': self.handle_ticker,
                'trades': self.handle_trades,
                'depth': self.handle_order_book,
                'WALLET_BALANCE_UPDATE': self.handle_balance,
                'ORDER_UPDATE': self.handle_order,
                'POSITION_UPDATE': self.handle_positions,
            }
            exacMethod = self.safe_value(methods, event)
            if exacMethod is not None:
                exacMethod(client, message)
