# -*- 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

from ccxt.async_support.base.exchange import Exchange
from ccxt.abstract.woo import ImplicitAPI
import hashlib
from ccxt.base.types import Account, Any, Balances, Bool, Conversion, Currencies, Currency, DepositAddress, Int, LedgerEntry, Leverage, MarginModification, Market, MarketType, Num, Order, OrderBook, OrderSide, OrderType, Position, Str, Strings, FundingRate, FundingRates, Trade, TradingFees, Transaction, TransferEntry
from typing import List
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import NotSupported
from ccxt.base.errors import OperationFailed
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.errors import OnMaintenance
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class woo(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(woo, self).describe(), {
            'id': 'woo',
            'name': 'WOO X',
            'countries': ['KY'],  # Cayman Islands
            'rateLimit': 100,
            'version': 'v1',
            'certified': True,
            'pro': True,
            'hostname': 'woox.io',
            'has': {
                'CORS': None,
                'spot': True,
                'margin': True,
                'swap': True,
                'future': False,
                'option': False,
                'addMargin': True,
                'cancelAllOrders': True,
                'cancelAllOrdersAfter': True,
                'cancelOrder': True,
                'cancelWithdraw': False,  # exchange have that endpoint disabled atm, but was once implemented in ccxt per old docs: https://docx.woo.io/wootrade-documents/#cancel-withdraw-request
                'closeAllPositions': False,
                'closePosition': False,
                'createConvertTrade': True,
                'createDepositAddress': False,
                'createMarketBuyOrderWithCost': True,
                'createMarketOrder': False,
                'createMarketOrderWithCost': False,
                'createMarketSellOrderWithCost': True,
                'createOrder': True,
                'createOrderWithTakeProfitAndStopLoss': True,
                'createReduceOnlyOrder': True,
                'createStopLimitOrder': False,
                'createStopLossOrder': True,
                'createStopMarketOrder': False,
                'createStopOrder': False,
                'createTakeProfitOrder': True,
                'createTrailingAmountOrder': True,
                'createTrailingPercentOrder': True,
                'createTriggerOrder': True,
                'fetchAccounts': True,
                'fetchBalance': True,
                'fetchCanceledOrders': False,
                'fetchClosedOrder': False,
                'fetchClosedOrders': True,
                'fetchConvertCurrencies': True,
                'fetchConvertQuote': True,
                'fetchConvertTrade': True,
                'fetchConvertTradeHistory': True,
                'fetchCurrencies': True,
                'fetchDepositAddress': True,
                'fetchDepositAddresses': False,
                'fetchDepositAddressesByNetwork': False,
                'fetchDeposits': True,
                'fetchDepositsWithdrawals': True,
                'fetchFundingHistory': True,
                'fetchFundingInterval': True,
                'fetchFundingIntervals': False,
                'fetchFundingRate': True,
                'fetchFundingRateHistory': True,
                'fetchFundingRates': True,
                'fetchIndexOHLCV': False,
                'fetchLedger': True,
                'fetchLeverage': True,
                'fetchMarginAdjustmentHistory': False,
                'fetchMarginMode': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenInterestHistory': False,
                'fetchOpenOrder': False,
                'fetchOpenOrders': True,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrders': True,
                'fetchOrderTrades': True,
                'fetchPosition': True,
                'fetchPositionHistory': False,
                'fetchPositionMode': False,
                'fetchPositions': True,
                'fetchPositionsHistory': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchStatus': True,
                'fetchTicker': False,
                'fetchTickers': False,
                'fetchTime': True,
                'fetchTrades': True,
                'fetchTradingFee': False,
                'fetchTradingFees': True,
                'fetchTransactions': 'emulated',
                'fetchTransfers': True,
                'fetchWithdrawals': True,
                'reduceMargin': False,
                'sandbox': True,
                'setLeverage': True,
                'setMargin': False,
                'setPositionMode': True,
                'transfer': True,
                'withdraw': True,  # exchange have that endpoint disabled atm, but was once implemented in ccxt per old docs: https://docx.woo.io/wootrade-documents/#token-withdraw
            },
            'timeframes': {
                '1m': '1m',
                '5m': '5m',
                '15m': '15m',
                '30m': '30m',
                '1h': '1h',
                '4h': '4h',
                '12h': '12h',
                '1d': '1d',
                '1w': '1w',
                '1M': '1mon',
                '1y': '1y',
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/150730761-1a00e5e0-d28c-480f-9e65-089ce3e6ef3b.jpg',
                'api': {
                    'pub': 'https://api-pub.woox.io',
                    'public': 'https://api.{hostname}',
                    'private': 'https://api.{hostname}',
                },
                'test': {
                    'pub': 'https://api-pub.staging.woox.io',
                    'public': 'https://api.staging.woox.io',
                    'private': 'https://api.staging.woox.io',
                },
                'www': 'https://woox.io/',
                'doc': [
                    'https://docs.woox.io/',
                ],
                'fees': [
                    'https://support.woox.io/hc/en-001/articles/4404611795353--Trading-Fees',
                ],
                'referral': {
                    'url': 'https://woox.io/register?ref=DIJT0CNL',
                    'discount': 0.35,
                },
            },
            'api': {
                'v1': {
                    'pub': {
                        'get': {
                            'hist/kline': 10,
                            'hist/trades': 10,
                        },
                    },
                    'public': {
                        'get': {
                            'info': 1,
                            'info/{symbol}': 1,
                            'system_info': 1,
                            'market_trades': 1,
                            'token': 1,
                            'token_network': 1,
                            'funding_rates': 1,
                            'funding_rate/{symbol}': 1,
                            'funding_rate_history': 1,
                            'futures': 1,
                            'futures/{symbol}': 1,
                            'orderbook/{symbol}': 1,
                            'kline': 1,
                        },
                    },
                    'private': {
                        'get': {
                            'client/token': 1,
                            'order/{oid}': 1,
                            'client/order/{client_order_id}': 1,
                            'orders': 1,
                            'client/trade/{tid}': 1,
                            'order/{oid}/trades': 1,
                            'client/trades': 1,
                            'client/hist_trades': 1,
                            'staking/yield_history': 1,
                            'client/holding': 1,
                            'asset/deposit': 10,
                            'asset/history': 60,
                            'sub_account/all': 60,
                            'sub_account/assets': 60,
                            'sub_account/asset_detail': 60,
                            'sub_account/ip_restriction': 10,
                            'asset/main_sub_transfer_history': 30,
                            'token_interest': 60,
                            'token_interest/{token}': 60,
                            'interest/history': 60,
                            'interest/repay': 60,
                            'funding_fee/history': 30,
                            'positions': 3.33,  # 30 requests per 10 seconds
                            'position/{symbol}': 3.33,
                            'client/transaction_history': 60,
                            'client/futures_leverage': 60,
                        },
                        'post': {
                            'order': 1,  # 10 requests per 1 second per symbol
                            'order/cancel_all_after': 1,
                            'asset/main_sub_transfer': 30,  # 20 requests per 60 seconds
                            'asset/ltv': 30,
                            'asset/withdraw': 30,  # implemented in ccxt, disabled on the exchange side https://docx.woo.io/wootrade-documents/#token-withdraw
                            'asset/internal_withdraw': 30,
                            'interest/repay': 60,
                            'client/account_mode': 120,
                            'client/position_mode': 5,
                            'client/leverage': 120,
                            'client/futures_leverage': 30,
                            'client/isolated_margin': 30,
                        },
                        'delete': {
                            'order': 1,
                            'client/order': 1,
                            'orders': 1,
                            'asset/withdraw': 120,  # implemented in ccxt, disabled on the exchange side https://docx.woo.io/wootrade-documents/#cancel-withdraw-request
                        },
                    },
                },
                'v2': {
                    'private': {
                        'get': {
                            'client/holding': 1,
                        },
                    },
                },
                'v3': {
                    'public': {
                        'get': {
                            'insuranceFund': 3,
                        },
                    },
                    'private': {
                        'get': {
                            'algo/order/{oid}': 1,
                            'algo/orders': 1,
                            'balances': 1,
                            'accountinfo': 60,
                            'positions': 3.33,
                            'buypower': 1,
                            'referrals': 60,
                            'referral_rewards': 60,
                            'convert/exchangeInfo': 1,
                            'convert/assetInfo': 1,
                            'convert/rfq': 60,
                            'convert/trade': 1,
                            'convert/trades': 1,
                        },
                        'post': {
                            'algo/order': 5,
                            'convert/rft': 60,
                        },
                        'put': {
                            'order/{oid}': 2,
                            'order/client/{client_order_id}': 2,
                            'algo/order/{oid}': 2,
                            'algo/order/client/{client_order_id}': 2,
                        },
                        'delete': {
                            'algo/order/{order_id}': 1,
                            'algo/orders/pending': 1,
                            'algo/orders/pending/{symbol}': 1,
                            'orders/pending': 1,
                        },
                    },
                },
            },
            'fees': {
                'trading': {
                    'tierBased': True,
                    'percentage': True,
                    'maker': self.parse_number('0.0002'),
                    'taker': self.parse_number('0.0005'),
                },
            },
            'options': {
                'timeDifference': 0,  # the difference between system clock and exchange clock
                'adjustForTimeDifference': False,  # controls the adjustment logic upon instantiation
                'sandboxMode': False,
                'createMarketBuyOrderRequiresPrice': True,
                # these network aliases require manual mapping here
                'network-aliases-for-tokens': {
                    'HT': 'ERC20',
                    'OMG': 'ERC20',
                    'UATOM': 'ATOM',
                    'ZRX': 'ZRX',
                },
                'networks': {
                    'TRX': 'TRON',
                    'TRC20': 'TRON',
                    'ERC20': 'ETH',
                    'BEP20': 'BSC',
                },
                # override defaultNetworkCodePriorities for a specific currency
                'defaultNetworkCodeForCurrencies': {
                    # 'USDT': 'TRC20',
                    # 'BTC': 'BTC',
                },
                'transfer': {
                    'fillResponseFromRequest': True,
                },
                'brokerId': 'bc830de7-50f3-460b-9ee0-f430f83f9dad',
            },
            'features': {
                'default': {
                    'sandbox': True,
                    'createOrder': {
                        'marginMode': True,
                        'triggerPrice': True,
                        'triggerPriceType': {
                            'last': True,
                            'mark': True,
                            'index': False,
                        },
                        'triggerDirection': False,
                        'stopLossPrice': False,  # todo by triggerPrice
                        'takeProfitPrice': False,  # todo by triggerPrice
                        'attachedStopLossTakeProfit': None,
                        'timeInForce': {
                            'IOC': True,
                            'FOK': True,
                            'PO': True,
                            'GTD': True,
                        },
                        'hedged': False,
                        'trailing': True,
                        'leverage': False,
                        'marketBuyByCost': True,
                        'marketBuyRequiresPrice': False,
                        'selfTradePrevention': False,
                        'iceberg': True,  # todo implement
                    },
                    'createOrders': None,
                    'fetchMyTrades': {
                        'marginMode': False,
                        'limit': 500,
                        'daysBack': 90,
                        'untilDays': 10000,
                        'symbolRequired': False,
                    },
                    'fetchOrder': {
                        'marginMode': False,
                        'trigger': True,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOpenOrders': {
                        'marginMode': False,
                        'limit': 500,
                        'trigger': True,
                        'trailing': True,
                        'symbolRequired': False,
                    },
                    'fetchOrders': {
                        'marginMode': False,
                        'limit': 500,
                        'daysBack': None,
                        'untilDays': 100000,
                        'trigger': True,
                        'trailing': True,
                        'symbolRequired': False,
                    },
                    'fetchClosedOrders': {
                        'marginMode': False,
                        'limit': 500,
                        'daysBack': None,
                        'daysBackCanceled': None,
                        'untilDays': 100000,
                        'trigger': True,
                        'trailing': True,
                        'symbolRequired': False,
                    },
                    'fetchOHLCV': {
                        'limit': 1000,
                    },
                },
                'spot': {
                    'extends': 'default',
                },
                'forSwap': {
                    'extends': 'default',
                    'createOrder': {
                        'hedged': True,
                    },
                },
                'swap': {
                    'linear': {
                        'extends': 'forSwap',
                    },
                    'inverse': None,
                },
                'future': {
                    'linear': None,
                    'inverse': None,
                },
            },
            'commonCurrencies': {},
            'exceptions': {
                'exact': {
                    '-1000': OperationFailed,  # {"code": -1000,  "message": "An unknown error occurred while processing the request"} or  {"success":false,"code":"-1000","message":"An internal error has occurred. We are unable to process your request. Please try again later."}
                    '-1001': AuthenticationError,  # {"code": -1001,  "message": "The api key or secret is in wrong format"}
                    '-1002': AuthenticationError,  # {"code": -1002,  "message": "API key or secret is invalid, it may because key have insufficient permission or the key is expired/revoked."}
                    '-1003': RateLimitExceeded,  # {"code": -1003,  "message": "Rate limit exceed."}
                    '-1004': BadRequest,  # {"code": -1004,  "message": "An unknown parameter was sent."}
                    '-1005': BadRequest,  # {"code": -1005,  "message": "Some parameters are in wrong format for api."}
                    '-1006': BadRequest,  # {"code": -1006,  "message": "The data is not found in server."}
                    '-1007': BadRequest,  # {"code": -1007,  "message": "The data is already exists or your request is duplicated."}
                    '-1008': InvalidOrder,  # {"code": -1008,  "message": "The quantity of settlement is too high than you can request."}
                    '-1009': BadRequest,  # {"code": -1009,  "message": "Can not request withdrawal settlement, you need to deposit other arrears first."}
                    '-1012': BadRequest,  # {"code": -1012,  "message": "Amount is required for buy market orders when margin disabled."}  The place/cancel order request is rejected by internal module, it may because the account is in liquidation or other internal errors. Please try again in a few seconds."}
                    '-1101': InvalidOrder,  # {"code": -1101,  "message": "The risk exposure for client is too high, it may cause by sending too big order or the leverage is too low. please refer to client info to check the current exposure."}
                    '-1102': InvalidOrder,  # {"code": -1102,  "message": "The order value(price * size) is too small."}
                    '-1103': InvalidOrder,  # {"code": -1103,  "message": "The order price is not following the tick size rule for the symbol."}
                    '-1104': InvalidOrder,  # {"code": -1104,  "message": "The order quantity is not following the step size rule for the symbol."}
                    '-1105': InvalidOrder,  # {"code": -1105,  "message": "Price is X% too high or X% too low from the mid price."}
                },
                'broad': {
                    'Can not place': ExchangeError,  # {"code": -1011,  "message": "Can not place/cancel orders, it may because internal network error. Please try again in a few seconds."}
                    'maintenance': OnMaintenance,  # {"code":"-1011","message":"The system is under maintenance.","success":false}
                    'symbol must not be blank': BadRequest,  # when sending 'cancelOrder' without symbol [-1005]
                    'The token is not supported': BadRequest,  # when getting incorrect token's deposit address [-1005]
                    'Your order and symbol are not valid or already canceled': BadRequest,  # actual response whensending 'cancelOrder' for already canceled id [-1006]
                    'Insufficient WOO. Please enable margin trading for leverage trading': BadRequest,  # when selling insufficent token [-1012]
                },
            },
            'precisionMode': TICK_SIZE,
        })

    async def fetch_status(self, params={}):
        """
        the latest known information on the availability of the exchange API

        https://docs.woox.io/#get-system-maintenance-status-public

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
        """
        response = await self.v1PublicGetSystemInfo(params)
        #
        #     {
        #         "success": True,
        #         "data": {
        #             "status": "0",
        #             "msg": "System is functioning properly."
        #         },
        #         "timestamp": "1709274106602"
        #     }
        #
        data = self.safe_dict(response, 'data', {})
        status = self.safe_string(data, 'status')
        if status is None:
            status = 'error'
        elif status == '0':
            status = 'ok'
        else:
            status = 'maintenance'
        return {
            'status': status,
            'updated': None,
            'eta': None,
            'url': None,
            'info': response,
        }

    async def fetch_time(self, params={}) -> Int:
        """
        fetches the current integer timestamp in milliseconds from the exchange server

        https://docs.woox.io/#get-system-maintenance-status-public

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        """
        response = await self.v1PublicGetSystemInfo(params)
        #
        #     {
        #         "success": True,
        #         "data": {
        #             "status": "0",
        #             "msg": "System is functioning properly."
        #         },
        #         "timestamp": "1709274106602"
        #     }
        #
        return self.safe_integer(response, 'timestamp')

    async def fetch_markets(self, params={}) -> List[Market]:
        """
        retrieves data on all markets for woo

        https://docs.woox.io/#exchange-information

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        if self.options['adjustForTimeDifference']:
            await self.load_time_difference()
        response = await self.v1PublicGetInfo(params)
        #
        # {
        #     "rows": [
        #         {
        #             "symbol": "SPOT_AAVE_USDT",
        #             "quote_min": 0,
        #             "quote_max": 100000,
        #             "quote_tick": 0.01,
        #             "base_min": 0.01,
        #             "base_max": 7284,
        #             "base_tick": 0.0001,
        #             "min_notional": 10,
        #             "price_range": 0.1,
        #             "created_time": "0",
        #             "updated_time": "1639107647.988",
        #             "is_stable": 0
        #         },
        #         ...
        #     "success": True
        # }
        #
        data = self.safe_list(response, 'rows', [])
        return self.parse_markets(data)

    def parse_market(self, market: dict) -> Market:
        marketId = self.safe_string(market, 'symbol')
        parts = marketId.split('_')
        first = self.safe_string(parts, 0)
        marketType: MarketType
        spot = False
        swap = False
        if first == 'SPOT':
            spot = True
            marketType = 'spot'
        elif first == 'PERP':
            swap = True
            marketType = 'swap'
        baseId = self.safe_string(parts, 1)
        quoteId = self.safe_string(parts, 2)
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        settleId: Str = None
        settle: Str = None
        symbol = base + '/' + quote
        contractSize: Num = None
        linear: Bool = None
        inverse: Bool = None
        margin = True
        contract = swap
        if contract:
            margin = False
            settleId = self.safe_string(parts, 2)
            settle = self.safe_currency_code(settleId)
            symbol = base + '/' + quote + ':' + settle
            contractSize = self.parse_number('1')
            linear = True
            inverse = False
        active = self.safe_string(market, 'is_trading') == '1'
        return {
            'id': marketId,
            'symbol': symbol,
            'base': base,
            'quote': quote,
            'settle': settle,
            'baseId': baseId,
            'quoteId': quoteId,
            'settleId': settleId,
            'type': marketType,
            'spot': spot,
            'margin': margin,
            'swap': swap,
            'future': False,
            'option': False,
            'active': active,
            'contract': contract,
            'linear': linear,
            'inverse': inverse,
            'contractSize': contractSize,
            'expiry': None,
            'expiryDatetime': None,
            'strike': None,
            'optionType': None,
            'precision': {
                'amount': self.safe_number(market, 'base_tick'),
                'price': self.safe_number(market, 'quote_tick'),
            },
            'limits': {
                'leverage': {
                    'min': None,
                    'max': None,
                },
                'amount': {
                    'min': self.safe_number(market, 'base_min'),
                    'max': self.safe_number(market, 'base_max'),
                },
                'price': {
                    'min': self.safe_number(market, 'quote_min'),
                    'max': self.safe_number(market, 'quote_max'),
                },
                'cost': {
                    'min': self.safe_number(market, 'min_notional'),
                    'max': None,
                },
            },
            'created': self.safe_timestamp(market, 'created_time'),
            'info': market,
        }

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

        https://docs.woox.io/#market-trades-public

        :param str symbol: unified symbol of the market to fetch trades for
        :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
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit
        response = await self.v1PublicGetMarketTrades(self.extend(request, params))
        #
        # {
        #     "success": True,
        #     "rows": [
        #         {
        #             "symbol": "SPOT_BTC_USDT",
        #             "side": "SELL",
        #             "executed_price": 46222.35,
        #             "executed_quantity": 0.0012,
        #             "executed_timestamp": "1641241162.329"
        #         },
        #         {
        #             "symbol": "SPOT_BTC_USDT",
        #             "side": "SELL",
        #             "executed_price": 46222.35,
        #             "executed_quantity": 0.0012,
        #             "executed_timestamp": "1641241162.329"
        #         },
        #         {
        #             "symbol": "SPOT_BTC_USDT",
        #             "side": "BUY",
        #             "executed_price": 46224.32,
        #             "executed_quantity": 0.00039,
        #             "executed_timestamp": "1641241162.287"
        #         },
        #         ...
        #      ]
        # }
        #
        resultResponse = self.safe_list(response, 'rows', [])
        return self.parse_trades(resultResponse, market, since, limit)

    def parse_trade(self, trade: dict, market: Market = None) -> Trade:
        #
        # public/market_trades
        #
        #     {
        #         "symbol": "SPOT_BTC_USDT",
        #         "side": "SELL",
        #         "executed_price": 46222.35,
        #         "executed_quantity": 0.0012,
        #         "executed_timestamp": "1641241162.329"
        #     }
        #
        # fetchOrderTrades, fetchOrder
        #
        #     {
        #         "id": "99119876",
        #         "symbol": "SPOT_WOO_USDT",
        #         "fee": "0.0024",
        #         "side": "BUY",
        #         "executed_timestamp": "1641481113.084",
        #         "order_id": "87001234",
        #         "order_tag": "default", <-- self param only in "fetchOrderTrades"
        #         "executed_price": "1",
        #         "executed_quantity": "12",
        #         "fee_asset": "WOO",
        #         "is_maker": "1"
        #     }
        #
        isFromFetchOrder = ('id' in trade)
        timestamp = self.safe_timestamp(trade, 'executed_timestamp')
        marketId = self.safe_string(trade, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        price = self.safe_string(trade, 'executed_price')
        amount = self.safe_string(trade, 'executed_quantity')
        order_id = self.safe_string(trade, 'order_id')
        fee = self.parse_token_and_fee_temp(trade, 'fee_asset', 'fee')
        feeCost = self.safe_string(fee, 'cost')
        if feeCost is not None:
            fee['cost'] = feeCost
        cost = Precise.string_mul(price, amount)
        side = self.safe_string_lower(trade, 'side')
        id = self.safe_string(trade, 'id')
        takerOrMaker: Str = None
        if isFromFetchOrder:
            isMaker = self.safe_string(trade, 'is_maker') == '1'
            takerOrMaker = 'maker' if isMaker else 'taker'
        return self.safe_trade({
            'id': id,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': symbol,
            'side': side,
            'price': price,
            'amount': amount,
            'cost': cost,
            'order': order_id,
            'takerOrMaker': takerOrMaker,
            'type': None,
            'fee': fee,
            'info': trade,
        }, market)

    def parse_token_and_fee_temp(self, item, feeTokenKey, feeAmountKey):
        feeCost = self.safe_string(item, feeAmountKey)
        fee = None
        if feeCost is not None:
            feeCurrencyId = self.safe_string(item, feeTokenKey)
            feeCurrencyCode = self.safe_currency_code(feeCurrencyId)
            fee = {
                'cost': feeCost,
                'currency': feeCurrencyCode,
            }
        return fee

    async def fetch_trading_fees(self, params={}) -> TradingFees:
        """
        fetch the trading fees for multiple markets

        https://docs.woox.io/#get-account-information-new

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>` indexed by market symbols
        """
        await self.load_markets()
        response = await self.v3PrivateGetAccountinfo(params)
        #
        #     {
        #         "success": True,
        #         "data": {
        #             "applicationId": "dsa",
        #             "account": "dsa",
        #             "alias": "haha",
        #             "accountMode": "MARGIN",
        #             "leverage": 1,
        #             "takerFeeRate": 1,
        #             "makerFeeRate": 1,
        #             "interestRate": 1,
        #             "futuresTakerFeeRate": 1,
        #             "futuresMakerFeeRate": 1,
        #             "otpauth": True,
        #             "marginRatio": 1,
        #             "openMarginRatio": 1,
        #             "initialMarginRatio": 1,
        #             "maintenanceMarginRatio": 1,
        #             "totalCollateral": 1,
        #             "freeCollateral": 1,
        #             "totalAccountValue": 1,
        #             "totalVaultValue": 1,
        #             "totalStakingValue": 1
        #         },
        #         "timestamp": 1673323685109
        #     }
        #
        data = self.safe_dict(response, 'data', {})
        maker = self.safe_string(data, 'makerFeeRate')
        taker = self.safe_string(data, 'takerFeeRate')
        result: dict = {}
        for i in range(0, len(self.symbols)):
            symbol = self.symbols[i]
            result[symbol] = {
                'info': response,
                'symbol': symbol,
                'maker': self.parse_number(Precise.string_div(maker, '10000')),
                'taker': self.parse_number(Precise.string_div(taker, '10000')),
                'percentage': True,
                'tierBased': True,
            }
        return result

    async def fetch_currencies(self, params={}) -> Currencies:
        """
        fetches all available currencies on an exchange

        https://docs.woox.io/#available-token-public

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        """
        result: dict = {}
        tokenResponse = await self.v1PublicGetToken(params)
        #
        # {
        #     "rows": [
        #         {
        #             "token": "ETH_USDT",
        #             "fullname": "Tether",
        #             "decimals": 6,
        #             "balance_token": "USDT",
        #             "created_time": "0",
        #             "updated_time": "0"
        #         },
        #         {
        #             "token": "BSC_USDT",
        #             "fullname": "Tether",
        #             "decimals": 18,
        #             "balance_token": "USDT",
        #             "created_time": "0",
        #             "updated_time": "0"
        #         },
        #         {
        #             "token": "ZEC",
        #             "fullname": "ZCash",
        #             "decimals": 8,
        #             "balance_token": "ZEC",
        #             "created_time": "0",
        #             "updated_time": "0"
        #         },
        #         ...
        #     ],
        #     "success": True
        # }
        #
        # only make one request for currrencies...
        # tokenNetworkResponse = await self.v1PublicGetTokenNetwork(params)
        #
        # {
        #     "rows": [
        #         {
        #             "protocol": "ERC20",
        #             "token": "USDT",
        #             "name": "Ethereum",
        #             "minimum_withdrawal": 30,
        #             "withdrawal_fee": 25,
        #             "allow_deposit": 1,
        #             "allow_withdraw": 1
        #         },
        #         {
        #             "protocol": "TRC20",
        #             "token": "USDT",
        #             "name": "Tron",
        #             "minimum_withdrawal": 30,
        #             "withdrawal_fee": 1,
        #             "allow_deposit": 1,
        #             "allow_withdraw": 1
        #         },
        #         ...
        #     ],
        #     "success": True
        # }
        #
        tokenRows = self.safe_list(tokenResponse, 'rows', [])
        networksByCurrencyId = self.group_by(tokenRows, 'balance_token')
        currencyIds = list(networksByCurrencyId.keys())
        for i in range(0, len(currencyIds)):
            currencyId = currencyIds[i]
            networks = networksByCurrencyId[currencyId]
            code = self.safe_currency_code(currencyId)
            name: Str = None
            minPrecision = None
            resultingNetworks: dict = {}
            for j in range(0, len(networks)):
                network = networks[j]
                name = self.safe_string(network, 'fullname')
                networkId = self.safe_string(network, 'token')
                splitted = networkId.split('_')
                unifiedNetwork = splitted[0]
                precision = self.parse_precision(self.safe_string(network, 'decimals'))
                if precision is not None:
                    minPrecision = precision if (minPrecision is None) else Precise.string_min(precision, minPrecision)
                resultingNetworks[unifiedNetwork] = {
                    'id': networkId,
                    'network': unifiedNetwork,
                    'limits': {
                        'withdraw': {
                            'min': None,
                            'max': None,
                        },
                        'deposit': {
                            'min': None,
                            'max': None,
                        },
                    },
                    'active': None,
                    'deposit': None,
                    'withdraw': None,
                    'fee': None,
                    'precision': self.parse_number(precision),
                    'info': network,
                }
            result[code] = {
                'id': currencyId,
                'name': name,
                'code': code,
                'precision': self.parse_number(minPrecision),
                'active': None,
                'fee': None,
                'networks': resultingNetworks,
                'deposit': None,
                'withdraw': None,
                'type': 'crypto',
                'limits': {
                    'deposit': {
                        'min': None,
                        'max': None,
                    },
                    'withdraw': {
                        'min': None,
                        'max': None,
                    },
                },
                'info': networks,
            }
        return result

    async def create_market_buy_order_with_cost(self, symbol: str, cost: float, params={}):
        """
        create a market buy order by providing the symbol and cost

        https://docs.woox.io/#send-order

        :param str symbol: unified symbol of the market to create an order in
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        if not market['spot']:
            raise NotSupported(self.id + ' createMarketBuyOrderWithCost() supports spot orders only')
        return await self.create_order(symbol, 'market', 'buy', cost, 1, params)

    async def create_market_sell_order_with_cost(self, symbol: str, cost: float, params={}):
        """
        create a market sell order by providing the symbol and cost

        https://docs.woox.io/#send-order

        :param str symbol: unified symbol of the market to create an order in
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        if not market['spot']:
            raise NotSupported(self.id + ' createMarketSellOrderWithCost() supports spot orders only')
        return await self.create_order(symbol, 'market', 'sell', cost, 1, params)

    async def create_trailing_amount_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, trailingAmount=None, trailingTriggerPrice=None, params={}) -> Order:
        """
        create a trailing order by providing the symbol, type, side, amount, price and trailingAmount

        https://docs.woox.io/#send-algo-order

        :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 you want to trade in units of the base currency, or number of contracts
        :param float [price]: the price for the order to be filled at, in units of the quote currency, ignored in market orders
        :param float trailingAmount: the quote amount to trail away from the current market price
        :param float trailingTriggerPrice: the price to activate a trailing order, default uses the price argument
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        if trailingAmount is None:
            raise ArgumentsRequired(self.id + ' createTrailingAmountOrder() requires a trailingAmount argument')
        if trailingTriggerPrice is None:
            raise ArgumentsRequired(self.id + ' createTrailingAmountOrder() requires a trailingTriggerPrice argument')
        params['trailingAmount'] = trailingAmount
        params['trailingTriggerPrice'] = trailingTriggerPrice
        return await self.create_order(symbol, type, side, amount, price, params)

    async def create_trailing_percent_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, trailingPercent=None, trailingTriggerPrice=None, params={}) -> Order:
        """
        create a trailing order by providing the symbol, type, side, amount, price and trailingPercent

        https://docs.woox.io/#send-algo-order

        :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 you want to trade in units of the base currency, or number of contracts
        :param float [price]: the price for the order to be filled at, in units of the quote currency, ignored in market orders
        :param float trailingPercent: the percent to trail away from the current market price
        :param float trailingTriggerPrice: the price to activate a trailing order, default uses the price argument
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        if trailingPercent is None:
            raise ArgumentsRequired(self.id + ' createTrailingPercentOrder() requires a trailingPercent argument')
        if trailingTriggerPrice is None:
            raise ArgumentsRequired(self.id + ' createTrailingPercentOrder() requires a trailingTriggerPrice argument')
        params['trailingPercent'] = trailingPercent
        params['trailingTriggerPrice'] = trailingTriggerPrice
        return await self.create_order(symbol, type, side, amount, price, params)

    async def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
        """
        create a trade order

        https://docs.woox.io/#send-order
        https://docs.woox.io/#send-algo-order

        :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 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 str [params.marginMode]: *for swap markets only* 'cross' or 'isolated', default 'cross'
        :param float [params.triggerPrice]: The price a trigger order is triggered at
        :param dict [params.takeProfit]: *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered(perpetual swap markets only)
        :param float [params.takeProfit.triggerPrice]: take profit trigger price
        :param dict [params.stopLoss]: *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered(perpetual swap markets only)
        :param float [params.stopLoss.triggerPrice]: stop loss trigger price
        :param float [params.algoType]: 'STOP' or 'TRAILING_STOP' or 'OCO' or 'CLOSE_POSITION'
        :param float [params.cost]: *spot market buy only* the quote quantity that can be used alternative for the amount
        :param str [params.trailingAmount]: the quote amount to trail away from the current market price
        :param str [params.trailingPercent]: the percent to trail away from the current market price
        :param str [params.trailingTriggerPrice]: the price to trigger a trailing order, default uses the price argument
        :param str [params.position_side]: 'SHORT' or 'LONG' - if position mode is HEDGE_MODE and the trading involves futures, then is required, otherwise self parameter is not required
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        reduceOnly = self.safe_bool_2(params, 'reduceOnly', 'reduce_only')
        params = self.omit(params, ['reduceOnly', 'reduce_only'])
        orderType = type.upper()
        await self.load_markets()
        market = self.market(symbol)
        orderSide = side.upper()
        request: dict = {
            'symbol': market['id'],
            'side': orderSide,
        }
        marginMode: Str = None
        marginMode, params = self.handle_margin_mode_and_params('createOrder', params)
        if marginMode is not None:
            request['margin_mode'] = self.encode_margin_mode(marginMode)
        triggerPrice = self.safe_string_2(params, 'triggerPrice', 'stopPrice')
        stopLoss = self.safe_value(params, 'stopLoss')
        takeProfit = self.safe_value(params, 'takeProfit')
        algoType = self.safe_string(params, 'algoType')
        trailingTriggerPrice = self.safe_string_2(params, 'trailingTriggerPrice', 'activatedPrice', self.number_to_string(price))
        trailingAmount = self.safe_string_2(params, 'trailingAmount', 'callbackValue')
        trailingPercent = self.safe_string_2(params, 'trailingPercent', 'callbackRate')
        isTrailingAmountOrder = trailingAmount is not None
        isTrailingPercentOrder = trailingPercent is not None
        isTrailing = isTrailingAmountOrder or isTrailingPercentOrder
        isConditional = isTrailing or triggerPrice is not None or stopLoss is not None or takeProfit is not None or (self.safe_value(params, 'childOrders') is not None)
        isMarket = orderType == 'MARKET'
        timeInForce = self.safe_string_lower(params, 'timeInForce')
        postOnly = self.is_post_only(isMarket, None, params)
        reduceOnlyKey = 'reduceOnly' if isConditional else 'reduce_only'
        clientOrderIdKey = 'clientOrderId' if isConditional else 'client_order_id'
        orderQtyKey = 'quantity' if isConditional else 'order_quantity'
        priceKey = 'price' if isConditional else 'order_price'
        typeKey = 'type' if isConditional else 'order_type'
        request[typeKey] = orderType  # LIMIT/MARKET/IOC/FOK/POST_ONLY/ASK/BID
        if not isConditional:
            if postOnly:
                request['order_type'] = 'POST_ONLY'
            elif timeInForce == 'fok':
                request['order_type'] = 'FOK'
            elif timeInForce == 'ioc':
                request['order_type'] = 'IOC'
        if reduceOnly:
            request[reduceOnlyKey] = reduceOnly
        if not isMarket and price is not None:
            request[priceKey] = self.price_to_precision(symbol, price)
        if isMarket and not isConditional:
            # for market buy it requires the amount of quote currency to spend
            cost = self.safe_string_2(params, 'cost', 'order_amount')
            params = self.omit(params, ['cost', 'order_amount'])
            isPriceProvided = price is not None
            if market['spot'] and (isPriceProvided or (cost is not None)):
                quoteAmount = None
                if cost is not None:
                    quoteAmount = self.cost_to_precision(symbol, cost)
                else:
                    amountString = self.number_to_string(amount)
                    priceString = self.number_to_string(price)
                    costRequest = Precise.string_mul(amountString, priceString)
                    quoteAmount = self.cost_to_precision(symbol, costRequest)
                request['order_amount'] = quoteAmount
            else:
                request['order_quantity'] = self.amount_to_precision(symbol, amount)
        elif algoType != 'POSITIONAL_TP_SL':
            request[orderQtyKey] = self.amount_to_precision(symbol, amount)
        clientOrderId = self.safe_string_n(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
        if clientOrderId is not None:
            request[clientOrderIdKey] = clientOrderId
        if isTrailing:
            if trailingTriggerPrice is None:
                raise ArgumentsRequired(self.id + ' createOrder() requires a trailingTriggerPrice parameter for trailing orders')
            request['activatedPrice'] = self.price_to_precision(symbol, trailingTriggerPrice)
            request['algoType'] = 'TRAILING_STOP'
            if isTrailingAmountOrder:
                request['callbackValue'] = trailingAmount
            elif isTrailingPercentOrder:
                convertedTrailingPercent = Precise.string_div(trailingPercent, '100')
                request['callbackRate'] = convertedTrailingPercent
        elif triggerPrice is not None:
            if algoType != 'TRAILING_STOP':
                request['triggerPrice'] = self.price_to_precision(symbol, triggerPrice)
                request['algoType'] = 'STOP'
        elif (stopLoss is not None) or (takeProfit is not None):
            request['algoType'] = 'BRACKET'
            outterOrder: dict = {
                'symbol': market['id'],
                'reduceOnly': False,
                'algoType': 'POSITIONAL_TP_SL',
                'childOrders': [],
            }
            childOrders = outterOrder['childOrders']
            closeSide = 'SELL' if (orderSide == 'BUY') else 'BUY'
            if stopLoss is not None:
                stopLossPrice = self.safe_string(stopLoss, 'triggerPrice', stopLoss)
                stopLossOrder: dict = {
                    'side': closeSide,
                    'algoType': 'STOP_LOSS',
                    'triggerPrice': self.price_to_precision(symbol, stopLossPrice),
                    'type': 'CLOSE_POSITION',
                    'reduceOnly': True,
                }
                childOrders.append(stopLossOrder)
            if takeProfit is not None:
                takeProfitPrice = self.safe_string(takeProfit, 'triggerPrice', takeProfit)
                takeProfitOrder: dict = {
                    'side': closeSide,
                    'algoType': 'TAKE_PROFIT',
                    'triggerPrice': self.price_to_precision(symbol, takeProfitPrice),
                    'type': 'CLOSE_POSITION',
                    'reduceOnly': True,
                }
                childOrders.append(takeProfitOrder)
            request['childOrders'] = [outterOrder]
        params = self.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id', 'postOnly', 'timeInForce', 'stopPrice', 'triggerPrice', 'stopLoss', 'takeProfit', 'trailingPercent', 'trailingAmount', 'trailingTriggerPrice'])
        response = None
        if isConditional:
            response = await self.v3PrivatePostAlgoOrder(self.extend(request, params))
        else:
            response = await self.v1PrivatePostOrder(self.extend(request, params))
        # {
        #     "success": True,
        #     "timestamp": "1641383206.489",
        #     "order_id": "86980774",
        #     "order_type": "LIMIT",
        #     "order_price": "1",  # null for "MARKET" order
        #     "order_quantity": "12",  # null for "MARKET" order
        #     "order_amount": null,  # NOT-null for "MARKET" order
        #     "client_order_id": "0"
        # }
        # stop orders
        # {
        #     "success": True,
        #     "data": {
        #       "rows": [
        #         {
        #           "orderId": "1578938",
        #           "clientOrderId": "0",
        #           "algoType": "STOP_LOSS",
        #           "quantity": "0.1"
        #         }
        #       ]
        #     },
        #     "timestamp": "1686149372216"
        # }
        data = self.safe_dict(response, 'data')
        if data is not None:
            rows = self.safe_list(data, 'rows', [])
            return self.parse_order(rows[0], market)
        order = self.parse_order(response, market)
        order['type'] = type
        return order

    def encode_margin_mode(self, mode):
        modes = {
            'cross': 'CROSS',
            'isolated': 'ISOLATED',
        }
        return self.safe_string(modes, mode, mode)

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

        https://docs.woox.io/#edit-order
        https://docs.woox.io/#edit-order-by-client_order_id
        https://docs.woox.io/#edit-algo-order
        https://docs.woox.io/#edit-algo-order-by-client_order_id

        :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 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 float [params.triggerPrice]: The price a trigger order is triggered at
        :param float [params.stopLossPrice]: price to trigger stop-loss orders
        :param float [params.takeProfitPrice]: price to trigger take-profit orders
        :param str [params.trailingAmount]: the quote amount to trail away from the current market price
        :param str [params.trailingPercent]: the percent to trail away from the current market price
        :param str [params.trailingTriggerPrice]: the price to trigger a trailing order, default uses the price argument
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            # 'quantity': self.amount_to_precision(symbol, amount),
            # 'price': self.price_to_precision(symbol, price),
        }
        if price is not None:
            request['price'] = self.price_to_precision(symbol, price)
        if amount is not None:
            request['quantity'] = self.amount_to_precision(symbol, amount)
        clientOrderIdUnified = self.safe_string_2(params, 'clOrdID', 'clientOrderId')
        clientOrderIdExchangeSpecific = self.safe_string(params, 'client_order_id', clientOrderIdUnified)
        isByClientOrder = clientOrderIdExchangeSpecific is not None
        triggerPrice = self.safe_number_n(params, ['triggerPrice', 'stopPrice', 'takeProfitPrice', 'stopLossPrice'])
        if triggerPrice is not None:
            request['triggerPrice'] = self.price_to_precision(symbol, triggerPrice)
        trailingTriggerPrice = self.safe_string_2(params, 'trailingTriggerPrice', 'activatedPrice', self.number_to_string(price))
        trailingAmount = self.safe_string_2(params, 'trailingAmount', 'callbackValue')
        trailingPercent = self.safe_string_2(params, 'trailingPercent', 'callbackRate')
        isTrailingAmountOrder = trailingAmount is not None
        isTrailingPercentOrder = trailingPercent is not None
        isTrailing = isTrailingAmountOrder or isTrailingPercentOrder
        if isTrailing:
            if trailingTriggerPrice is not None:
                request['activatedPrice'] = self.price_to_precision(symbol, trailingTriggerPrice)
            if isTrailingAmountOrder:
                request['callbackValue'] = trailingAmount
            elif isTrailingPercentOrder:
                convertedTrailingPercent = Precise.string_div(trailingPercent, '100')
                request['callbackRate'] = convertedTrailingPercent
        params = self.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id', 'stopPrice', 'triggerPrice', 'takeProfitPrice', 'stopLossPrice', 'trailingTriggerPrice', 'trailingAmount', 'trailingPercent'])
        isConditional = isTrailing or (triggerPrice is not None) or (self.safe_value(params, 'childOrders') is not None)
        response = None
        if isByClientOrder:
            request['client_order_id'] = clientOrderIdExchangeSpecific
            if isConditional:
                response = await self.v3PrivatePutAlgoOrderClientClientOrderId(self.extend(request, params))
            else:
                response = await self.v3PrivatePutOrderClientClientOrderId(self.extend(request, params))
        else:
            request['oid'] = id
            if isConditional:
                response = await self.v3PrivatePutAlgoOrderOid(self.extend(request, params))
            else:
                response = await self.v3PrivatePutOrderOid(self.extend(request, params))
        #
        #     {
        #         "code": 0,
        #         "data": {
        #             "status": "string",
        #             "success": True
        #         },
        #         "message": "string",
        #         "success": True,
        #         "timestamp": 0
        #     }
        #
        data = self.safe_dict(response, 'data', {})
        return self.parse_order(data, market)

    async def cancel_order(self, id: str, symbol: Str = None, params={}):
        """

        https://docs.woox.io/#cancel-algo-order
        https://docs.woox.io/#cancel-order
        https://docs.woox.io/#cancel-order-by-client_order_id

        cancels an open order
        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.trigger]: whether the order is a trigger/algo order
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        isTrigger = self.safe_bool_2(params, 'trigger', 'stop', False)
        params = self.omit(params, ['trigger', 'stop'])
        if not isTrigger and (symbol is None):
            raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
        await self.load_markets()
        market: Market = None
        if symbol is not None:
            market = self.market(symbol)
        request: dict = {}
        clientOrderIdUnified = self.safe_string_2(params, 'clOrdID', 'clientOrderId')
        clientOrderIdExchangeSpecific = self.safe_string(params, 'client_order_id', clientOrderIdUnified)
        isByClientOrder = clientOrderIdExchangeSpecific is not None
        response = None
        if isTrigger:
            request['order_id'] = id
            response = await self.v3PrivateDeleteAlgoOrderOrderId(self.extend(request, params))
        else:
            request['symbol'] = market['id']
            if isByClientOrder:
                request['client_order_id'] = clientOrderIdExchangeSpecific
                params = self.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
                response = await self.v1PrivateDeleteClientOrder(self.extend(request, params))
            else:
                request['order_id'] = id
                response = await self.v1PrivateDeleteOrder(self.extend(request, params))
        #
        # {success: True, status: "CANCEL_SENT"}
        #
        extendParams: dict = {'symbol': symbol}
        if isByClientOrder:
            extendParams['client_order_id'] = clientOrderIdExchangeSpecific
        else:
            extendParams['id'] = id
        return self.extend(self.parse_order(response), extendParams)

    async def cancel_all_orders(self, symbol: Str = None, params={}):
        """

        https://docs.woox.io/#cancel-all-pending-orders
        https://docs.woox.io/#cancel-orders
        https://docs.woox.io/#cancel-all-pending-algo-orders

        cancel all open orders in a market
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.trigger]: whether the order is a trigger/algo order
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        trigger = self.safe_bool_2(params, 'stop', 'trigger')
        params = self.omit(params, ['stop', 'trigger'])
        if trigger:
            return await self.v3PrivateDeleteAlgoOrdersPending(params)
        if symbol is None:
            raise ArgumentsRequired(self.id + ' cancelOrders() requires a symbol argument')
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = await self.v1PrivateDeleteOrders(self.extend(request, params))
        #
        #     {
        #         "success":true,
        #         "status":"CANCEL_ALL_SENT"
        #     }
        #
        return [
            self.safe_order(response),
        ]

    async def cancel_all_orders_after(self, timeout: Int, params={}):
        """
        dead man's switch, cancel all orders after the given timeout

        https://docs.woox.io/#cancel-all-after

        :param number timeout: time in milliseconds, 0 represents cancel the timer
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: the api result
        """
        await self.load_markets()
        request: dict = {
            'trigger_after': timeout if (timeout > 0) else 0,
        }
        response = await self.v1PrivatePostOrderCancelAllAfter(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #         "data": {
        #             "expected_trigger_time": 1711534302938
        #         },
        #         "timestamp": 1711534302943
        #     }
        #
        return [
            self.safe_order(response),
        ]

    async def fetch_order(self, id: str, symbol: Str = None, params={}):
        """

        https://docs.woox.io/#get-algo-order
        https://docs.woox.io/#get-order

        fetches information on an order made by the user
        :param str id: the order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.trigger]: whether the order is a trigger/algo order
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol) if (symbol is not None) else None
        trigger = self.safe_bool_2(params, 'stop', 'trigger')
        params = self.omit(params, ['stop', 'trigger'])
        request: dict = {}
        clientOrderId = self.safe_string_2(params, 'clOrdID', 'clientOrderId')
        response = None
        if trigger:
            request['oid'] = id
            response = await self.v3PrivateGetAlgoOrderOid(self.extend(request, params))
        elif clientOrderId:
            request['client_order_id'] = clientOrderId
            response = await self.v1PrivateGetClientOrderClientOrderId(self.extend(request, params))
        else:
            request['oid'] = id
            response = await self.v1PrivateGetOrderOid(self.extend(request, params))
        #
        # {
        #     "success": True,
        #     "symbol": "SPOT_WOO_USDT",
        #     "status": "FILLED",  # FILLED, NEW
        #     "side": "BUY",
        #     "created_time": "1641480933.000",
        #     "order_id": "87541111",
        #     "order_tag": "default",
        #     "price": "1",
        #     "type": "LIMIT",
        #     "quantity": "12",
        #     "amount": null,
        #     "visible": "12",
        #     "executed": "12",  # or any partial amount
        #     "total_fee": "0.0024",
        #     "fee_asset": "WOO",
        #     "client_order_id": null,
        #     "average_executed_price": "1",
        #     "Transactions": [
        #       {
        #         "id": "99111647",
        #         "symbol": "SPOT_WOO_USDT",
        #         "fee": "0.0024",
        #         "side": "BUY",
        #         "executed_timestamp": "1641482113.084",
        #         "order_id": "87541111",
        #         "executed_price": "1",
        #         "executed_quantity": "12",
        #         "fee_asset": "WOO",
        #         "is_maker": "1"
        #       }
        #     ]
        # }
        #
        orders = self.safe_dict(response, 'data', response)
        return self.parse_order(orders, market)

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

        https://docs.woox.io/#get-orders
        https://docs.woox.io/#get-algo-orders

        :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 boolean [params.trigger]: whether the order is a trigger/algo order
        :param boolean [params.isTriggered]: whether the order has been triggered(False by default)
        :param str [params.side]: 'buy' or 'sell'
        :param boolean [params.trailing]: set to True if you want to fetch trailing orders
        :param boolean [params.paginate]: set to True if you want to fetch orders with pagination
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        paginate = False
        paginate, params = self.handle_option_and_params(params, 'fetchOrders', 'paginate')
        if paginate:
            return await self.fetch_paginated_call_incremental('fetchOrders', symbol, since, limit, params, 'page', 500)
        request: dict = {}
        market: Market = None
        trigger = self.safe_bool_2(params, 'stop', 'trigger')
        trailing = self.safe_bool(params, 'trailing', False)
        params = self.omit(params, ['stop', 'trailing', 'trigger'])
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            if trigger or trailing:
                request['createdTimeStart'] = since
            else:
                request['start_t'] = since
        if limit is not None:
            request['size'] = limit
        else:
            request['size'] = 500
        if trigger:
            request['algoType'] = 'stop'
        elif trailing:
            request['algoType'] = 'TRAILING_STOP'
        response = None
        if trigger or trailing:
            response = await self.v3PrivateGetAlgoOrders(self.extend(request, params))
        else:
            response = await self.v1PrivateGetOrders(self.extend(request, params))
        #
        #     {
        #         "success":true,
        #         "meta":{
        #             "total":1,
        #             "records_per_page":100,
        #             "current_page":1
        #         },
        #         "rows":[
        #             {
        #                 "symbol":"PERP_BTC_USDT",
        #                 "status":"FILLED",
        #                 "side":"SELL",
        #                 "created_time":"1611617776.000",
        #                 "updated_time":"1611617776.000",
        #                 "order_id":52121167,
        #                 "order_tag":"default",
        #                 "price":null,
        #                 "type":"MARKET",
        #                 "quantity":0.002,
        #                 "amount":null,
        #                 "visible":0,
        #                 "executed":0.002,
        #                 "total_fee":0.01732885,
        #                 "fee_asset":"USDT",
        #                 "client_order_id":null,
        #                 "average_executed_price":28881.41
        #             }
        #         ]
        #     }
        #
        data = self.safe_value(response, 'data', response)
        orders = self.safe_list(data, 'rows')
        return self.parse_orders(orders, market, since, limit)

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

        https://docs.woox.io/#get-orders
        https://docs.woox.io/#get-algo-orders

        :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 boolean [params.trigger]: whether the order is a trigger/algo order
        :param boolean [params.isTriggered]: whether the order has been triggered(False by default)
        :param str [params.side]: 'buy' or 'sell'
        :param boolean [params.trailing]: set to True if you want to fetch trailing orders
        :param boolean [params.paginate]: set to True if you want to fetch orders with pagination
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        extendedParams = self.extend(params, {'status': 'INCOMPLETE'})
        return await self.fetch_orders(symbol, since, limit, extendedParams)

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

        https://docs.woox.io/#get-orders
        https://docs.woox.io/#get-algo-orders

        :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 boolean [params.trigger]: whether the order is a trigger/algo order
        :param boolean [params.isTriggered]: whether the order has been triggered(False by default)
        :param str [params.side]: 'buy' or 'sell'
        :param boolean [params.trailing]: set to True if you want to fetch trailing orders
        :param boolean [params.paginate]: set to True if you want to fetch orders with pagination
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        extendedParams = self.extend(params, {'status': 'COMPLETED'})
        return await self.fetch_orders(symbol, since, limit, extendedParams)

    def parse_time_in_force(self, timeInForce: Str):
        timeInForces: dict = {
            'ioc': 'IOC',
            'fok': 'FOK',
            'post_only': 'PO',
        }
        return self.safe_string(timeInForces, timeInForce, None)

    def parse_order(self, order: dict, market: Market = None) -> Order:
        #
        # Possible input functions:
        # * createOrder
        # * cancelOrder
        # * fetchOrder
        # * fetchOrders
        # isFromFetchOrder = ('order_tag' in order); TO_DO
        #
        # stop order after creating it:
        #   {
        #     "orderId": "1578938",
        #     "clientOrderId": "0",
        #     "algoType": "STOP_LOSS",
        #     "quantity": "0.1"
        #   }
        # stop order after fetching it:
        #   {
        #       "algoOrderId": "1578958",
        #       "clientOrderId": "0",
        #       "rootAlgoOrderId": "1578958",
        #       "parentAlgoOrderId": "0",
        #       "symbol": "SPOT_LTC_USDT",
        #       "orderTag": "default",
        #       "algoType": "STOP_LOSS",
        #       "side": "BUY",
        #       "quantity": "0.1",
        #       "isTriggered": False,
        #       "triggerPrice": "100",
        #       "triggerStatus": "USELESS",
        #       "type": "LIMIT",
        #       "rootAlgoStatus": "CANCELLED",
        #       "algoStatus": "CANCELLED",
        #       "triggerPriceType": "MARKET_PRICE",
        #       "price": "75",
        #       "triggerTime": "0",
        #       "totalExecutedQuantity": "0",
        #       "averageExecutedPrice": "0",
        #       "totalFee": "0",
        #       "feeAsset": '',
        #       "reduceOnly": False,
        #       "createdTime": "1686149609.744",
        #       "updatedTime": "1686149903.362"
        #   }
        #
        timestamp = self.safe_timestamp_n(order, ['timestamp', 'created_time', 'createdTime'])
        orderId = self.safe_string_n(order, ['order_id', 'orderId', 'algoOrderId'])
        clientOrderId = self.omit_zero(self.safe_string_2(order, 'client_order_id', 'clientOrderId'))  # Somehow, self always returns 0 for limit order
        marketId = self.safe_string(order, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        price = self.safe_string_2(order, 'order_price', 'price')
        amount = self.safe_string_2(order, 'order_quantity', 'quantity')  # This is base amount
        cost = self.safe_string_2(order, 'order_amount', 'amount')  # This is quote amount
        orderType = self.safe_string_lower_2(order, 'order_type', 'type')
        status = self.safe_value_2(order, 'status', 'algoStatus')
        side = self.safe_string_lower(order, 'side')
        filled = self.omit_zero(self.safe_value_2(order, 'executed', 'totalExecutedQuantity'))
        average = self.omit_zero(self.safe_string_2(order, 'average_executed_price', 'averageExecutedPrice'))
        # remaining = Precise.string_sub(cost, filled)
        fee = self.safe_number_2(order, 'total_fee', 'totalFee')
        feeCurrency = self.safe_string_2(order, 'fee_asset', 'feeAsset')
        transactions = self.safe_value(order, 'Transactions')
        triggerPrice = self.safe_number(order, 'triggerPrice')
        takeProfitPrice: Num = None
        stopLossPrice: Num = None
        childOrders = self.safe_value(order, 'childOrders')
        if childOrders is not None:
            first = self.safe_value(childOrders, 0)
            innerChildOrders = self.safe_value(first, 'childOrders', [])
            innerChildOrdersLength = len(innerChildOrders)
            if innerChildOrdersLength > 0:
                takeProfitOrder = self.safe_value(innerChildOrders, 0)
                stopLossOrder = self.safe_value(innerChildOrders, 1)
                takeProfitPrice = self.safe_number(takeProfitOrder, 'triggerPrice')
                stopLossPrice = self.safe_number(stopLossOrder, 'triggerPrice')
        lastUpdateTimestamp = self.safe_timestamp_2(order, 'updatedTime', 'updated_time')
        return self.safe_order({
            'id': orderId,
            'clientOrderId': clientOrderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'lastUpdateTimestamp': lastUpdateTimestamp,
            'status': self.parse_order_status(status),
            'symbol': symbol,
            'type': orderType,
            'timeInForce': self.parse_time_in_force(orderType),
            'postOnly': None,  # TO_DO
            'reduceOnly': self.safe_bool(order, 'reduce_only'),
            'side': side,
            'price': price,
            'triggerPrice': triggerPrice,
            'takeProfitPrice': takeProfitPrice,
            'stopLossPrice': stopLossPrice,
            'average': average,
            'amount': amount,
            'filled': filled,
            'remaining': None,  # TO_DO
            'cost': cost,
            'trades': transactions,
            'fee': {
                'cost': fee,
                'currency': feeCurrency,
            },
            'info': order,
        }, market)

    def parse_order_status(self, status: Str):
        if status is not None:
            statuses: dict = {
                'NEW': 'open',
                'FILLED': 'closed',
                'CANCEL_SENT': 'canceled',
                'CANCEL_ALL_SENT': 'canceled',
                'CANCELLED': 'canceled',
                'PARTIAL_FILLED': 'open',
                'REJECTED': 'rejected',
                'INCOMPLETE': 'open',
                'COMPLETED': 'closed',
            }
            return self.safe_string(statuses, status, status)
        return status

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

        https://docs.woox.io/#orderbook-snapshot-public

        :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
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        if limit is not None:
            limit = min(limit, 1000)
            request['max_level'] = limit
        response = await self.v1PublicGetOrderbookSymbol(self.extend(request, params))
        #
        # {
        #   "success": True,
        #   "timestamp": "1641562961192",
        #   "asks": [
        #     {price: '0.921', quantity: "76.01"},
        #     {price: '0.933', quantity: "477.10"},
        #     ...
        #   ],
        #   "bids": [
        #     {price: '0.940', quantity: "13502.47"},
        #     {price: '0.932', quantity: "43.91"},
        #     ...
        #   ]
        # }
        #
        timestamp = self.safe_integer(response, 'timestamp')
        return self.parse_order_book(response, symbol, timestamp, 'bids', 'asks', 'price', 'quantity')

    async def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
        """

        https://docs.woox.io/#kline-public
        https://docs.woox.io/#kline-historical-data-public

        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :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]: max=1000, max=100 when since is defined and is less than(now - (999 * (timeframe in ms)))
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
            'type': self.safe_string(self.timeframes, timeframe, timeframe),
        }
        useHistEndpoint = since is not None
        if (limit is not None) and (since is not None):
            oneThousandCandles = self.parse_timeframe(timeframe) * 1000 * 999  # 999 because there will be delay between self and the request, causing the latest candle to be excluded sometimes
            startWithLimit = self.milliseconds() - oneThousandCandles
            useHistEndpoint = since < startWithLimit
        if useHistEndpoint:
            request['start_time'] = since
        elif limit is not None:  # the hist endpoint does not accept limit
            request['limit'] = min(limit, 1000)
        response = None
        if not useHistEndpoint:
            response = await self.v1PublicGetKline(self.extend(request, params))
            #
            #    {
            #        "success": True,
            #        "rows": [
            #            {
            #                "open": "0.94238",
            #                "close": "0.94271",
            #                "low": "0.94238",
            #                "high": "0.94296",
            #                "volume": "73.55",
            #                "amount": "69.32040520",
            #                "symbol": "SPOT_WOO_USDT",
            #                "type": "1m",
            #                "start_timestamp": "1641584700000",
            #                "end_timestamp": "1641584760000"
            #            },
            #            ...
            #        ]
            #    }
            #
        else:
            response = await self.v1PubGetHistKline(self.extend(request, params))
            response = self.safe_dict(response, 'data')
            #
            #    {
            #        "success": True,
            #        "data": {
            #            "rows": [
            #                {
            #                    "symbol": "SPOT_BTC_USDT",
            #                    "open": 44181.40000000,
            #                    "close": 44174.29000000,
            #                    "high": 44193.44000000,
            #                    "low": 44148.34000000,
            #                    "volume": 110.11930100,
            #                    "amount": 4863796.24318878,
            #                    "type": "1m",
            #                    "start_timestamp": 1704153600000,
            #                    "end_timestamp": 1704153660000
            #                },
            #                ...
            #            ]
            #        }
            #    }
            #
        rows = self.safe_list(response, 'rows', [])
        return self.parse_ohlcvs(rows, market, timeframe, since, limit)

    def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
        # example response in fetchOHLCV
        return [
            self.safe_integer(ohlcv, 'start_timestamp'),
            self.safe_number(ohlcv, 'open'),
            self.safe_number(ohlcv, 'high'),
            self.safe_number(ohlcv, 'low'),
            self.safe_number(ohlcv, 'close'),
            self.safe_number(ohlcv, 'volume'),
        ]

    async def fetch_order_trades(self, id: str, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        fetch all the trades made from a single order

        https://docs.woox.io/#get-trades

        :param str id: order id
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        """
        await self.load_markets()
        market: Market = None
        if symbol is not None:
            market = self.market(symbol)
        request: dict = {
            'oid': id,
        }
        response = await self.v1PrivateGetOrderOidTrades(self.extend(request, params))
        # {
        #     "success": True,
        #     "rows": [
        #       {
        #         "id": "99111647",
        #         "symbol": "SPOT_WOO_USDT",
        #         "fee": "0.0024",
        #         "side": "BUY",
        #         "executed_timestamp": "1641482113.084",
        #         "order_id": "87541111",
        #         "order_tag": "default",
        #         "executed_price": "1",
        #         "executed_quantity": "12",
        #         "fee_asset": "WOO",
        #         "is_maker": "1"
        #       }
        #     ]
        # }
        trades = self.safe_list(response, 'rows', [])
        return self.parse_trades(trades, market, since, limit, params)

    async def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        fetch all trades made by the user

        https://docs.woox.io/#get-trade-history

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: set to True if you want to fetch trades with pagination
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        """
        await self.load_markets()
        paginate = False
        paginate, params = self.handle_option_and_params(params, 'fetchMyTrades', 'paginate')
        if paginate:
            return await self.fetch_paginated_call_incremental('fetchMyTrades', symbol, since, limit, params, 'page', 500)
        request: dict = {}
        market: Market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            request['start_t'] = since
        request, params = self.handle_until_option('end_t', request, params)
        if limit is not None:
            request['size'] = limit
        else:
            request['size'] = 500
        response = await self.v1PrivateGetClientTrades(self.extend(request, params))
        # {
        #     "success": True,
        #     "meta": {
        #         "records_per_page": 25,
        #         "current_page": 1
        #     },
        #     "rows": [
        #         {
        #             "id": 5,
        #             "symbol": "SPOT_BTC_USDT",
        #             "order_id": 211,
        #             "order_tag": "default",
        #             "executed_price": 10892.84,
        #             "executed_quantity": 0.002,
        #             "is_maker": 0,
        #             "side": "SELL",
        #             "fee": 0,
        #             "fee_asset": "USDT",
        #             "executed_timestamp": "1566264290.250"
        #         },
        #         ...
        #     ]
        # }
        trades = self.safe_list(response, 'rows', [])
        return self.parse_trades(trades, market, since, limit, params)

    async def fetch_accounts(self, params={}) -> List[Account]:
        """
        fetch all the accounts associated with a profile

        https://docs.woox.io/#get-assets-of-subaccounts

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `account structures <https://docs.ccxt.com/#/?id=account-structure>` indexed by the account type
        """
        response = await self.v1PrivateGetSubAccountAssets(params)
        #
        #     {
        #         "rows": [{
        #                 "application_id": "13e4fc34-e2ff-4cb7-b1e4-4c22fee7d365",
        #                 "account": "Main",
        #                 "usdt_balance": "4.0"
        #             },
        #             {
        #                 "application_id": "432952aa-a401-4e26-aff6-972920aebba3",
        #                 "account": "subaccount",
        #                 "usdt_balance": "1.0"
        #             }
        #         ],
        #         "success": True
        #     }
        #
        rows = self.safe_list(response, 'rows', [])
        return self.parse_accounts(rows, params)

    def parse_account(self, account):
        #
        #     {
        #         "application_id": "336952aa-a401-4e26-aff6-972920aebba3",
        #         "account": "subaccount",
        #         "usdt_balance": "1.0",
        #     }
        #
        accountId = self.safe_string(account, 'account')
        return {
            'info': account,
            'id': self.safe_string(account, 'application_id'),
            'name': accountId,
            'code': None,
            'type': accountId == 'main' if 'Main' else 'subaccount',
        }

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

        https://docs.woox.io/#get-current-holding-get-balance-new

        :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()
        response = await self.v3PrivateGetBalances(params)
        #
        #     {
        #         "success": True,
        #         "data": {
        #             "holding": [
        #                 {
        #                     "token": "0_token",
        #                     "holding": 1,
        #                     "frozen": 0,
        #                     "staked": 0,
        #                     "unbonding": 0,
        #                     "vault": 0,
        #                     "interest": 0,
        #                     "pendingShortQty": 0,
        #                     "pendingLongQty": 0,
        #                     "availableBalance": 0,
        #                     "updatedTime": 312321.121
        #                 }
        #             ]
        #         },
        #         "timestamp": 1673323746259
        #     }
        #
        data = self.safe_dict(response, 'data')
        return self.parse_balance(data)

    def parse_balance(self, response) -> Balances:
        result: dict = {
            'info': response,
        }
        balances = self.safe_list(response, 'holding', [])
        for i in range(0, len(balances)):
            balance = balances[i]
            code = self.safe_currency_code(self.safe_string(balance, 'token'))
            account = self.account()
            account['total'] = self.safe_string(balance, 'holding')
            account['free'] = self.safe_string(balance, 'availableBalance')
            result[code] = account
        return self.safe_balance(result)

    async def fetch_deposit_address(self, code: str, params={}) -> DepositAddress:
        """
        fetch the deposit address for a currency associated with self account

        https://docs.woox.io/#get-token-deposit-address

        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        """
        # self method is TODO because of networks unification
        await self.load_markets()
        currency = self.currency(code)
        networkCodeDefault = self.default_network_code_for_currency(code)
        networkCode = self.safe_string(params, 'network', networkCodeDefault)
        params = self.omit(params, 'network')
        codeForExchange = networkCode + '_' + currency['code']
        request: dict = {
            'token': codeForExchange,
        }
        response = await self.v1PrivateGetAssetDeposit(self.extend(request, params))
        # {
        #     "success": True,
        #     "address": "3Jmtjx5544T4smrit9Eroe4PCrRkpDeKjP",
        #     "extra": ''
        # }
        tag = self.safe_string(response, 'extra')
        address = self.safe_string(response, 'address')
        self.check_address(address)
        return {
            'info': response,
            'currency': code,
            'network': networkCode,
            'address': address,
            'tag': tag,
        }

    async def get_asset_history_rows(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> Any:
        await self.load_markets()
        request: dict = {}
        currency: Currency = None
        if code is not None:
            currency = self.currency(code)
            request['balance_token'] = currency['id']
        if since is not None:
            request['start_t'] = since
        if limit is not None:
            request['pageSize'] = limit
        transactionType = self.safe_string(params, 'type')
        params = self.omit(params, 'type')
        if transactionType is not None:
            request['type'] = transactionType
        response = await self.v1PrivateGetAssetHistory(self.extend(request, params))
        # {
        #     "rows": [
        #       {
        #         "id": "22010508193900165",
        #         "token": "TRON_USDT",
        #         "extra": '',
        #         "amount": "13.75848500",
        #         "status": "COMPLETED",
        #         "account": null,
        #         "description": null,
        #         "user_id": "42222",
        #         "application_id": "6ad2b303-f354-45c0-8105-9f5f19d0e335",
        #         "external_id": "220105081900134",
        #         "target_address": "TXnyFSnAYad3YCaqtwMw9jvXKkeU39NLnK",
        #         "source_address": "TYDzsYUEpvnYmQk4zGP9sWWcTEd2MiAtW6",
        #         "type": "BALANCE",
        #         "token_side": "DEPOSIT",
        #         "tx_id": "35b0004022f6b3ad07f39a0b7af199f6b258c2c3e2c7cdc93c67efa74fd625ee",
        #         "fee_token": '',
        #         "fee_amount": "0.00000000",
        #         "created_time": "1641370779.442",
        #         "updated_time": "1641370779.465",
        #         "is_new_target_address": null,
        #         "confirmed_number": "29",
        #         "confirming_threshold": "27",
        #         "audit_tag": "1",
        #         "audit_result": "0",
        #         "balance_token": null,  # TODO -write to support, that self seems broken. here should be the token id
        #         "network_name": null  # TODO -write to support, that self seems broken. here should be the network id
        #       }
        #     ],
        #     "meta": {total: '1', records_per_page: "25", current_page: "1"},
        #     "success": True
        # }
        return [currency, self.safe_list(response, 'rows', [])]

    async def fetch_ledger(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[LedgerEntry]:
        """
        fetch the history of changes, actions done by the user or operations that altered balance of the user

        https://docs.woox.io/#get-asset-history

        :param str [code]: unified currency code, default is None
        :param int [since]: timestamp in ms of the earliest ledger entry, default is None
        :param int [limit]: max number of ledger entries to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
        """
        currencyRows = await self.get_asset_history_rows(code, since, limit, params)
        currency = self.safe_value(currencyRows, 0)
        rows = self.safe_list(currencyRows, 1)
        return self.parse_ledger(rows, currency, since, limit, params)

    def parse_ledger_entry(self, item: dict, currency: Currency = None) -> LedgerEntry:
        networkizedCode = self.safe_string(item, 'token')
        currencyDefined = self.get_currency_from_chaincode(networkizedCode, currency)
        code = currencyDefined['code']
        currency = self.safe_currency(code, currency)
        amount = self.safe_number(item, 'amount')
        side = self.safe_string(item, 'token_side')
        direction = 'in' if (side == 'DEPOSIT') else 'out'
        timestamp = self.safe_timestamp(item, 'created_time')
        fee = self.parse_token_and_fee_temp(item, 'fee_token', 'fee_amount')
        return self.safe_ledger_entry({
            'info': item,
            'id': self.safe_string(item, 'id'),
            'currency': code,
            'account': self.safe_string(item, 'account'),
            'referenceAccount': None,
            'referenceId': self.safe_string(item, 'tx_id'),
            'status': self.parse_transaction_status(self.safe_string(item, 'status')),
            'amount': amount,
            'before': None,
            'after': None,
            'direction': direction,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'type': self.parse_ledger_entry_type(self.safe_string(item, 'type')),
            'fee': fee,
        }, currency)

    def parse_ledger_entry_type(self, type):
        types: dict = {
            'BALANCE': 'transaction',  # Funds moved in/out wallet
            'COLLATERAL': 'transfer',  # Funds moved between portfolios
        }
        return self.safe_string(types, type, type)

    def get_currency_from_chaincode(self, networkizedCode, currency):
        if currency is not None:
            return currency
        else:
            parts = networkizedCode.split('_')
            partsLength = len(parts)
            firstPart = self.safe_string(parts, 0)
            currencyId = self.safe_string(parts, 1, firstPart)
            if partsLength > 2:
                currencyId += '_' + self.safe_string(parts, 2)
            currency = self.safe_currency(currencyId)
        return currency

    async def fetch_deposits(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
        """
        fetch all deposits made to an account

        https://docs.woox.io/#get-asset-history

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        request: dict = {
            'token_side': 'DEPOSIT',
        }
        return await self.fetch_deposits_withdrawals(code, since, limit, self.extend(request, params))

    async def fetch_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
        """
        fetch all withdrawals made from an account

        https://docs.woox.io/#get-asset-history

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        request: dict = {
            'token_side': 'WITHDRAW',
        }
        return await self.fetch_deposits_withdrawals(code, since, limit, self.extend(request, params))

    async def fetch_deposits_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
        """
        fetch history of deposits and withdrawals

        https://docs.woox.io/#get-asset-history

        :param str [code]: unified currency code for the currency of the deposit/withdrawals, default is None
        :param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None
        :param int [limit]: max number of deposit/withdrawals to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        request: dict = {
            'type': 'BALANCE',
        }
        currencyRows = await self.get_asset_history_rows(code, since, limit, self.extend(request, params))
        currency = self.safe_value(currencyRows, 0)
        rows = self.safe_list(currencyRows, 1)
        #
        #     {
        #         "rows":[],
        #         "meta":{
        #             "total":0,
        #             "records_per_page":25,
        #             "current_page":1
        #         },
        #         "success":true
        #     }
        #
        return self.parse_transactions(rows, currency, since, limit, params)

    def parse_transaction(self, transaction: dict, currency: Currency = None) -> Transaction:
        # example in fetchLedger
        networkizedCode = self.safe_string(transaction, 'token')
        currencyDefined = self.get_currency_from_chaincode(networkizedCode, currency)
        code = currencyDefined['code']
        movementDirection = self.safe_string_lower(transaction, 'token_side')
        if movementDirection == 'withdraw':
            movementDirection = 'withdrawal'
        fee = self.parse_token_and_fee_temp(transaction, 'fee_token', 'fee_amount')
        addressTo = self.safe_string(transaction, 'target_address')
        addressFrom = self.safe_string(transaction, 'source_address')
        timestamp = self.safe_timestamp(transaction, 'created_time')
        return {
            'info': transaction,
            'id': self.safe_string_2(transaction, 'id', 'withdraw_id'),
            'txid': self.safe_string(transaction, 'tx_id'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'address': None,
            'addressFrom': addressFrom,
            'addressTo': addressTo,
            'tag': self.safe_string(transaction, 'extra'),
            'tagFrom': None,
            'tagTo': None,
            'type': movementDirection,
            'amount': self.safe_number(transaction, 'amount'),
            'currency': code,
            'status': self.parse_transaction_status(self.safe_string(transaction, 'status')),
            'updated': self.safe_timestamp(transaction, 'updated_time'),
            'comment': None,
            'internal': None,
            'fee': fee,
            'network': None,
        }

    def parse_transaction_status(self, status: Str):
        statuses: dict = {
            'NEW': 'pending',
            'CONFIRMING': 'pending',
            'PROCESSING': 'pending',
            'COMPLETED': 'ok',
            'CANCELED': 'canceled',
        }
        return self.safe_string(statuses, status, status)

    async def transfer(self, code: str, amount: float, fromAccount: str, toAccount: str, params={}) -> TransferEntry:
        """
        transfer currency internally between wallets on the same account

        https://docs.woox.io/#get-transfer-history

        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account to transfer from
        :param str toAccount: account to transfer to
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        """
        await self.load_markets()
        currency = self.currency(code)
        request: dict = {
            'token': currency['id'],
            'amount': self.parse_to_numeric(amount),
            'from_application_id': fromAccount,
            'to_application_id': toAccount,
        }
        response = await self.v1PrivatePostAssetMainSubTransfer(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #         "id": 200
        #     }
        #
        transfer = self.parse_transfer(response, currency)
        transferOptions = self.safe_dict(self.options, 'transfer', {})
        fillResponseFromRequest = self.safe_bool(transferOptions, 'fillResponseFromRequest', True)
        if fillResponseFromRequest:
            transfer['amount'] = amount
            transfer['fromAccount'] = fromAccount
            transfer['toAccount'] = toAccount
        return transfer

    async def fetch_transfers(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[TransferEntry]:
        """
        fetch a history of internal transfers made on an account

        https://docs.woox.io/#get-transfer-history

        :param str code: unified currency code of the currency transferred
        :param int [since]: the earliest time in ms to fetch transfers for
        :param int [limit]: the maximum number of  transfers structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch entries for
        :returns dict[]: a list of `transfer structures <https://docs.ccxt.com/#/?id=transfer-structure>`
        """
        request: dict = {}
        if limit is not None:
            request['size'] = limit
        if since is not None:
            request['start_t'] = since
        until = self.safe_integer(params, 'until')  # unified in milliseconds
        params = self.omit(params, ['until'])
        if until is not None:
            request['end_t'] = until
        response = await self.v1PrivateGetAssetMainSubTransferHistory(self.extend(request, params))
        #
        #     {
        #         "rows": [
        #             {
        #                 "id": 46704,
        #                 "token": "USDT",
        #                 "amount": 30000.00000000,
        #                 "status": "COMPLETED",
        #                 "from_application_id": "0f1bd3cd-dba2-4563-b8bb-0adb1bfb83a3",
        #                 "to_application_id": "c01e6940-a735-4022-9b6c-9d3971cdfdfa",
        #                 "from_user": "LeverageLow",
        #                 "to_user": "dev",
        #                 "created_time": "1709022325.427",
        #                 "updated_time": "1709022325.542"
        #             }
        #         ],
        #         "meta": {
        #             "total": 50,
        #             "records_per_page": 25,
        #             "current_page": 1
        #         },
        #         "success": True
        #     }
        #
        data = self.safe_list(response, 'rows', [])
        return self.parse_transfers(data, None, since, limit, params)

    def parse_transfer(self, transfer: dict, currency: Currency = None) -> TransferEntry:
        #
        #    fetchTransfers
        #     {
        #         "id": 46704,
        #         "token": "USDT",
        #         "amount": 30000.00000000,
        #         "status": "COMPLETED",
        #         "from_application_id": "0f1bd3cd-dba2-4563-b8bb-0adb1bfb83a3",
        #         "to_application_id": "c01e6940-a735-4022-9b6c-9d3971cdfdfa",
        #         "from_user": "LeverageLow",
        #         "to_user": "dev",
        #         "created_time": "1709022325.427",
        #         "updated_time": "1709022325.542"
        #     }
        #
        #    transfer
        #        {
        #            "success": True,
        #            "id": 200
        #        }
        #
        networkizedCode = self.safe_string(transfer, 'token')
        currencyDefined = self.get_currency_from_chaincode(networkizedCode, currency)
        code = currencyDefined['code']
        timestamp = self.safe_timestamp(transfer, 'created_time')
        success = self.safe_bool(transfer, 'success')
        status: Str = None
        if success is not None:
            status = 'ok' if success else 'failed'
        return {
            'id': self.safe_string(transfer, 'id'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'currency': code,
            'amount': self.safe_number(transfer, 'amount'),
            'fromAccount': self.safe_string(transfer, 'from_application_id'),
            'toAccount': self.safe_string(transfer, 'to_application_id'),
            'status': self.parse_transfer_status(self.safe_string(transfer, 'status', status)),
            'info': transfer,
        }

    def parse_transfer_status(self, status: Str) -> Str:
        statuses: dict = {
            'NEW': 'pending',
            'CONFIRMING': 'pending',
            'PROCESSING': 'pending',
            'COMPLETED': 'ok',
            'CANCELED': 'canceled',
        }
        return self.safe_string(statuses, status, status)

    async def withdraw(self, code: str, amount: float, address: str, tag=None, params={}) -> Transaction:
        """
        make a withdrawal

        https://docs.woox.io/#token-withdraw

        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        tag, params = self.handle_withdraw_tag_and_params(tag, params)
        await self.load_markets()
        self.check_address(address)
        currency = self.currency(code)
        request: dict = {
            'amount': amount,
            'address': address,
        }
        if tag is not None:
            request['extra'] = tag
        networks = self.safe_dict(self.options, 'networks', {})
        currencyNetworks = self.safe_dict(currency, 'networks', {})
        network = self.safe_string_upper(params, 'network')
        networkId = self.safe_string(networks, network, network)
        coinNetwork = self.safe_dict(currencyNetworks, networkId, {})
        coinNetworkId = self.safe_string(coinNetwork, 'id')
        if coinNetworkId is None:
            raise BadRequest(self.id + ' withdraw() require network parameter')
        request['token'] = coinNetworkId
        response = await self.v1PrivatePostAssetWithdraw(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #         "withdraw_id": "20200119145703654"
        #     }
        #
        return self.parse_transaction(response, currency)

    async def repay_margin(self, code: str, amount: float, symbol: Str = None, params={}):
        """
        repay borrowed margin and interest

        https://docs.woox.io/#repay-interest

        :param str code: unified currency code of the currency to repay
        :param float amount: the amount to repay
        :param str symbol: not used by woo.repayMargin()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin loan structure <https://docs.ccxt.com/#/?id=margin-loan-structure>`
        """
        await self.load_markets()
        market: Market = None
        if symbol is not None:
            market = self.market(symbol)
            symbol = market['symbol']
        currency = self.currency(code)
        request: dict = {
            'token': currency['id'],  # interest token that you want to repay
            'amount': self.currency_to_precision(code, amount),
        }
        response = await self.v1PrivatePostInterestRepay(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #     }
        #
        transaction = self.parse_margin_loan(response, currency)
        return self.extend(transaction, {
            'amount': amount,
            'symbol': symbol,
        })

    def parse_margin_loan(self, info, currency: Currency = None):
        #
        #     {
        #         "success": True,
        #     }
        #
        return {
            'id': None,
            'currency': self.safe_currency_code(None, currency),
            'amount': None,
            'symbol': None,
            'timestamp': None,
            'datetime': None,
            'info': info,
        }

    def nonce(self):
        return self.milliseconds() - self.options['timeDifference']

    def sign(self, path, section='public', method='GET', params={}, headers=None, body=None):
        version = section[0]
        access = section[1]
        pathWithParams = self.implode_params(path, params)
        url = self.implode_hostname(self.urls['api'][access])
        url += '/' + version + '/'
        params = self.omit(params, self.extract_params(path))
        params = self.keysort(params)
        if access == 'public':
            url += access + '/' + pathWithParams
            if params:
                url += '?' + self.urlencode(params)
        elif access == 'pub':
            url += pathWithParams
            if params:
                url += '?' + self.urlencode(params)
        else:
            self.check_required_credentials()
            if method == 'POST' and (path == 'algo/order' or path == 'order'):
                isSandboxMode = self.safe_bool(self.options, 'sandboxMode', False)
                if not isSandboxMode:
                    applicationId = 'bc830de7-50f3-460b-9ee0-f430f83f9dad'
                    brokerId = self.safe_string(self.options, 'brokerId', applicationId)
                    isTrigger = path.find('algo') > -1
                    if isTrigger:
                        params['brokerId'] = brokerId
                    else:
                        params['broker_id'] = brokerId
                params = self.keysort(params)
            auth = ''
            ts = str(self.nonce())
            url += pathWithParams
            headers = {
                'x-api-key': self.apiKey,
                'x-api-timestamp': ts,
            }
            if version == 'v3':
                auth = ts + method + '/' + version + '/' + pathWithParams
                if method == 'POST' or method == 'PUT' or method == 'DELETE':
                    body = self.json(params)
                    auth += body
                else:
                    if params:
                        query = self.urlencode(params)
                        url += '?' + query
                        auth += '?' + query
                headers['content-type'] = 'application/json'
            else:
                auth = self.urlencode(params)
                if method == 'POST' or method == 'PUT' or method == 'DELETE':
                    body = auth
                else:
                    if params:
                        url += '?' + auth
                auth += '|' + ts
                headers['content-type'] = 'application/x-www-form-urlencoded'
            headers['x-api-signature'] = self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha256)
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, httpCode: int, reason: str, url: str, method: str, headers: dict, body: str, response, requestHeaders, requestBody):
        if not response:
            return None  # fallback to default error handler
        #
        #     400 Bad Request {"success":false,"code":-1012,"message":"Amount is required for buy market orders when margin disabled."}
        #                     {"code":"-1011","message":"The system is under maintenance.","success":false}
        #
        success = self.safe_bool(response, 'success')
        errorCode = self.safe_string(response, 'code')
        if not success:
            feedback = self.id + ' ' + self.json(response)
            self.throw_broadly_matched_exception(self.exceptions['broad'], body, feedback)
            self.throw_exactly_matched_exception(self.exceptions['exact'], errorCode, feedback)
        return None

    def parse_income(self, income, market: Market = None):
        #
        #     {
        #         "id":666666,
        #         "symbol":"PERP_BTC_USDT",
        #         "funding_rate":0.00001198,
        #         "mark_price":28941.04000000,
        #         "funding_fee":0.00069343,
        #         "payment_type":"Pay",
        #         "status":"COMPLETED",
        #         "created_time":"1653616000.666",
        #         "updated_time":"1653616000.605"
        #     }
        #
        marketId = self.safe_string(income, 'symbol')
        symbol = self.safe_symbol(marketId, market)
        amount = self.safe_string(income, 'funding_fee')
        code = self.safe_currency_code('USD')
        id = self.safe_string(income, 'id')
        timestamp = self.safe_timestamp(income, 'updated_time')
        rate = self.safe_number(income, 'funding_rate')
        paymentType = self.safe_string(income, 'payment_type')
        amount = Precise.string_neg(amount) if (paymentType == 'Pay') else amount
        return {
            'info': income,
            'symbol': symbol,
            'code': code,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'id': id,
            'amount': self.parse_number(amount),
            'rate': rate,
        }

    async def fetch_funding_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        fetch the history of funding payments paid and received on self account

        https://docs.woox.io/#get-funding-fee-history

        :param str [symbol]: unified market symbol
        :param int [since]: the earliest time in ms to fetch funding history for
        :param int [limit]: the maximum number of funding history structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict: a `funding history structure <https://docs.ccxt.com/#/?id=funding-history-structure>`
        """
        await self.load_markets()
        paginate = False
        paginate, params = self.handle_option_and_params(params, 'fetchFundingHistory', 'paginate')
        if paginate:
            return await self.fetch_paginated_call_cursor('fetchFundingHistory', symbol, since, limit, params, 'page', 'page', 1, 500)
        request: dict = {}
        market: Market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            request['start_t'] = since
        if limit is not None:
            request['size'] = limit
        else:
            request['size'] = 5000
        response = await self.v1PrivateGetFundingFeeHistory(self.extend(request, params))
        #
        #     {
        #         "rows":[
        #             {
        #                 "id":666666,
        #                 "symbol":"PERP_BTC_USDT",
        #                 "funding_rate":0.00001198,
        #                 "mark_price":28941.04000000,
        #                 "funding_fee":0.00069343,
        #                 "payment_type":"Pay",
        #                 "status":"COMPLETED",
        #                 "created_time":"1653616000.666",
        #                 "updated_time":"1653616000.605"
        #             }
        #         ],
        #         "meta":{
        #             "total":235,
        #             "records_per_page":25,
        #             "current_page":1
        #         },
        #         "success":true
        #     }
        #
        meta = self.safe_dict(response, 'meta', {})
        cursor = self.safe_integer(meta, 'current_page')
        result = self.safe_list(response, 'rows', [])
        resultLength = len(result)
        if resultLength > 0:
            lastItem = result[resultLength - 1]
            lastItem['page'] = cursor
            result[resultLength - 1] = lastItem
        return self.parse_incomes(result, market, since, limit)

    def parse_funding_rate(self, fundingRate, market: Market = None) -> FundingRate:
        #
        #     {
        #         "success": True,
        #         "timestamp": 1727427915529,
        #         "symbol": "PERP_BTC_USDT",
        #         "est_funding_rate": -0.00092719,
        #         "est_funding_rate_timestamp": 1727427899060,
        #         "last_funding_rate": -0.00092610,
        #         "last_funding_rate_timestamp": 1727424000000,
        #         "next_funding_time": 1727452800000,
        #         "last_funding_rate_interval": 8,
        #         "est_funding_rate_interval": 8
        #     }
        #
        symbol = self.safe_string(fundingRate, 'symbol')
        market = self.market(symbol)
        nextFundingTimestamp = self.safe_integer(fundingRate, 'next_funding_time')
        estFundingRateTimestamp = self.safe_integer(fundingRate, 'est_funding_rate_timestamp')
        lastFundingRateTimestamp = self.safe_integer(fundingRate, 'last_funding_rate_timestamp')
        intervalString = self.safe_string(fundingRate, 'est_funding_rate_interval')
        return {
            'info': fundingRate,
            'symbol': market['symbol'],
            'markPrice': None,
            'indexPrice': None,
            'interestRate': self.parse_number('0'),
            'estimatedSettlePrice': None,
            'timestamp': estFundingRateTimestamp,
            'datetime': self.iso8601(estFundingRateTimestamp),
            'fundingRate': self.safe_number(fundingRate, 'est_funding_rate'),
            'fundingTimestamp': nextFundingTimestamp,
            'fundingDatetime': self.iso8601(nextFundingTimestamp),
            'nextFundingRate': None,
            'nextFundingTimestamp': None,
            'nextFundingDatetime': None,
            'previousFundingRate': self.safe_number(fundingRate, 'last_funding_rate'),
            'previousFundingTimestamp': lastFundingRateTimestamp,
            'previousFundingDatetime': self.iso8601(lastFundingRateTimestamp),
            'interval': intervalString + 'h',
        }

    async def fetch_funding_interval(self, symbol: str, params={}) -> FundingRate:
        """
        fetch the current funding rate interval

        https://docs.woox.io/#get-predicted-funding-rate-for-one-market-public

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        """
        return await self.fetch_funding_rate(symbol, params)

    async def fetch_funding_rate(self, symbol: str, params={}) -> FundingRate:
        """
        fetch the current funding rate

        https://docs.woox.io/#get-predicted-funding-rate-for-one-market-public

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = await self.v1PublicGetFundingRateSymbol(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #         "timestamp": 1727428037877,
        #         "symbol": "PERP_BTC_USDT",
        #         "est_funding_rate": -0.00092674,
        #         "est_funding_rate_timestamp": 1727428019064,
        #         "last_funding_rate": -0.00092610,
        #         "last_funding_rate_timestamp": 1727424000000,
        #         "next_funding_time": 1727452800000,
        #         "last_funding_rate_interval": 8,
        #         "est_funding_rate_interval": 8
        #     }
        #
        return self.parse_funding_rate(response, market)

    async def fetch_funding_rates(self, symbols: Strings = None, params={}) -> FundingRates:
        """
        fetch the funding rate for multiple markets

        https://docs.woox.io/#get-predicted-funding-rate-for-all-markets-public

        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rates-structure>`, indexed by market symbols
        """
        await self.load_markets()
        symbols = self.market_symbols(symbols)
        response = await self.v1PublicGetFundingRates(params)
        #
        #     {
        #         "success":true,
        #         "rows":[
        #             {
        #                 "symbol":"PERP_AAVE_USDT",
        #                 "est_funding_rate":-0.00003447,
        #                 "est_funding_rate_timestamp":1653633959001,
        #                 "last_funding_rate":-0.00002094,
        #                 "last_funding_rate_timestamp":1653631200000,
        #                 "next_funding_time":1653634800000
        #             }
        #         ],
        #         "timestamp":1653633985646
        #     }
        #
        rows = self.safe_list(response, 'rows', [])
        return self.parse_funding_rates(rows, symbols)

    async def fetch_funding_rate_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        fetches historical funding rate prices

        https://docs.woox.io/#get-funding-rate-history-for-one-market-public

        :param str symbol: unified symbol of the market to fetch the funding rate history for
        :param int [since]: timestamp in ms of the earliest funding rate to fetch
        :param int [limit]: the maximum amount of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>` to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest funding rate
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
        """
        await self.load_markets()
        paginate = False
        paginate, params = self.handle_option_and_params(params, 'fetchFundingRateHistory', 'paginate')
        if paginate:
            return await self.fetch_paginated_call_incremental('fetchFundingRateHistory', symbol, since, limit, params, 'page', 25)
        request: dict = {}
        if symbol is not None:
            market = self.market(symbol)
            symbol = market['symbol']
            request['symbol'] = market['id']
        if since is not None:
            request['start_t'] = self.parse_to_int(since / 1000)
        request, params = self.handle_until_option('end_t', request, params, 0.001)
        response = await self.v1PublicGetFundingRateHistory(self.extend(request, params))
        #
        #     {
        #         "success":true,
        #         "meta":{
        #             "total":2464,
        #             "records_per_page":25,
        #             "current_page":1
        #         },
        #         "rows":[
        #             {
        #                 "symbol":"PERP_BTC_USDT",
        #                 "funding_rate":0.00000629,
        #                 "funding_rate_timestamp":1653638400000,
        #                 "next_funding_time":1653642000000
        #             }
        #         ],
        #         "timestamp":1653640814885
        #     }
        #
        result = self.safe_list(response, 'rows')
        rates = []
        for i in range(0, len(result)):
            entry = result[i]
            marketId = self.safe_string(entry, 'symbol')
            timestamp = self.safe_integer(entry, 'funding_rate_timestamp')
            rates.append({
                'info': entry,
                'symbol': self.safe_symbol(marketId),
                'fundingRate': self.safe_number(entry, 'funding_rate'),
                'timestamp': timestamp,
                'datetime': self.iso8601(timestamp),
            })
        sorted = self.sort_by(rates, 'timestamp')
        return self.filter_by_symbol_since_limit(sorted, symbol, since, limit)

    async def set_position_mode(self, hedged: bool, symbol: Str = None, params={}):
        """
        set hedged to True or False for a market

        https://docs.woox.io/#update-position-mode

        :param bool hedged: set to True to use HEDGE_MODE, False for ONE_WAY
        :param str symbol: not used by woo setPositionMode
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        """
        hedgeMode = None
        if hedged:
            hedgeMode = 'HEDGE_MODE'
        else:
            hedgeMode = 'ONE_WAY'
        request: dict = {
            'position_mode': hedgeMode,
        }
        response = await self.v1PrivatePostClientPositionMode(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #         "data": {},
        #         "timestamp": "1709195608551"
        #     }
        #
        return response

    async def fetch_leverage(self, symbol: str, params={}) -> Leverage:
        """
        fetch the set leverage for a market

        https://docs.woox.io/#get-account-information-new

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: *for swap markets only* 'cross' or 'isolated'
        :param str [params.position_mode]: *for swap markets only* 'ONE_WAY' or 'HEDGE_MODE'
        :returns dict: a `leverage structure <https://docs.ccxt.com/#/?id=leverage-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        response: dict = None
        if market['spot']:
            response = await self.v3PrivateGetAccountinfo(params)
            #
            #     {
            #         "success": True,
            #         "data": {
            #             "applicationId": "dsa",
            #             "account": "dsa",
            #             "alias": "haha",
            #             "accountMode": "MARGIN",
            #             "leverage": 1,
            #             "takerFeeRate": 1,
            #             "makerFeeRate": 1,
            #             "interestRate": 1,
            #             "futuresTakerFeeRate": 1,
            #             "futuresMakerFeeRate": 1,
            #             "otpauth": True,
            #             "marginRatio": 1,
            #             "openMarginRatio": 1,
            #             "initialMarginRatio": 1,
            #             "maintenanceMarginRatio": 1,
            #             "totalCollateral": 1,
            #             "freeCollateral": 1,
            #             "totalAccountValue": 1,
            #             "totalVaultValue": 1,
            #             "totalStakingValue": 1
            #         },
            #         "timestamp": 1673323685109
            #     }
            #
        elif market['swap']:
            request: dict = {
                'symbol': market['id'],
            }
            marginMode: Str = None
            marginMode, params = self.handle_margin_mode_and_params('fetchLeverage', params, 'cross')
            request['margin_mode'] = self.encode_margin_mode(marginMode)
            response = await self.v1PrivateGetClientFuturesLeverage(self.extend(request, params))
            #
            # HEDGE_MODE
            #     {
            #         "success": True,
            #         "data":
            #             {
            #                 "symbol": "PERP_ETH_USDT",
            #                 "default_margin_mode": "CROSS",
            #                 "position_mode": "HEDGE_MODE",
            #                 "details":  [
            #                     {
            #                         "position_side": "LONG",
            #                         "leverage": 10
            #                     },
            #                     {
            #                         "position_side": "SHORT",
            #                         "leverage": 10
            #                     }
            #                 ]
            #             },
            #         "timestamp": 1720886470482
            #     }
            #
            # ONE_WAY
            #     {
            #         "success": True,
            #         "data": {
            #             "symbol": "PERP_ETH_USDT",
            #             "default_margin_mode": "ISOLATED",
            #             "position_mode": "ONE_WAY",
            #             "details": [
            #                 {
            #                     "position_side": "BOTH",
            #                     "leverage": 10
            #                 }
            #             ]
            #         },
            #         "timestamp": 1720886810317
            #     }
            #
        else:
            raise NotSupported(self.id + ' fetchLeverage() is not supported for ' + market['type'] + ' markets')
        data = self.safe_dict(response, 'data', {})
        return self.parse_leverage(data, market)

    def parse_leverage(self, leverage: dict, market: Market = None) -> Leverage:
        marketId = self.safe_string(leverage, 'symbol')
        market = self.safe_market(marketId, market)
        marginMode = self.safe_string_lower(leverage, 'default_margin_mode')
        spotLeverage = self.safe_integer(leverage, 'leverage')
        longLeverage = spotLeverage
        shortLeverage = spotLeverage
        details = self.safe_list(leverage, 'details', [])
        for i in range(0, len(details)):
            position = self.safe_dict(details, i, {})
            positionLeverage = self.safe_integer(position, 'leverage')
            side = self.safe_string(position, 'position_side')
            if side == 'BOTH':
                longLeverage = positionLeverage
                shortLeverage = positionLeverage
            elif side == 'LONG':
                longLeverage = positionLeverage
            elif side == 'SHORT':
                shortLeverage = positionLeverage
        return {
            'info': leverage,
            'symbol': market['symbol'],
            'marginMode': marginMode,
            'longLeverage': longLeverage,
            'shortLeverage': shortLeverage,
        }

    async def set_leverage(self, leverage: Int, symbol: Str = None, params={}):
        """
        set the level of leverage for a market

        https://docs.woox.io/#update-leverage-setting
        https://docs.woox.io/#update-futures-leverage-setting

        :param float leverage: the rate of leverage(1, 2, 3, 4 or 5 for spot markets, 1, 2, 3, 4, 5, 10, 15, 20 for swap markets)
        :param str [symbol]: unified market symbol(is mandatory for swap markets)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: *for swap markets only* 'cross' or 'isolated'
        :param str [params.position_side]: *for swap markets only* 'LONG' or 'SHORT' in hedge mode, 'BOTH' in one way mode.
        :returns dict: response from the exchange
        """
        await self.load_markets()
        request: dict = {
            'leverage': leverage,
        }
        market: Market = None
        if symbol is not None:
            market = self.market(symbol)
        if (symbol is None) or market['spot']:
            return await self.v1PrivatePostClientLeverage(self.extend(request, params))
        elif market['swap']:
            request['symbol'] = market['id']
            marginMode: Str = None
            marginMode, params = self.handle_margin_mode_and_params('fetchLeverage', params, 'cross')
            request['margin_mode'] = self.encode_margin_mode(marginMode)
            return await self.v1PrivatePostClientFuturesLeverage(self.extend(request, params))
        else:
            raise NotSupported(self.id + ' fetchLeverage() is not supported for ' + market['type'] + ' markets')

    async def add_margin(self, symbol: str, amount: float, params={}) -> MarginModification:
        """
        add margin

        https://docs.woox.io/#update-isolated-margin-setting

        :param str symbol: unified market symbol
        :param float amount: amount of margin to add
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.position_side]: 'LONG' or 'SHORT' in hedge mode, 'BOTH' in one way mode
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=add-margin-structure>`
        """
        return await self.modify_margin_helper(symbol, amount, 'ADD', params)

    async def reduce_margin(self, symbol: str, amount: float, params={}) -> MarginModification:
        """
        remove margin from a position

        https://docs.woox.io/#update-isolated-margin-setting

        :param str symbol: unified market symbol
        :param float amount: amount of margin to remove
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.position_side]: 'LONG' or 'SHORT' in hedge mode, 'BOTH' in one way mode
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=reduce-margin-structure>`
        """
        return await self.modify_margin_helper(symbol, amount, 'REDUCE', params)

    async def modify_margin_helper(self, symbol: str, amount, type, params={}) -> MarginModification:
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
            'adjust_token': 'USDT',  # todo check
            'adjust_amount': amount,
            'action': type,
        }
        return await self.v1PrivatePostClientIsolatedMargin(self.extend(request, params))

    async def fetch_position(self, symbol: Str, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = await self.v1PrivateGetPositionSymbol(self.extend(request, params))
        #
        #     {
        #         "symbol": "PERP_ETH_USDT",
        #         "position_side": "BOTH",
        #         "leverage": 10,
        #         "margin_mode": "CROSS",
        #         "average_open_price": 3139.9,
        #         "isolated_margin_amount": 0.0,
        #         "isolated_margin_token": "",
        #         "opening_time": "1720627963.094",
        #         "mark_price": 3155.19169891,
        #         "pending_short_qty": 0.0,
        #         "pending_long_qty": 0.0,
        #         "holding": -0.7,
        #         "pnl_24_h": 0.0,
        #         "est_liq_price": 9107.40055552,
        #         "settle_price": 3151.0319904,
        #         "success": True,
        #         "fee_24_h": 0.0,
        #         "isolated_frozen_long": 0.0,
        #         "isolated_frozen_short": 0.0,
        #         "timestamp": "1720867502.544"
        #     }
        #
        return self.parse_position(response, market)

    async def fetch_positions(self, symbols: Strings = None, params={}) -> List[Position]:
        await self.load_markets()
        response = await self.v3PrivateGetPositions(params)
        #
        #     {
        #         "success": True,
        #         "data":
        #         {
        #             "positions": [
        #                 {
        #                     "symbol": "PERP_ETH_USDT",
        #                     "holding": -1.0,
        #                     "pendingLongQty": 0.0,
        #                     "pendingShortQty": 0.0,
        #                     "settlePrice": 3143.2,
        #                     "averageOpenPrice": 3143.2,
        #                     "pnl24H": 0.0,
        #                     "fee24H": 1.5716,
        #                     "markPrice": 3134.97984158,
        #                     "estLiqPrice": 3436.176349,
        #                     "timestamp": 1720628031.463,
        #                     "adlQuantile": 5,
        #                     "positionSide": "BOTH",
        #                     "marginMode": "ISOLATED",
        #                     "isolatedMarginToken": "USDT",
        #                     "isolatedMarginAmount": 314.62426,
        #                     "isolatedFrozenLong": 0.0,
        #                     "isolatedFrozenShort": 0.0,
        #                     "leverage": 10
        #                 },
        #                 {
        #                     "symbol": "PERP_SOL_USDT",
        #                     "holding": -1.0,
        #                     "pendingLongQty": 0.0,
        #                     "pendingShortQty": 0.0,
        #                     "settlePrice": 141.89933923,
        #                     "averageOpenPrice": 171.38,
        #                     "pnl24H": 0.0,
        #                     "fee24H": 0.0,
        #                     "markPrice": 141.65155427,
        #                     "estLiqPrice": 4242.73548551,
        #                     "timestamp": 1720616702.68,
        #                     "adlQuantile": 5,
        #                     "positionSide": "BOTH",
        #                     "marginMode": "CROSS",
        #                     "isolatedMarginToken": "",
        #                     "isolatedMarginAmount": 0.0,
        #                     "isolatedFrozenLong": 0.0,
        #                     "isolatedFrozenShort": 0.0,
        #                     "leverage": 10
        #                 }
        #             ]
        #         },
        #         "timestamp": 1720628675078
        #     }
        #
        result = self.safe_dict(response, 'data', {})
        positions = self.safe_list(result, 'positions', [])
        return self.parse_positions(positions, symbols)

    def parse_position(self, position: dict, market: Market = None):
        #
        # v1PrivateGetPositionSymbol
        #     {
        #         "symbol": "PERP_ETH_USDT",
        #         "position_side": "BOTH",
        #         "leverage": 10,
        #         "margin_mode": "CROSS",
        #         "average_open_price": 3139.9,
        #         "isolated_margin_amount": 0.0,
        #         "isolated_margin_token": "",
        #         "opening_time": "1720627963.094",
        #         "mark_price": 3155.19169891,
        #         "pending_short_qty": 0.0,
        #         "pending_long_qty": 0.0,
        #         "holding": -0.7,
        #         "pnl_24_h": 0.0,
        #         "est_liq_price": 9107.40055552,
        #         "settle_price": 3151.0319904,
        #         "success": True,
        #         "fee_24_h": 0.0,
        #         "isolated_frozen_long": 0.0,
        #         "isolated_frozen_short": 0.0,
        #         "timestamp": "1720867502.544"
        #     }
        #
        # v3PrivateGetPositions
        #     {
        #         "symbol": "PERP_ETH_USDT",
        #         "holding": -1.0,
        #         "pendingLongQty": 0.0,  # todo: check
        #         "pendingShortQty": 0.0,  # todo: check
        #         "settlePrice": 3143.2,
        #         "averageOpenPrice": 3143.2,
        #         "pnl24H": 0.0,  # todo: check
        #         "fee24H": 1.5716,  # todo: check
        #         "markPrice": 3134.97984158,
        #         "estLiqPrice": 3436.176349,
        #         "timestamp": 1720628031.463,
        #         "adlQuantile": 5,
        #         "positionSide": "BOTH",
        #         "marginMode": "ISOLATED",
        #         "isolatedMarginToken": "USDT",  # todo: check
        #         "isolatedMarginAmount": 314.62426,  # todo: check
        #         "isolatedFrozenLong": 0.0,  # todo: check
        #         "isolatedFrozenShort": 0.0,  # todo: check
        #         "leverage": 10
        #     }
        #
        contract = self.safe_string(position, 'symbol')
        market = self.safe_market(contract, market)
        size = self.safe_string(position, 'holding')
        side: Str = None
        if Precise.string_gt(size, '0'):
            side = 'long'
        else:
            side = 'short'
        contractSize = self.safe_string(market, 'contractSize')
        markPrice = self.safe_string_2(position, 'markPrice', 'mark_price')
        timestamp = self.safe_timestamp(position, 'timestamp')
        entryPrice = self.safe_string_2(position, 'averageOpenPrice', 'average_open_price')
        priceDifference = Precise.string_sub(markPrice, entryPrice)
        unrealisedPnl = Precise.string_mul(priceDifference, size)
        size = Precise.string_abs(size)
        notional = Precise.string_mul(size, markPrice)
        positionSide = self.safe_string(position, 'positionSide')  # 'SHORT' or 'LONG' for hedged, 'BOTH' for non-hedged
        return self.safe_position({
            'info': position,
            'id': None,
            'symbol': self.safe_string(market, 'symbol'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastUpdateTimestamp': None,
            'initialMargin': None,
            'initialMarginPercentage': None,
            'maintenanceMargin': None,
            'maintenanceMarginPercentage': None,
            'entryPrice': self.parse_number(entryPrice),
            'notional': self.parse_number(notional),
            'leverage': self.safe_number(position, 'leverage'),
            'unrealizedPnl': self.parse_number(unrealisedPnl),
            'contracts': self.parse_number(size),
            'contractSize': self.parse_number(contractSize),
            'marginRatio': None,
            'liquidationPrice': self.safe_number_2(position, 'estLiqPrice', 'est_liq_price'),
            'markPrice': self.parse_number(markPrice),
            'lastPrice': None,
            'collateral': None,
            'marginMode': self.safe_string_lower_2(position, 'marginMode', 'margin_mode'),
            'side': side,
            'percentage': None,
            'hedged': positionSide != 'BOTH',
            'stopLossPrice': None,
            'takeProfitPrice': None,
        })

    async def fetch_convert_quote(self, fromCode: str, toCode: str, amount: Num = None, params={}) -> Conversion:
        """
        fetch a quote for converting from one currency to another

        https://docs.woox.io/#get-quote-rfq

        :param str fromCode: the currency that you want to sell and convert from
        :param str toCode: the currency that you want to buy and convert into
        :param float [amount]: how much you want to trade in units of the from currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
        """
        await self.load_markets()
        request: dict = {
            'sellToken': fromCode.upper(),
            'buyToken': toCode.upper(),
            'sellQuantity': self.number_to_string(amount),
        }
        response = await self.v3PrivateGetConvertRfq(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #         "data": {
        #             "quoteId": 123123123,
        #             "counterPartyId": "",
        #             "sellToken": "ETH",
        #             "sellQuantity": "0.0445",
        #             "buyToken": "USDT",
        #             "buyQuantity": "33.45",
        #             "buyPrice": "6.77",
        #             "expireTimestamp": 1659084466000,
        #             "message": 1659084466000
        #         }
        #     }
        #
        data = self.safe_dict(response, 'data', {})
        fromCurrencyId = self.safe_string(data, 'sellToken', fromCode)
        fromCurrency = self.currency(fromCurrencyId)
        toCurrencyId = self.safe_string(data, 'buyToken', toCode)
        toCurrency = self.currency(toCurrencyId)
        return self.parse_conversion(data, fromCurrency, toCurrency)

    async def create_convert_trade(self, id: str, fromCode: str, toCode: str, amount: Num = None, params={}) -> Conversion:
        """
        convert from one currency to another

        https://docs.woox.io/#send-quote-rft

        :param str id: the id of the trade that you want to make
        :param str fromCode: the currency that you want to sell and convert from
        :param str toCode: the currency that you want to buy and convert into
        :param float [amount]: how much you want to trade in units of the from currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
        """
        await self.load_markets()
        request: dict = {
            'quoteId': id,
        }
        response = await self.v3PrivatePostConvertRft(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #         "data": {
        #             "quoteId": 123123123,
        #             "counterPartyId": "",
        #             "rftAccepted": 1  # 1 -> success; 2 -> processing; 3 -> fail
        #         }
        #     }
        #
        data = self.safe_dict(response, 'data', {})
        return self.parse_conversion(data)

    async def fetch_convert_trade(self, id: str, code: Str = None, params={}) -> Conversion:
        """
        fetch the data for a conversion trade

        https://docs.woox.io/#get-quote-trade

        :param str id: the id of the trade that you want to fetch
        :param str [code]: the unified currency code of the conversion trade
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
        """
        await self.load_markets()
        request: dict = {
            'quoteId': id,
        }
        response = await self.v3PrivateGetConvertTrade(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #         "data": {
        #             "quoteId": 12,
        #             "buyAsset": "",
        #             "sellAsset": "",
        #             "buyAmount": 12.11,
        #             "sellAmount": 12.11,
        #             "tradeStatus": 12,
        #             "createdTime": ""
        #         }
        #     }
        #
        data = self.safe_dict(response, 'data', {})
        fromCurrencyId = self.safe_string(data, 'sellAsset')
        toCurrencyId = self.safe_string(data, 'buyAsset')
        fromCurrency = None
        toCurrency = None
        if fromCurrencyId is not None:
            fromCurrency = self.currency(fromCurrencyId)
        if toCurrencyId is not None:
            toCurrency = self.currency(toCurrencyId)
        return self.parse_conversion(data, fromCurrency, toCurrency)

    async def fetch_convert_trade_history(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Conversion]:
        """
        fetch the users history of conversion trades

        https://docs.woox.io/#get-quote-trades

        :param str [code]: the unified currency code
        :param int [since]: the earliest time in ms to fetch conversions for
        :param int [limit]: the maximum number of conversion structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest conversion to fetch
        :returns dict[]: a list of `conversion structures <https://docs.ccxt.com/#/?id=conversion-structure>`
        """
        await self.load_markets()
        request: dict = {}
        request, params = self.handle_until_option('endTime', request, params)
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            request['size'] = limit
        response = await self.v3PrivateGetConvertTrades(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #         "data": {
        #             "count": 12,
        #             "tradeVos":[
        #                 {
        #                     "quoteId": 12,
        #                     "buyAsset": "",
        #                     "sellAsset": "",
        #                     "buyAmount": 12.11,
        #                     "sellAmount": 12.11,
        #                     "tradeStatus": 12,
        #                     "createdTime": ""
        #                 }
        #                 ...
        #             ]
        #         }
        #     }
        #
        data = self.safe_dict(response, 'data', {})
        rows = self.safe_list(data, 'tradeVos', [])
        return self.parse_conversions(rows, code, 'sellAsset', 'buyAsset', since, limit)

    def parse_conversion(self, conversion: dict, fromCurrency: Currency = None, toCurrency: Currency = None) -> Conversion:
        #
        # fetchConvertQuote
        #
        #     {
        #         "quoteId": 123123123,
        #         "counterPartyId": "",
        #         "sellToken": "ETH",
        #         "sellQuantity": "0.0445",
        #         "buyToken": "USDT",
        #         "buyQuantity": "33.45",
        #         "buyPrice": "6.77",
        #         "expireTimestamp": 1659084466000,
        #         "message": 1659084466000
        #     }
        #
        # createConvertTrade
        #
        #     {
        #         "quoteId": 123123123,
        #         "counterPartyId": "",
        #         "rftAccepted": 1  # 1 -> success; 2 -> processing; 3 -> fail
        #     }
        #
        # fetchConvertTrade, fetchConvertTradeHistory
        #
        #     {
        #         "quoteId": 12,
        #         "buyAsset": "",
        #         "sellAsset": "",
        #         "buyAmount": 12.11,
        #         "sellAmount": 12.11,
        #         "tradeStatus": 12,
        #         "createdTime": ""
        #     }
        #
        timestamp = self.safe_integer_2(conversion, 'expireTimestamp', 'createdTime')
        fromCurr = self.safe_string_2(conversion, 'sellToken', 'buyAsset')
        fromCode = self.safe_currency_code(fromCurr, fromCurrency)
        to = self.safe_string_2(conversion, 'buyToken', 'sellAsset')
        toCode = self.safe_currency_code(to, toCurrency)
        return {
            'info': conversion,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'id': self.safe_string(conversion, 'quoteId'),
            'fromCurrency': fromCode,
            'fromAmount': self.safe_number_2(conversion, 'sellQuantity', 'sellAmount'),
            'toCurrency': toCode,
            'toAmount': self.safe_number_2(conversion, 'buyQuantity', 'buyAmount'),
            'price': self.safe_number(conversion, 'buyPrice'),
            'fee': None,
        }

    async def fetch_convert_currencies(self, params={}) -> Currencies:
        """
        fetches all available currencies that can be converted

        https://docs.woox.io/#get-quote-asset-info

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        """
        await self.load_markets()
        response = await self.v3PrivateGetConvertAssetInfo(params)
        #
        #     {
        #         "success": True,
        #         "rows": [
        #             {
        #                 "token": "BTC",
        #                 "tick": 0.0001,
        #                 "createdTime": "1575014248.99",  # Unix epoch time in seconds
        #                 "updatedTime": "1575014248.99"  # Unix epoch time in seconds
        #             },
        #         ]
        #     }
        #
        result: dict = {}
        data = self.safe_list(response, 'rows', [])
        for i in range(0, len(data)):
            entry = data[i]
            id = self.safe_string(entry, 'token')
            code = self.safe_currency_code(id)
            result[code] = {
                'info': entry,
                'id': id,
                'code': code,
                'networks': None,
                'type': None,
                'name': None,
                'active': None,
                'deposit': None,
                'withdraw': None,
                'fee': None,
                'precision': self.safe_number(entry, 'tick'),
                'limits': {
                    'amount': {
                        'min': None,
                        'max': None,
                    },
                    'withdraw': {
                        'min': None,
                        'max': None,
                    },
                    'deposit': {
                        'min': None,
                        'max': None,
                    },
                },
                'created': self.safe_timestamp(entry, 'createdTime'),
            }
        return result

    def default_network_code_for_currency(self, code):
        currencyItem = self.currency(code)
        networks = currencyItem['networks']
        networkKeys = list(networks.keys())
        for i in range(0, len(networkKeys)):
            network = networkKeys[i]
            if network == 'ETH':
                return network
        # if it was not returned according to above options, then return the first network of currency
        return self.safe_value(networkKeys, 0)

    def set_sandbox_mode(self, enable: bool):
        super(woo, self).set_sandbox_mode(enable)
        self.options['sandboxMode'] = enable
