# -*- 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, ArrayCacheBySymbolBySide, ArrayCacheByTimestamp
import hashlib
from ccxt.base.types import Any, Balances, Int, Market, Num, Order, OrderBook, OrderSide, OrderType, Position, Str, Strings, Ticker, Tickers, Trade
from ccxt.async_support.base.ws.client import Client
from typing import List
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest


class oxfun(ccxt.async_support.oxfun):

    def describe(self) -> Any:
        return self.deep_extend(super(oxfun, self).describe(), {
            'has': {
                'ws': True,
                'watchTrades': True,
                'watchTradesForSymbols': True,
                'watchOrderBook': True,
                'watchOrderBookForSymbols': True,
                'watchOHLCV': True,
                'watchOHLCVForSymbols': True,
                'watchOrders': True,
                'watchMyTrades': False,
                'watchTicker': True,
                'watchTickers': True,
                'watchBidsAsks': True,
                'watchBalance': True,
                'createOrderWs': True,
                'editOrderWs': True,
                'cancelOrderWs': True,
                'cancelOrdersWs': True,
            },
            'urls': {
                'api': {
                    'ws': 'wss://api.ox.fun/v2/websocket',
                    'test': 'wss://stgapi.ox.fun/v2/websocket',
                },
            },
            'options': {
                'timeframes': {
                    '1m': '60s',
                    '3m': '180s',
                    '5m': '300s',
                    '15m': '900s',
                    '30m': '1800s',
                    '1h': '3600s',
                    '2h': '7200s',
                    '4h': '14400s',
                    '6h': '21600s',
                    '12h': '43200s',
                    '1d': '86400s',
                },
                'watchOrderBook': {
                    'channel': 'depth',  # depth, depthL5, depthL10, depthL25
                },
            },
            'streaming': {
                'ping': self.ping,
                'keepAlive': 50000,
            },
        })

    async def subscribe_multiple(self, messageHashes, argsArray, params={}):
        url = self.urls['api']['ws']
        request: dict = {
            'op': 'subscribe',
            'args': argsArray,
        }
        return await self.watch_multiple(url, messageHashes, self.extend(request, params), messageHashes)

    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://docs.ox.fun/?json#trade

        :param str symbol: unified market symbol of the market trades were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of trade structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int|str [params.tag]: If given it will be echoed in the reply and the max size of tag is 32
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        """
        return await self.watch_trades_for_symbols([symbol], since, limit, params)

    async def watch_trades_for_symbols(self, symbols: List[str], since: Int = None, limit: Int = None, params={}) -> List[Trade]:
        """
        get the list of most recent trades for a particular symbol

        https://docs.ox.fun/?json#trade

        :param str[] symbols:
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int|str [params.tag]: If given it will be echoed in the reply and the max size of tag is 32
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        """
        await self.load_markets()
        symbols = self.market_symbols(symbols, None, False)
        args = []
        messageHashes = []
        for i in range(0, len(symbols)):
            symbol = symbols[i]
            messageHash = 'trades' + ':' + symbol
            messageHashes.append(messageHash)
            marketId = self.market_id(symbol)
            arg = 'trade:' + marketId
            args.append(arg)
        trades = await self.subscribe_multiple(messageHashes, args, params)
        if self.newUpdates:
            first = self.safe_dict(trades, 0, {})
            tradeSymbol = self.safe_string(first, 'symbol')
            limit = trades.getLimit(tradeSymbol, limit)
        return self.filter_by_since_limit(trades, since, limit, 'timestamp', True)

    def handle_trades(self, client: Client, message):
        #
        #     {
        #         table: 'trade',
        #         data: [
        #             {
        #                 side: 'SELL',
        #                 quantity: '0.074',
        #                 matchType: 'TAKER',
        #                 price: '3079.5',
        #                 marketCode: 'ETH-USD-SWAP-LIN',
        #                 tradeId: '400017157974517783',
        #                 timestamp: '1716124156643'
        #             }
        #         ]
        #     }
        #
        data = self.safe_list(message, 'data', [])
        for i in range(0, len(data)):
            trade = self.safe_dict(data, i, {})
            parsedTrade = self.parse_ws_trade(trade)
            symbol = self.safe_string(parsedTrade, 'symbol')
            messageHash = 'trades:' + symbol
            if not (symbol in self.trades):
                tradesLimit = self.safe_integer(self.options, 'tradesLimit', 1000)
                self.trades[symbol] = ArrayCache(tradesLimit)
            stored = self.trades[symbol]
            stored.append(parsedTrade)
            client.resolve(stored, messageHash)

    def parse_ws_trade(self, trade, market=None) -> Trade:
        #
        #     {
        #         side: 'SELL',
        #         quantity: '0.074',
        #         matchType: 'TAKER',
        #         price: '3079.5',
        #         marketCode: 'ETH-USD-SWAP-LIN',
        #         tradeId: '400017157974517783',
        #         timestamp: '1716124156643'
        #     }
        #
        marketId = self.safe_string(trade, 'marketCode')
        market = self.safe_market(marketId, market)
        timestamp = self.safe_integer(trade, 'timestamp')
        return self.safe_trade({
            'info': trade,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': market['symbol'],
            'id': self.safe_string(trade, 'tradeId'),
            'order': None,
            'type': None,
            'takerOrMaker': self.safe_string_lower(trade, 'matchType'),
            'side': self.safe_string_lower(trade, 'side'),
            'price': self.safe_number(trade, 'price'),
            'amount': self.safe_number(trade, 'quantity'),
            'cost': None,
            'fee': None,
        })

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

        https://docs.ox.fun/?json#candles

        :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
        :param int|str [params.tag]: If given it will be echoed in the reply and the max size of tag is 32
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        await self.load_markets()
        market = self.market(symbol)
        timeframes = self.safe_dict(self.options, 'timeframes', {})
        interval = self.safe_string(timeframes, timeframe, timeframe)
        args = 'candles' + interval + ':' + market['id']
        messageHash = 'ohlcv:' + symbol + ':' + timeframe
        url = self.urls['api']['ws']
        request: dict = {
            'op': 'subscribe',
            'args': [args],
        }
        ohlcvs = await self.watch(url, messageHash, self.extend(request, params), messageHash)
        if self.newUpdates:
            limit = ohlcvs.getLimit(symbol, limit)
        return self.filter_by_since_limit(ohlcvs, since, limit, 0, True)

    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, and close price, and the volume of a market

        https://docs.ox.fun/?json#candles

        :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
        :param int|str [params.tag]: If given it will be echoed in the reply and the max size of tag is 32
        :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:OX', '1m'], ['OX/USDT', '5m']]")
        await self.load_markets()
        args = []
        messageHashes = []
        timeframes = self.safe_dict(self.options, 'timeframes', {})
        for i in range(0, len(symbolsAndTimeframes)):
            symbolAndTimeframe = symbolsAndTimeframes[i]
            sym = symbolAndTimeframe[0]
            tf = symbolAndTimeframe[1]
            marketId = self.market_id(sym)
            interval = self.safe_string(timeframes, tf, tf)
            arg = 'candles' + interval + ':' + marketId
            args.append(arg)
            messageHash = 'multi:ohlcv:' + sym + ':' + tf
            messageHashes.append(messageHash)
        symbol, timeframe, candles = await self.subscribe_multiple(messageHashes, args, 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)

    def handle_ohlcv(self, client: Client, message):
        #
        #     {
        #         "table": "candles60s",
        #         "data": [
        #             {
        #                 "marketCode": "BTC-USD-SWAP-LIN",
        #                 "candle": [
        #                     "1594313762698",  #timestamp
        #                     "9633.1",        #open
        #                     "9693.9",        #high
        #                     "9238.1",        #low
        #                     "9630.2",        #close
        #                     "45247",         #volume in OX
        #                     "5.3"            #volume in Contracts
        #                 ]
        #             }
        #         ]
        #     }
        #
        table = self.safe_string(message, 'table')
        parts = table.split('candles')
        timeframeId = self.safe_string(parts, 1, '')
        timeframe = self.find_timeframe(timeframeId)
        messageData = self.safe_list(message, 'data', [])
        data = self.safe_dict(messageData, 0, {})
        marketId = self.safe_string(data, 'marketCode')
        market = self.safe_market(marketId)
        symbol = self.safe_symbol(marketId, market)
        if not (symbol in self.ohlcvs):
            self.ohlcvs[symbol] = {}
        if not (timeframe in self.ohlcvs[symbol]):
            limit = self.safe_integer(self.options, 'OHLCVLimit', 1000)
            self.ohlcvs[symbol][timeframe] = ArrayCacheByTimestamp(limit)
        candle = self.safe_list(data, 'candle', [])
        parsed = self.parse_ws_ohlcv(candle, market)
        stored = self.ohlcvs[symbol][timeframe]
        stored.append(parsed)
        messageHash = 'ohlcv:' + symbol + ':' + timeframe
        client.resolve(stored, messageHash)
        # for multiOHLCV we need special object, to other "multi"
        # methods, because OHLCV response item does not contain symbol
        # or timeframe, thus otherwise it would be unrecognizable
        messageHashForMulti = 'multi:' + messageHash
        client.resolve([symbol, timeframe, stored], messageHashForMulti)

    def parse_ws_ohlcv(self, ohlcv, market: Market = None) -> list:
        #
        #     [
        #         "1594313762698",  #timestamp
        #         "9633.1",        #open
        #         "9693.9",        #high
        #         "9238.1",        #low
        #         "9630.2",        #close
        #         "45247",         #volume in OX
        #         "5.3"            #volume in Contracts
        #     ]
        #
        return [
            self.safe_integer(ohlcv, 0),
            self.safe_number(ohlcv, 1),
            self.safe_number(ohlcv, 2),
            self.safe_number(ohlcv, 3),
            self.safe_number(ohlcv, 4),
            self.safe_number(ohlcv, 6),
        ]

    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://docs.ox.fun/?json#fixed-size-order-book
        https://docs.ox.fun/?json#full-order-book

        :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 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://docs.ox.fun/?json#fixed-size-order-book
        https://docs.ox.fun/?json#full-order-book

        :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
        :param int|str [params.tag]: If given it will be echoed in the reply and the max size of tag is 32
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        """
        await self.load_markets()
        symbols = self.market_symbols(symbols)
        channel = 'depth'
        options = self.safe_dict(self.options, 'watchOrderBook', {})
        defaultChannel = self.safe_string(options, 'channel')
        if defaultChannel is not None:
            channel = defaultChannel
        elif limit is not None:
            if limit <= 5:
                channel = 'depthL5'
            elif limit <= 10:
                channel = 'depthL10'
            elif limit <= 25:
                channel = 'depthL25'
        args = []
        messageHashes = []
        for i in range(0, len(symbols)):
            symbol = symbols[i]
            messageHash = 'orderbook:' + symbol
            messageHashes.append(messageHash)
            marketId = self.market_id(symbol)
            arg = channel + ':' + marketId
            args.append(arg)
        orderbook = await self.subscribe_multiple(messageHashes, args, params)
        return orderbook.limit()

    def handle_order_book(self, client: Client, message):
        #
        #     {
        #         "table": "depth",
        #         "data": {
        #             "seqNum": "100170478917895032",
        #             "asks": [
        #                 [0.01, 100500],
        #                 ...
        #             ],
        #             "bids": [
        #                 [69.69696, 69],
        #                 ...
        #             ],
        #             "checksum": 261021645,
        #             "marketCode": "OX-USDT",
        #             "timestamp": 1716204786184
        #         },
        #         "action": "partial"
        #     }
        #
        data = self.safe_dict(message, 'data', {})
        marketId = self.safe_string(data, 'marketCode')
        symbol = self.safe_symbol(marketId)
        timestamp = self.safe_integer(data, 'timestamp')
        messageHash = 'orderbook:' + symbol
        if not (symbol in self.orderbooks):
            self.orderbooks[symbol] = self.order_book({})
        orderbook = self.orderbooks[symbol]
        snapshot = self.parse_order_book(data, symbol, timestamp, 'asks', 'bids')
        orderbook.reset(snapshot)
        orderbook['nonce'] = self.safe_integer(data, 'seqNum')
        self.orderbooks[symbol] = orderbook
        client.resolve(orderbook, messageHash)

    async def watch_ticker(self, symbol: str, params={}) -> Ticker:
        """

        https://docs.ox.fun/?json#ticker

        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :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 int|str [params.tag]: If given it will be echoed in the reply and the max size of tag is 32
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        ticker = await self.watch_tickers([symbol], params)
        return self.safe_value(ticker, symbol)

    async def watch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
        """

        https://docs.ox.fun/?json#ticker

        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
        :param str[] [symbols]: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int|str [params.tag]: If given it will be echoed in the reply and the max size of tag is 32
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        await self.load_markets()
        allSymbols = (symbols is None)
        sym = symbols
        args = []
        if allSymbols:
            sym = self.symbols
            args.append('ticker:all')
        messageHashes = []
        for i in range(0, len(sym)):
            symbol = sym[i]
            messageHash = 'tickers' + ':' + symbol
            messageHashes.append(messageHash)
            marketId = self.market_id(symbol)
            if not allSymbols:
                args.append('ticker:' + marketId)
        newTicker = await self.subscribe_multiple(messageHashes, args, params)
        if self.newUpdates:
            result = {}
            result[newTicker['symbol']] = newTicker
            return result
        return self.filter_by_array(self.tickers, 'symbol', symbols)

    def handle_ticker(self, client: Client, message):
        #
        #     {
        #         "table": "ticker",
        #         "data": [
        #             {
        #                 "last": "3088.6",
        #                 "open24h": "3087.2",
        #                 "high24h": "3142.0",
        #                 "low24h": "3053.9",
        #                 "volume24h": "450512672.1800",
        #                 "currencyVolume24h": "1458.579",
        #                 "openInterest": "3786.801",
        #                 "marketCode": "ETH-USD-SWAP-LIN",
        #                 "timestamp": "1716212747050",
        #                 "lastQty": "0.813",
        #                 "markPrice": "3088.6",
        #                 "lastMarkPrice": "3088.6",
        #                 "indexPrice": "3086.5"
        #             },
        #             ...
        #         ]
        #     }
        #
        data = self.safe_list(message, 'data', [])
        for i in range(0, len(data)):
            rawTicker = self.safe_dict(data, i, {})
            ticker = self.parse_ticker(rawTicker)
            symbol = ticker['symbol']
            messageHash = 'tickers:' + symbol
            self.tickers[symbol] = ticker
            client.resolve(ticker, messageHash)

    async def watch_bids_asks(self, symbols: Strings = None, params={}) -> Tickers:
        """

        https://docs.ox.fun/?json#best-bid-ask

        watches best bid & ask for symbols
        :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)
        messageHashes = []
        args = []
        for i in range(0, len(symbols)):
            market = self.market(symbols[i])
            args.append('bestBidAsk:' + market['id'])
            messageHashes.append('bidask:' + market['symbol'])
        newTickers = await self.subscribe_multiple(messageHashes, args, params)
        if self.newUpdates:
            tickers: dict = {}
            tickers[newTickers['symbol']] = newTickers
            return tickers
        return self.filter_by_array(self.bidsasks, 'symbol', symbols)

    def handle_bid_ask(self, client: Client, message):
        #
        #     {
        #       "table": "bestBidAsk",
        #       "data": {
        #         "ask": [
        #           19045.0,
        #           1.0
        #         ],
        #         "checksum": 3790706311,
        #         "marketCode": "BTC-USD-SWAP-LIN",
        #         "bid": [
        #           19015.0,
        #           1.0
        #         ],
        #         "timestamp": "1665456882928"
        #       }
        #     }
        #
        data = self.safe_dict(message, 'data', {})
        parsedTicker = self.parse_ws_bid_ask(data)
        symbol = parsedTicker['symbol']
        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, 'marketCode')
        market = self.safe_market(marketId, market)
        symbol = self.safe_string(market, 'symbol')
        timestamp = self.safe_integer(ticker, 'timestamp')
        ask = self.safe_list(ticker, 'ask', [])
        bid = self.safe_list(ticker, 'bid', [])
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'ask': self.safe_number(ask, 0),
            'askVolume': self.safe_number(ask, 1),
            'bid': self.safe_number(bid, 0),
            'bidVolume': self.safe_number(bid, 1),
            'info': ticker,
        }, market)

    async def watch_balance(self, params={}) -> Balances:
        """

        https://docs.ox.fun/?json#balance-channel

        watch balance and get the amount of funds available for trading or funds locked in orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int|str [params.tag]: If given it will be echoed in the reply and the max size of tag is 32
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        """
        await self.load_markets()
        self.authenticate()
        args = 'balance:all'
        messageHash = 'balance'
        url = self.urls['api']['ws']
        request: dict = {
            'op': 'subscribe',
            'args': [args],
        }
        return await self.watch(url, messageHash, self.extend(request, params), messageHash)

    def handle_balance(self, client, message):
        #
        #     {
        #         "table": "balance",
        #         "accountId": "106464",
        #         "timestamp": "1716549132780",
        #         "tradeType": "PORTFOLIO",
        #         "data": [
        #             {
        #                 "instrumentId": "xOX",
        #                 "total": "23.375591220",
        #                 "available": "23.375591220",
        #                 "reserved": "0",
        #                 "quantityLastUpdated": "1716509744262",
        #                 "locked": "0"
        #             },
        #             ...
        #         ]
        #     }
        #
        balances = self.safe_list(message, 'data')
        timestamp = self.safe_integer(message, 'timestamp')
        self.balance['info'] = message
        self.balance['timestamp'] = timestamp
        self.balance['datetime'] = self.iso8601(timestamp)
        for i in range(0, len(balances)):
            balance = self.safe_dict(balances, i, {})
            currencyId = self.safe_string(balance, 'instrumentId')
            code = self.safe_currency_code(currencyId)
            if not (code in self.balance):
                self.balance[code] = self.account()
            account = self.balance[code]
            account['total'] = self.safe_string(balance, 'total')
            account['used'] = self.safe_string(balance, 'reserved')
            account['free'] = self.safe_string(balance, 'available')
            self.balance[code] = account
        self.balance = self.safe_balance(self.balance)
        client.resolve(self.balance, 'balance')

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

        https://docs.ox.fun/?json#position-channel

        watch all open positions
        :param str[]|None symbols: list of unified market symbols
 @param since
 @param limit
        :param dict params: extra parameters specific to the exchange API endpoint
        :param int|str [params.tag]: If given it will be echoed in the reply and the max size of tag is 32
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        """
        await self.load_markets()
        await self.authenticate()
        allSymbols = (symbols is None)
        sym = symbols
        args = []
        if allSymbols:
            sym = self.symbols
            args.append('position:all')
        messageHashes = []
        for i in range(0, len(sym)):
            symbol = sym[i]
            messageHash = 'positions' + ':' + symbol
            messageHashes.append(messageHash)
            marketId = self.market_id(symbol)
            if not allSymbols:
                args.append('position:' + marketId)
        newPositions = await self.subscribe_multiple(messageHashes, args, params)
        if self.newUpdates:
            return newPositions
        return self.filter_by_symbols_since_limit(self.positions, symbols, since, limit, True)

    def handle_positions(self, client: Client, message):
        #
        #     {
        #         "table": "position",
        #         "accountId": "106464",
        #         "timestamp": "1716550771582",
        #         "data": [
        #             {
        #                 "instrumentId": "ETH-USD-SWAP-LIN",
        #                 "quantity": "0.01",
        #                 "lastUpdated": "1716550757299",
        #                 "contractValCurrency": "ETH",
        #                 "entryPrice": "3709.6",
        #                 "positionPnl": "-5.000",
        #                 "estLiquidationPrice": "743.4",
        #                 "margin": "0",
        #                 "leverage": "0"
        #             }
        #         ]
        #     }
        #
        if self.positions is None:
            self.positions = ArrayCacheBySymbolBySide()
        cache = self.positions
        data = self.safe_list(message, 'data', [])
        for i in range(0, len(data)):
            rawPosition = self.safe_dict(data, i, {})
            position = self.parse_ws_position(rawPosition)
            symbol = position['symbol']
            messageHash = 'positions:' + symbol
            cache.append(position)
            client.resolve(position, messageHash)

    def parse_ws_position(self, position, market: Market = None):
        #
        #     {
        #         "instrumentId": "ETH-USD-SWAP-LIN",
        #         "quantity": "0.01",
        #         "lastUpdated": "1716550757299",
        #         "contractValCurrency": "ETH",
        #         "entryPrice": "3709.6",
        #         "positionPnl": "-5.000",
        #         "estLiquidationPrice": "743.4",
        #         "margin": "0",  # Currently always reports 0
        #         "leverage": "0"  # Currently always reports 0
        #     }
        #
        marketId = self.safe_string(position, 'instrumentId')
        market = self.safe_market(marketId, market)
        return self.safe_position({
            'info': position,
            'id': None,
            'symbol': market['symbol'],
            'notional': None,
            'marginMode': 'cross',
            'liquidationPrice': self.safe_number(position, 'estLiquidationPrice'),
            'entryPrice': self.safe_number(position, 'entryPrice'),
            'unrealizedPnl': self.safe_number(position, 'positionPnl'),
            'realizedPnl': None,
            'percentage': None,
            'contracts': self.safe_number(position, 'quantity'),
            'contractSize': None,
            'markPrice': None,
            'lastPrice': None,
            'side': None,
            'hedged': None,
            'timestamp': None,
            'datetime': None,
            'lastUpdateTimestamp': self.safe_integer(position, 'lastUpdated'),
            'maintenanceMargin': None,
            'maintenanceMarginPercentage': None,
            'collateral': None,
            'initialMargin': None,
            'initialMarginPercentage': None,
            'leverage': None,
            'marginRatio': None,
            'stopLossPrice': None,
            'takeProfitPrice': None,
        })

    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://docs.ox.fun/?json#order-channel

        :param str 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 dict [params]: extra parameters specific to the exchange API endpoint
        :param int|str [params.tag]: If given it will be echoed in the reply and the max size of tag is 32
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        await self.authenticate()
        messageHash = 'orders'
        args = 'order:'
        market = self.safe_market(symbol)
        if symbol is None:
            args += 'all'
        else:
            messageHash += ':' + symbol
            args += ':' + market['id']
        request: dict = {
            'op': 'subscribe',
            'args': [
                args,
            ],
        }
        url = self.urls['api']['ws']
        orders = await self.watch(url, messageHash, request, messageHash)
        if self.newUpdates:
            limit = orders.getLimit(symbol, limit)
        return self.filter_by_symbol_since_limit(orders, symbol, since, limit, True)

    def handle_orders(self, client: Client, message):
        #
        #     {
        #         "table": "order",
        #         "data": [
        #             {
        #                 "accountId": "106464",
        #                 "clientOrderId": "1716713676233",
        #                 "orderId": "1000116921319",
        #                 "price": "1000.0",
        #                 "quantity": "0.01",
        #                 "amount": "0.0",
        #                 "side": "BUY",
        #                 "status": "OPEN",
        #                 "marketCode": "ETH-USD-SWAP-LIN",
        #                 "timeInForce": "MAKER_ONLY",
        #                 "timestamp": "1716713677834",
        #                 "remainQuantity": "0.01",
        #                 "limitPrice": "1000.0",
        #                 "notice": "OrderOpened",
        #                 "orderType": "LIMIT",
        #                 "isTriggered": "false",
        #                 "displayQuantity": "0.01"
        #             }
        #         ]
        #     }
        #
        data = self.safe_list(message, 'data', [])
        messageHash = 'orders'
        if self.orders is None:
            limit = self.safe_integer(self.options, 'ordersLimit', 1000)
            self.orders = ArrayCacheBySymbolById(limit)
        orders = self.orders
        for i in range(0, len(data)):
            order = self.safe_dict(data, i, {})
            parsedOrder = self.parse_order(order)
            orders.append(parsedOrder)
            messageHash += ':' + parsedOrder['symbol']
            client.resolve(self.orders, messageHash)

    async def create_order_ws(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}) -> Order:
        """

        https://docs.ox.fun/?json#order-commands

        create a trade order
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market', 'limit', 'STOP_LIMIT' or 'STOP_MARKET'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.clientOrderId]: a unique id for the order
        :param int [params.timestamp]: in milliseconds. If an order reaches the matching engine and the current timestamp exceeds timestamp + recvWindow, then the order will be rejected.
        :param int [params.recvWindow]: in milliseconds. If an order reaches the matching engine and the current timestamp exceeds timestamp + recvWindow, then the order will be rejected. If timestamp is provided without recvWindow, then a default recvWindow of 1000ms is used.
        :param float [params.cost]: the quote quantity that can be used alternative for the amount for market buy orders
        :param float [params.triggerPrice]: The price at which a trigger order is triggered at
        :param float [params.limitPrice]: Limit price for the STOP_LIMIT order
        :param bool [params.postOnly]: if True, the order will only be posted if it will be a maker order
        :param str [params.timeInForce]: GTC(default), IOC, FOK, PO, MAKER_ONLY or MAKER_ONLY_REPRICE(reprices order to the best maker only price if the specified price were to lead to a taker trade)
        :param str [params.selfTradePreventionMode]: NONE, EXPIRE_MAKER, EXPIRE_TAKER or EXPIRE_BOTH for more info check here {@link https://docs.ox.fun/?json#self-trade-prevention-modes}
        :param str [params.displayQuantity]: for an iceberg order, pass both quantity and displayQuantity fields in the order request
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        await self.authenticate()
        messageHash = str(self.nonce())
        request: dict = {
            'op': 'placeorder',
            'tag': messageHash,
        }
        params = self.omit(params, 'tag')
        orderRequest: dict = self.create_order_request(symbol, type, side, amount, price, params)
        timestamp = self.safe_integer(orderRequest, 'timestamp')
        if timestamp is None:
            orderRequest['timestamp'] = self.milliseconds()
        request['data'] = orderRequest
        url = self.urls['api']['ws']
        return await self.watch(url, messageHash, request, messageHash)

    async def edit_order_ws(self, id: str, symbol: str, type: OrderType, side: OrderSide, amount: Num = None, price: Num = None, params={}) -> Order:
        """
        edit a trade order

        https://docs.ox.fun/?json#modify-order

        :param str id: order id
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of the currency you want to trade in units of the base currency
        :param float|None [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.timestamp]: in milliseconds. If an order reaches the matching engine and the current timestamp exceeds timestamp + recvWindow, then the order will be rejected.
        :param int [params.recvWindow]: in milliseconds. If an order reaches the matching engine and the current timestamp exceeds timestamp + recvWindow, then the order will be rejected. If timestamp is provided without recvWindow, then a default recvWindow of 1000ms is used.
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        await self.authenticate()
        messageHash = str(self.nonce())
        request: dict = {
            'op': 'modifyorder',
            'tag': messageHash,
        }
        params = self.omit(params, 'tag')
        orderRequest: dict = self.create_order_request(symbol, type, side, amount, price, params)
        orderRequest = self.extend(orderRequest, {'orderId': id})
        timestamp = self.safe_integer(orderRequest, 'timestamp')
        if timestamp is None:
            orderRequest['timestamp'] = self.milliseconds()
        request['data'] = orderRequest
        url = self.urls['api']['ws']
        return await self.watch(url, messageHash, request, messageHash)

    def handle_place_orders(self, client: Client, message):
        #
        #     {
        #         "event": "placeorder",
        #         "submitted": True,
        #         "tag": "1716934577",
        #         "timestamp": "1716932973899",
        #         "data": {
        #             "marketCode": "ETH-USD-SWAP-LIN",
        #             "side": "BUY",
        #             "orderType": "LIMIT",
        #             "quantity": "0.010",
        #             "timeInForce": "GTC",
        #             "price": "400.0",
        #             "limitPrice": "400.0",
        #             "orderId": "1000117429736",
        #             "source": 13
        #         }
        #     }
        #
        #
        # Failure response format
        #     {
        #         "event": "placeorder",
        #         "submitted": False,
        #         "message": "JSON data format is invalid",
        #         "code": "20009",
        #         "timestamp": "1716932877381"
        #     }
        #
        messageHash = self.safe_string(message, 'tag')
        submitted = self.safe_bool(message, 'submitted')
        # filter out partial errors
        if not submitted:
            method = self.safe_string(message, 'event')
            stringMsg = self.json(message)
            code = self.safe_integer(message, 'code')
            self.handle_errors(code, '', client.url, method, {}, stringMsg, message, {}, {})
        data = self.safe_value(message, 'data', {})
        order = self.parse_order(data)
        client.resolve(order, messageHash)

    async def cancel_order_ws(self, id: str, symbol: Str = None, params={}) -> Order:
        """

        https://docs.ox.fun/?json#cancel-order

        cancels an open order
        :param str id: order id
        :param str symbol: unified market symbol, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' cancelOrderWs() requires a symbol argument')
        await self.load_markets()
        await self.authenticate()
        messageHash = str(self.nonce())
        data: dict = {
            'marketCode': self.market_id(symbol),
            'orderId': id,
        }
        request: dict = {
            'op': 'cancelorder',
            'tag': messageHash,
            'data': data,
        }
        url = self.urls['api']['ws']
        return await self.watch(url, messageHash, request, messageHash)

    async def cancel_orders_ws(self, ids: List[str], symbol: Str = None, params={}):
        """

        https://www.okx.com/docs-v5/en/#order-book-trading-trade-ws-mass-cancel-order

        cancel multiple orders
        :param str[] ids: order ids
        :param str symbol: unified market symbol, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        idsLength: number = len(ids)
        if idsLength > 20:
            raise BadRequest(self.id + ' cancelOrdersWs() accepts up to 20 ids at a time')
        if symbol is None:
            raise ArgumentsRequired(self.id + ' cancelOrdersWs() requires a symbol argument')
        await self.load_markets()
        await self.authenticate()
        messageHash = str(self.nonce())
        marketId = self.market_id(symbol)
        dataArray = []
        for i in range(0, idsLength):
            data: dict = {
                'instId': marketId,
                'ordId': ids[i],
            }
            dataArray.append(data)
        request: dict = {
            'op': 'cancelorders',
            'tag': messageHash,
            'dataArray': dataArray,
        }
        url = self.urls['api']['ws']
        return await self.watch(url, messageHash, self.deep_extend(request, params), messageHash)

    async def authenticate(self, params={}):
        url = self.urls['api']['ws']
        client = self.client(url)
        messageHash = 'authenticated'
        future = client.reusableFuture(messageHash)
        authenticated = self.safe_dict(client.subscriptions, messageHash)
        if authenticated is None:
            self.check_required_credentials()
            timestamp = self.milliseconds()
            payload = str(timestamp) + 'GET/auth/self/verify'
            signature = self.hmac(self.encode(payload), self.encode(self.secret), hashlib.sha256, 'base64')
            request: dict = {
                'op': 'login',
                'data': {
                    'apiKey': self.apiKey,
                    'timestamp': timestamp,
                    'signature': signature,
                },
            }
            message = self.extend(request, params)
            self.watch(url, messageHash, message, messageHash)
        return await future

    def handle_authentication_message(self, client: Client, message):
        authenticated = self.safe_bool(message, 'success', False)
        messageHash = 'authenticated'
        if authenticated:
            # we resolve the future here permanently so authentication only happens once
            future = self.safe_dict(client.futures, messageHash)
            future.resolve(True)
        else:
            error = AuthenticationError(self.json(message))
            client.reject(error, messageHash)
            if messageHash in client.subscriptions:
                del client.subscriptions[messageHash]

    def ping(self, client: Client):
        return 'ping'

    def handle_pong(self, client: Client, message):
        client.lastPong = self.milliseconds()
        return message

    def handle_message(self, client: Client, message):
        if message == 'pong':
            self.handle_pong(client, message)
            return
        table = self.safe_string(message, 'table')
        data = self.safe_list(message, 'data', [])
        event = self.safe_string(message, 'event')
        if (table is not None) and (data is not None):
            if table == 'trade':
                self.handle_trades(client, message)
            if table == 'ticker':
                self.handle_ticker(client, message)
            if table.find('candles') > -1:
                self.handle_ohlcv(client, message)
            if table.find('depth') > -1:
                self.handle_order_book(client, message)
            if table.find('balance') > -1:
                self.handle_balance(client, message)
            if table.find('position') > -1:
                self.handle_positions(client, message)
            if table.find('order') > -1:
                self.handle_orders(client, message)
            if table == 'bestBidAsk':
                self.handle_bid_ask(client, message)
        else:
            if event == 'login':
                self.handle_authentication_message(client, message)
            if (event == 'placeorder') or (event == 'modifyorder') or (event == 'cancelorder'):
                self.handle_place_orders(client, message)
