# -*- 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
import hashlib
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 RateLimitExceeded
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class woo(Exchange):

    def describe(self):
        return self.deep_extend(super(woo, self).describe(), {
            'id': 'woo',
            'name': 'WOO X',
            'countries': ['KY'],  # Cayman Islands
            'rateLimit': 100,
            'version': 'v1',
            'certified': False,
            'pro': True,
            'hostname': 'woo.org',
            'has': {
                'CORS': None,
                'spot': True,
                'margin': True,
                'swap': True,
                'future': False,
                'option': False,
                'addMargin': False,
                'borrowMargin': False,
                'cancelAllOrders': True,
                'cancelOrder': True,
                'cancelWithdraw': False,  # exchange have that endpoint disabled atm, but was once implemented in ccxt per old docs: https://kronosresearch.github.io/wootrade-documents/#cancel-withdraw-request
                'createDepositAddress': False,
                'createMarketOrder': False,
                'createOrder': True,
                'createReduceOnlyOrder': True,
                'createStopLimitOrder': False,
                'createStopMarketOrder': False,
                'createStopOrder': False,
                'fetchAccounts': True,
                'fetchBalance': True,
                'fetchCanceledOrders': False,
                'fetchClosedOrder': False,
                'fetchClosedOrders': False,
                'fetchCurrencies': True,
                'fetchDepositAddress': False,
                'fetchDeposits': True,
                'fetchFundingHistory': True,
                'fetchFundingRate': True,
                'fetchFundingRateHistory': True,
                'fetchFundingRates': True,
                'fetchIndexOHLCV': False,
                'fetchLedger': True,
                'fetchLeverage': True,
                'fetchMarginMode': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenInterestHistory': False,
                'fetchOpenOrder': False,
                'fetchOpenOrders': False,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrders': True,
                'fetchOrderTrades': True,
                'fetchPosition': True,
                'fetchPositionMode': False,
                'fetchPositions': True,
                'fetchPremiumIndexOHLCV': False,
                'fetchStatus': False,
                'fetchTicker': False,
                'fetchTickers': False,
                'fetchTime': False,
                'fetchTrades': True,
                'fetchTradingFee': False,
                'fetchTradingFees': True,
                'fetchTransactions': True,
                'fetchTransfers': True,
                'fetchWithdrawals': True,
                'reduceMargin': False,
                'repayMargin': True,
                'setLeverage': True,
                'setMargin': False,
                'transfer': True,
                'withdraw': True,  # exchange have that endpoint disabled atm, but was once implemented in ccxt per old docs: https://kronosresearch.github.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.woo.org',
                    'public': 'https://api.{hostname}',
                    'private': 'https://api.{hostname}',
                },
                'test': {
                    'pub': 'https://api-pub.staging.woo.org',
                    'public': 'https://api.staging.woo.org',
                    'private': 'https://api.staging.woo.org',
                },
                'www': 'https://woo.org/',
                'doc': [
                    'https://docs.woo.org/',
                ],
                'fees': [
                    'https://support.woo.org/hc/en-001/articles/4404611795353--Trading-Fees',
                ],
                'referral': 'https://referral.woo.org/BAJS6oNmZb3vi3RGA',
            },
            'api': {
                'v1': {
                    'pub': {
                        'get': {
                            'hist/kline': 10,
                            'hist/trades': 1,
                        },
                    },
                    '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,
                        },
                    },
                    'private': {
                        'get': {
                            'client/token': 1,
                            'order/{oid}': 1,
                            'client/order/{client_order_id}': 1,
                            'orders': 1,
                            'orderbook/{symbol}': 1,
                            'kline': 1,
                            'client/trade/{tid}': 1,
                            'order/{oid}/trades': 1,
                            'client/trades': 1,
                            'client/info': 60,
                            'asset/deposit': 10,
                            'asset/history': 60,
                            'sub_account/all': 60,
                            'sub_account/assets': 60,
                            '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,
                        },
                        'post': {
                            'order': 5,  # 2 requests per 1 second per symbol
                            'asset/main_sub_transfer': 30,  # 20 requests per 60 seconds
                            'asset/withdraw': 30,  # implemented in ccxt, disabled on the exchange side https://kronosresearch.github.io/wootrade-documents/#token-withdraw
                            'interest/repay': 60,
                            'client/account_mode': 120,
                            'client/leverage': 120,
                        },
                        'delete': {
                            'order': 1,
                            'client/order': 1,
                            'orders': 1,
                            'asset/withdraw': 120,  # implemented in ccxt, disabled on the exchange side https://kronosresearch.github.io/wootrade-documents/#cancel-withdraw-request
                        },
                    },
                },
                'v2': {
                    'private': {
                        'get': {
                            'client/holding': 1,
                        },
                    },
                },
                'v3': {
                    'private': {
                        'get': {
                            'algo/order/{oid}': 1,
                            'algo/orders': 1,
                            'balances': 1,
                            'accountinfo': 60,
                            'positions': 3.33,
                            'buypower': 1,
                        },
                        'post': {
                            'algo/order': 5,
                        },
                        'put': {
                            'order/{oid}': 2,
                            'order/client/{oid}': 2,
                            'algo/order/{oid}': 2,
                            'algo/order/client/{oid}': 2,
                        },
                        'delete': {
                            'algo/order/{oid}': 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': {
                '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,
                },
            },
            'commonCurrencies': {},
            'exceptions': {
                'exact': {
                    '-1000': ExchangeError,  # {"code": -1000,  "message": "An unknown error occurred while processing the request"}
                    '-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."}
                    '-1011': ExchangeError,  # {"code": -1011,  "message": "Can not place/cancel orders, it may because internal network error. Please try again in a few seconds."}
                    '-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': {
                    '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_markets(self, params={}):
        """
        retrieves data on all markets for woo
        :param dict params: extra parameters specific to the exchange api endpoint
        :returns [dict]: an array of objects representing market data
        """
        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
        # }
        #
        result = []
        data = self.safe_value(response, 'rows', [])
        for i in range(0, len(data)):
            market = data[i]
            marketId = self.safe_string(market, 'symbol')
            parts = marketId.split('_')
            marketType = self.safe_string_lower(parts, 0)
            isSpot = marketType == 'spot'
            isSwap = marketType == 'perp'
            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 = None
            settle = None
            symbol = base + '/' + quote
            contractSize = None
            linear = None
            if isSwap:
                settleId = self.safe_string(parts, 2)
                settle = self.safe_currency_code(settleId)
                symbol = base + '/' + quote + ':' + settle
                contractSize = self.parse_number('1')
                marketType = 'swap'
                linear = True
            result.append({
                'id': marketId,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'settle': settle,
                'baseId': baseId,
                'quoteId': quoteId,
                'settleId': settleId,
                'type': marketType,
                'spot': isSpot,
                'margin': True,
                'swap': isSwap,
                'future': False,
                'option': False,
                'active': None,
                'contract': isSwap,
                'linear': linear,
                'inverse': None,
                '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,
                    },
                },
                'info': market,
            })
        return result

    async def fetch_trades(self, symbol, since=None, limit=None, params={}):
        """
        get the list of most recent trades for a particular symbol
        :param str symbol: unified symbol of the market to fetch trades for
        :param int|None since: timestamp in ms of the earliest trade to fetch
        :param int|None limit: the maximum amount of trades to fetch
        :param dict params: extra parameters specific to the woo api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html?#public-trades>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchTrades() requires a symbol argument')
        await self.load_markets()
        market = self.market(symbol)
        request = {
            '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_value(response, 'rows', {})
        return self.parse_trades(resultResponse, market, since, limit)

    def parse_trade(self, trade, market=None):
        #
        # 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')
        cost = Precise.string_mul(price, amount)
        side = self.safe_string_lower(trade, 'side')
        id = self.safe_string(trade, 'id')
        takerOrMaker = 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={}):
        """
        fetch the trading fees for multiple markets
        see https://docs.woo.org/#get-account-information-new
        :param dict params: extra parameters specific to the woo api endpoint
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/en/latest/manual.html#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_value(response, 'data', {})
        maker = self.safe_string(data, 'makerFeeRate')
        taker = self.safe_string(data, 'takerFeeRate')
        result = {}
        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={}):
        """
        fetches all available currencies on an exchange
        :param dict params: extra parameters specific to the woo api endpoint
        :returns dict: an associative dictionary of currencies
        """
        result = {}
        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_value(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 = None
            minPrecision = None
            resultingNetworks = {}
            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,
                'limits': {
                    'deposit': {
                        'min': None,
                        'max': None,
                    },
                    'withdraw': {
                        'min': None,
                        'max': None,
                    },
                },
                'info': networks,
            }
        return result

    async def create_order(self, symbol, type, side, amount, price=None, params={}):
        """
        create a trade 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|None price: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
        :param dict params: extra parameters specific to the woo api endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        reduceOnly = self.safe_value(params, 'reduceOnly')
        orderType = type.upper()
        if reduceOnly is not None:
            if orderType != 'LIMIT':
                raise InvalidOrder(self.id + ' createOrder() only support reduceOnly for limit orders')
        await self.load_markets()
        market = self.market(symbol)
        orderSide = side.upper()
        request = {
            'symbol': market['id'],
            'order_type': orderType,  # LIMIT/MARKET/IOC/FOK/POST_ONLY/ASK/BID
            'side': orderSide,
        }
        isMarket = orderType == 'MARKET'
        timeInForce = self.safe_string_lower(params, 'timeInForce')
        postOnly = self.is_post_only(isMarket, None, params)
        if postOnly:
            request['order_type'] = 'POST_ONLY'
        elif timeInForce == 'fok':
            request['order_type'] = 'FOK'
        elif timeInForce == 'ioc':
            request['order_type'] = 'IOC'
        if reduceOnly:
            request['reduce_only'] = reduceOnly
        if price is not None:
            request['order_price'] = self.price_to_precision(symbol, price)
        if isMarket:
            # for market buy it requires the amount of quote currency to spend
            if market['spot'] and orderSide == 'BUY':
                cost = self.safe_number(params, 'cost')
                if self.safe_value(self.options, 'createMarketBuyOrderRequiresPrice', True):
                    if cost is None:
                        if price is None:
                            raise InvalidOrder(self.id + " createOrder() requires the price argument for market buy orders to calculate total order cost. Supply a price argument to createOrder() call if you want the cost to be calculated for you from price and amount, or alternatively, supply the total cost value in the 'order_amount' in  exchange-specific parameters")
                        else:
                            amountString = self.number_to_string(amount)
                            priceString = self.number_to_string(price)
                            orderAmount = Precise.string_mul(amountString, priceString)
                            request['order_amount'] = self.cost_to_precision(symbol, orderAmount)
                    else:
                        request['order_amount'] = self.cost_to_precision(symbol, cost)
                else:
                    request['order_amount'] = self.cost_to_precision(symbol, amount)
            else:
                request['order_quantity'] = self.amount_to_precision(symbol, amount)
        else:
            request['order_quantity'] = self.amount_to_precision(symbol, amount)
        clientOrderId = self.safe_string_2(params, 'clOrdID', 'clientOrderId')
        if clientOrderId is not None:
            request['client_order_id'] = clientOrderId
        params = self.omit(params, ['clOrdID', 'clientOrderId', 'postOnly', 'timeInForce'])
        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'
        # }
        return self.extend(
            self.parse_order(response, market),
            {'type': type}
        )

    async def edit_order(self, id, symbol, type, side, amount, price=None, params={}):
        """
        edit a trade order
        :param str id: order id
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float|None price: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
        :param dict params: extra parameters specific to the woo api endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'oid': id,
            # '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)
        response = await self.v3PrivatePutOrderOid(self.extend(request, params))
        #
        #     {
        #         "code": 0,
        #         "data": {
        #             "status": "string",
        #             "success": True
        #         },
        #         "message": "string",
        #         "success": True,
        #         "timestamp": 0
        #     }
        #
        data = self.safe_value(response, 'data', {})
        return self.parse_order(data, market)

    async def cancel_order(self, id, symbol=None, params={}):
        """
        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 woo api endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
        await self.load_markets()
        request = {}
        clientOrderIdUnified = self.safe_string_2(params, 'clOrdID', 'clientOrderId')
        clientOrderIdExchangeSpecific = self.safe_string_2(params, 'client_order_id', clientOrderIdUnified)
        isByClientOrder = clientOrderIdExchangeSpecific is not None
        if isByClientOrder:
            request['client_order_id'] = clientOrderIdExchangeSpecific
            params = self.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
        else:
            request['order_id'] = id
        market = None
        if symbol is not None:
            market = self.market(symbol)
        request['symbol'] = market['id']
        response = await self.v1PrivateDeleteOrder(self.extend(request, params))
        #
        # {success: True, status: 'CANCEL_SENT'}
        #
        extendParams = {'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=None, params={}):
        """
        cancel all open orders in a market
        :param str|None symbol: unified market symbol
        :param dict params: extra parameters specific to the woo api endpoint
        :returns dict: an list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' canelOrders() requires a symbol argument')
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.v1PrivateDeleteOrders(self.extend(request, params))
        #
        #     {
        #         "success":true,
        #         "status":"CANCEL_ALL_SENT"
        #     }
        #
        return response

    async def fetch_order(self, id, symbol=None, params={}):
        """
        fetches information on an order made by the user
        :param str|None symbol: unified symbol of the market the order was made in
        :param dict params: extra parameters specific to the woo api endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol) if (symbol is not None) else None
        request = {}
        clientOrderId = self.safe_string_2(params, 'clOrdID', 'clientOrderId')
        chosenSpotMethod = None
        if clientOrderId:
            chosenSpotMethod = 'v1PrivateGetClientOrderClientOrderId'
            request['client_order_id'] = clientOrderId
        else:
            chosenSpotMethod = 'v1PrivateGetOrderOid'
            request['oid'] = id
        response = await getattr(self, chosenSpotMethod)(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'
        #       }
        #     ]
        # }
        #
        return self.parse_order(response, market)

    async def fetch_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches information on multiple orders made by the user
        :param str|None symbol: unified market symbol of the market orders were made in
        :param int|None since: the earliest time in ms to fetch orders for
        :param int|None limit: the maximum number of  orde structures to retrieve
        :param dict params: extra parameters specific to the woo api endpoint
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        request = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            request['start_t'] = since
        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, 'rows')
        return self.parse_orders(data, market, since, limit, params)

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

    def parse_order(self, order, market=None):
        #
        # Possible input functions:
        # * createOrder
        # * cancelOrder
        # * fetchOrder
        # * fetchOrders
        # isFromFetchOrder = ('order_tag' in order); TO_DO
        timestamp = self.safe_timestamp_2(order, 'timestamp', 'created_time')
        orderId = self.safe_string(order, 'order_id')
        clientOrderId = self.safe_string(order, 'client_order_id')  # 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(order, 'status')
        side = self.safe_string_lower(order, 'side')
        filled = self.safe_value(order, 'executed')
        remaining = Precise.string_sub(cost, filled)
        fee = self.safe_value(order, 'total_fee')
        feeCurrency = self.safe_string(order, 'fee_asset')
        transactions = self.safe_value(order, 'Transactions')
        return self.safe_order({
            'id': orderId,
            'clientOrderId': clientOrderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'status': self.parse_order_status(status),
            'symbol': symbol,
            'type': orderType,
            'timeInForce': self.parse_time_in_force(orderType),
            'postOnly': None,  # TO_DO
            'reduceOnly': self.safe_value(order, 'reduce_only'),
            'side': side,
            'price': price,
            'stopPrice': None,
            'triggerPrice': None,
            'average': None,
            'amount': amount,
            'filled': filled,
            'remaining': remaining,  # TO_DO
            'cost': cost,
            'trades': transactions,
            'fee': {
                'cost': fee,
                'currency': feeCurrency,
            },
            'info': order,
        }, market)

    def parse_order_status(self, status):
        if status is not None:
            statuses = {
                '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, limit=None, params={}):
        """
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str symbol: unified symbol of the market to fetch the order book for
        :param int|None limit: the maximum amount of order book entries to return
        :param dict params: extra parameters specific to the woo api endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbols
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            limit = min(limit, 1000)
            request['max_level'] = limit
        response = await self.v1PrivateGetOrderbookSymbol(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, timeframe='1m', since=None, limit=None, params={}):
        """
        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|None since: timestamp in ms of the earliest candle to fetch
        :param int|None limit: the maximum amount of candles to fetch
        :param dict params: extra parameters specific to the woo api endpoint
        :returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            'type': self.safe_string(self.timeframes, timeframe, timeframe),
        }
        if limit is not None:
            request['limit'] = min(limit, 1000)
        response = await self.v1PrivateGetKline(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'
        #       },
        #       {
        #         open: '0.94186',
        #         close: '0.94186',
        #         low: '0.94186',
        #         high: '0.94186',
        #         volume: '64.00',
        #         amount: '60.27904000',
        #         symbol: 'SPOT_WOO_USDT',
        #         type: '1m',
        #         start_timestamp: '1641584640000',
        #         end_timestamp: '1641584700000'
        #       },
        #       ...
        #     ]
        # }
        data = self.safe_value(response, 'rows', [])
        return self.parse_ohlcvs(data, market, timeframe, since, limit)

    def parse_ohlcv(self, ohlcv, market=None):
        # 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, symbol=None, since=None, limit=None, params={}):
        """
        fetch all the trades made from a single order
        :param str id: order id
        :param str|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch trades for
        :param int|None limit: the maximum number of trades to retrieve
        :param dict params: extra parameters specific to the woo api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
        """
        await self.load_markets()
        market = None
        if symbol is not None:
            market = self.market(symbol)
        request = {
            '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_value(response, 'rows', [])
        return self.parse_trades(trades, market, since, limit, params)

    async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
        """
        fetch all trades made by the user
        :param str|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch trades for
        :param int|None limit: the maximum number of trades structures to retrieve
        :param dict params: extra parameters specific to the woo api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
        """
        await self.load_markets()
        request = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            request['start_t'] = since
        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_value(response, 'rows', [])
        return self.parse_trades(trades, market, since, limit, params)

    async def fetch_accounts(self, params={}):
        """
        fetch all the accounts associated with a profile
        :param dict params: extra parameters specific to the woo api endpoint
        :returns dict: a dictionary of `account structures <https://docs.ccxt.com/en/latest/manual.html#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_value(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={}):
        """
        query for balance and get the amount of funds available for trading or funds locked in orders
        see https://docs.woo.org/#get-current-holding-get-balance-new
        :param dict params: extra parameters specific to the woo api endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#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_value(response, 'data')
        return self.parse_balance(data)

    def parse_balance(self, response):
        result = {
            'info': response,
        }
        balances = self.safe_value(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, params={}):
        """
        fetch the deposit address for a currency associated with self account
        :param str code: unified currency code
        :param dict params: extra parameters specific to the woo api endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#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 = {
            '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 {
            'currency': code,
            'address': address,
            'tag': tag,
            'network': networkCode,
            'info': response,
        }

    async def get_asset_history_rows(self, code=None, since=None, limit=None, params={}):
        await self.load_markets()
        request = {}
        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_value(response, 'rows', {})]

    async def fetch_ledger(self, code=None, since=None, limit=None, params={}):
        """
        fetch the history of changes, actions done by the user or operations that altered balance of the user
        :param str|None code: unified currency code, default is None
        :param int|None since: timestamp in ms of the earliest ledger entry, default is None
        :param int|None limit: max number of ledger entrys to return, default is None
        :param dict params: extra parameters specific to the woo api endpoint
        :returns dict: a `ledger structure <https://docs.ccxt.com/en/latest/manual.html#ledger-structure>`
        """
        currency, rows = await self.get_asset_history_rows(code, since, limit, params)
        return self.parse_ledger(rows, currency, since, limit, params)

    def parse_ledger_entry(self, item, currency=None):
        networkizedCode = self.safe_string(item, 'token')
        currencyDefined = self.get_currency_from_chaincode(networkizedCode, currency)
        code = currencyDefined['code']
        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 {
            '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,
            'fee': fee,
            'direction': direction,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'type': self.parse_ledger_entry_type(self.safe_string(item, 'type')),
            'info': item,
        }

    def parse_ledger_entry_type(self, type):
        types = {
            '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=None, since=None, limit=None, params={}):
        """
        fetch all deposits made to an account
        :param str|None code: unified currency code
        :param int|None since: the earliest time in ms to fetch deposits for
        :param int|None limit: the maximum number of deposits structures to retrieve
        :param dict params: extra parameters specific to the woo api endpoint
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        request = {
            'token_side': 'DEPOSIT',
        }
        return await self.fetch_transactions(code, since, limit, self.extend(request, params))

    async def fetch_withdrawals(self, code=None, since=None, limit=None, params={}):
        """
        fetch all withdrawals made from an account
        :param str|None code: unified currency code
        :param int|None since: the earliest time in ms to fetch withdrawals for
        :param int|None limit: the maximum number of withdrawals structures to retrieve
        :param dict params: extra parameters specific to the woo api endpoint
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        request = {
            'token_side': 'WITHDRAW',
        }
        return await self.fetch_transactions(code, since, limit, self.extend(request, params))

    async def fetch_transactions(self, code=None, since=None, limit=None, params={}):
        """
        fetch history of deposits and withdrawals
        :param str|None code: unified currency code for the currency of the transactions, default is None
        :param int|None since: timestamp in ms of the earliest transaction, default is None
        :param int|None limit: max number of transactions to return, default is None
        :param dict params: extra parameters specific to the woo api endpoint
        :returns dict: a list of `transaction structure <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        request = {
            'type': 'BALANCE',
        }
        currency, rows = await self.get_asset_history_rows(code, since, limit, self.extend(request, params))
        #
        #     {
        #         "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, currency=None):
        # 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 {
            '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'),
            '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'),
            'fee': fee,
            'info': transaction,
        }

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

    async def transfer(self, code, amount, fromAccount, toAccount, params={}):
        """
        transfer currency internally between wallets on the same account
        :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 woo api endpoint
        :returns dict: a `transfer structure <https://docs.ccxt.com/en/latest/manual.html#transfer-structure>`
        """
        await self.load_markets()
        currency = self.currency(code)
        request = {
            'token': currency['id'],
            'amount': self.parse_number(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_value(self.options, 'transfer', {})
        fillResponseFromRequest = self.safe_value(transferOptions, 'fillResponseFromRequest', True)
        if fillResponseFromRequest:
            transfer['amount'] = amount
            transfer['fromAccount'] = fromAccount
            transfer['toAccount'] = toAccount
        return transfer

    async def fetch_transfers(self, code=None, since=None, limit=None, params={}):
        """
        fetch a history of internal transfers made on an account
        :param str|None code: unified currency code of the currency transferred
        :param int|None since: the earliest time in ms to fetch transfers for
        :param int|None limit: the maximum number of  transfers structures to retrieve
        :param dict params: extra parameters specific to the woo api endpoint
        :returns [dict]: a list of `transfer structures <https://docs.ccxt.com/en/latest/manual.html#transfer-structure>`
        """
        request = {
            'type': 'COLLATERAL',
        }
        currency, rows = await self.get_asset_history_rows(code, since, limit, self.extend(request, params))
        return self.parse_transfers(rows, currency, since, limit, params)

    def parse_transfer(self, transfer, currency=None):
        #
        #    getAssetHistoryRows
        #        {
        #            "created_time": "1579399877.041",  # Unix epoch time in seconds
        #            "updated_time": "1579399877.041",  # Unix epoch time in seconds
        #            "id": "202029292829292",
        #            "external_id": "202029292829292",
        #            "application_id": null,
        #            "token": "ETH",
        #            "target_address": "0x31d64B3230f8baDD91dE1710A65DF536aF8f7cDa",
        #            "source_address": "0x70fd25717f769c7f9a46b319f0f9103c0d887af0",
        #            "extra": "",
        #            "type": "BALANCE",
        #            "token_side": "DEPOSIT",
        #            "amount": 1000,
        #            "tx_id": "0x8a74c517bc104c8ebad0c3c3f64b1f302ed5f8bca598ae4459c63419038106b6",
        #            "fee_token": null,
        #            "fee_amount": null,
        #            "status": "CONFIRMING"
        #        }
        #
        #    v1PrivatePostAssetMainSubTransfer
        #        {
        #            "success": True,
        #            "id": 200
        #        }
        #
        networkizedCode = self.safe_string(transfer, 'token')
        currencyDefined = self.get_currency_from_chaincode(networkizedCode, currency)
        code = currencyDefined['code']
        movementDirection = self.safe_string_lower(transfer, 'token_side')
        if movementDirection == 'withdraw':
            movementDirection = 'withdrawal'
        fromAccount = None
        toAccount = None
        if movementDirection == 'withdraw':
            fromAccount = None
            toAccount = 'spot'
        elif movementDirection == 'deposit':
            fromAccount = 'spot'
            toAccount = None
        timestamp = self.safe_timestamp(transfer, 'created_time')
        success = self.safe_value(transfer, 'success')
        status = 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': fromAccount,
            'toAccount': toAccount,
            'status': self.parse_transfer_status(self.safe_string(transfer, 'status', status)),
            'info': transfer,
        }

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

    async def withdraw(self, code, amount, address, tag=None, params={}):
        """
        make a withdrawal
        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str|None tag:
        :param dict params: extra parameters specific to the woo api endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/en/latest/manual.html#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 = {
            'amount': amount,
            'address': address,
        }
        if tag is not None:
            request['extra'] = tag
        networks = self.safe_value(self.options, 'networks', {})
        currencyNetworks = self.safe_value(currency, 'networks', {})
        network = self.safe_string_upper(params, 'network')
        networkId = self.safe_string(networks, network, network)
        coinNetwork = self.safe_value(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, amount, symbol=None, params={}):
        """
        repay borrowed margin and interest
        see https://docs.woo.org/#repay-interest
        :param str code: unified currency code of the currency to repay
        :param float amount: the amount to repay
        :param str|None symbol: not used by woo.repayMargin()
        :param dict params: extra parameters specific to the woo api endpoint
        :returns dict: a `margin loan structure <https://docs.ccxt.com/en/latest/manual.html#margin-loan-structure>`
        """
        await self.load_markets()
        market = None
        if symbol is not None:
            market = self.market(symbol)
            symbol = market['symbol']
        currency = self.currency(code)
        request = {
            '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=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()

    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)
        else:
            self.check_required_credentials()
            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:
                    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, reason, url, method, headers, body, response, requestHeaders, requestBody):
        if not response:
            return  # fallback to default error handler
        #
        #     400 Bad Request {"success":false,"code":-1012,"message":"Amount is required for buy market orders when margin disabled."}
        #
        success = self.safe_value(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)

    def parse_income(self, income, 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_number(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')
        return {
            'info': income,
            'symbol': symbol,
            'code': code,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'id': id,
            'amount': amount,
            'rate': rate,
        }

    async def fetch_funding_history(self, symbol=None, since=None, limit=None, params={}):
        await self.load_markets()
        request = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            request['start_t'] = since
        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
        #     }
        #
        result = self.safe_value(response, 'rows', [])
        return self.parse_incomes(result, market, since, limit)

    def parse_funding_rate(self, fundingRate, market=None):
        #
        #         {
        #             "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
        #         }
        #
        #
        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')
        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),
        }

    async def fetch_funding_rate(self, symbol, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.v1PublicGetFundingRateSymbol(self.extend(request, params))
        #
        #     {
        #         "success":true,
        #         "timestamp":1653640572711,
        #         "symbol":"PERP_BTC_USDT",
        #         "est_funding_rate":0.00000738,
        #         "est_funding_rate_timestamp":1653640559003,
        #         "last_funding_rate":0.00000629,
        #         "last_funding_rate_timestamp":1653638400000,
        #         "next_funding_time":1653642000000
        #     }
        #
        return self.parse_funding_rate(response, market)

    async def fetch_funding_rates(self, symbols=None, params={}):
        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_value(response, 'rows', {})
        result = self.parse_funding_rates(rows)
        return self.filter_by_array(result, 'symbol', symbols)

    async def fetch_funding_rate_history(self, symbol=None, since=None, limit=None, params={}):
        await self.load_markets()
        request = {}
        if symbol is not None:
            market = self.market(symbol)
            symbol = market['symbol']
            request['symbol'] = market['id']
        if since is not None:
            request['start_t'] = int(since / 1000)
        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_value(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 fetch_leverage(self, symbol, params={}):
        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
        #     }
        #
        result = self.safe_value(response, 'data')
        leverage = self.safe_number(result, 'leverage')
        return {
            'info': response,
            'leverage': leverage,
        }

    async def set_leverage(self, leverage, symbol=None, params={}):
        await self.load_markets()
        if (leverage < 1) or (leverage > 20):
            raise BadRequest(self.id + ' leverage should be between 1 and 20')
        request = {
            'leverage': leverage,
        }
        return await self.v1PrivatePostClientLeverage(self.extend(request, params))

    async def fetch_position(self, symbol=None, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.v1PrivateGetPositionSymbol(self.extend(request, params))
        #
        #     {
        #         "symbol":"PERP_ETC_USDT",
        #         "holding":0.0,
        #         "pnl_24_h":0,
        #         "settle_price":0.0,
        #         "average_open_price":0,
        #         "success":true,
        #         "mark_price":22.6955,
        #         "pending_short_qty":0.0,
        #         "pending_long_qty":0.0,
        #         "fee_24_h":0,
        #         "timestamp":"1652231044.920"
        #     }
        #
        return self.parse_position(response, market)

    async def fetch_positions(self, symbols=None, params={}):
        await self.load_markets()
        response = await self.v3PrivateGetPositions(params)
        #
        #     {
        #         "success": True,
        #         "data": {
        #             "positions": [
        #                 {
        #                     "symbol": "0_symbol",
        #                     "holding": 1,
        #                     "pendingLongQty": 0,
        #                     "pendingShortQty": 1,
        #                     "settlePrice": 1,
        #                     "averageOpenPrice": 1,
        #                     "pnl24H": 1,
        #                     "fee24H": 1,
        #                     "markPrice": 1,
        #                     "estLiqPrice": 1,
        #                     "timestamp": 12321321
        #                 }
        #             ]
        #         },
        #         "timestamp": 1673323880342
        #     }
        #
        result = self.safe_value(response, 'data', {})
        positions = self.safe_value(result, 'positions', [])
        return self.parse_positions(positions, symbols)

    def parse_position(self, position, market=None):
        #
        #     {
        #         "symbol": "0_symbol",
        #         "holding": 1,
        #         "pendingLongQty": 0,
        #         "pendingShortQty": 1,
        #         "settlePrice": 1,
        #         "averageOpenPrice": 1,
        #         "pnl24H": 1,
        #         "fee24H": 1,
        #         "markPrice": 1,
        #         "estLiqPrice": 1,
        #         "timestamp": 12321321
        #     }
        #
        contract = self.safe_string(position, 'symbol')
        market = self.safe_market(contract, market)
        size = self.safe_string(position, 'holding')
        side = None
        if Precise.string_gt(size, '0'):
            side = 'long'
        else:
            side = 'short'
        contractSize = self.safe_string(market, 'contractSize')
        markPrice = self.safe_string(position, 'markPrice')
        timestamp = self.safe_timestamp(position, 'timestamp')
        entryPrice = self.safe_string(position, 'averageOpenPrice')
        priceDifference = Precise.string_sub(markPrice, entryPrice)
        unrealisedPnl = Precise.string_mul(priceDifference, size)
        size = Precise.string_abs(size)
        notional = Precise.string_mul(size, markPrice)
        return {
            'info': position,
            'id': None,
            'symbol': self.safe_string(market, 'symbol'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'initialMargin': None,
            'initialMarginPercentage': None,
            'maintenanceMargin': None,
            'maintenanceMarginPercentage': None,
            'entryPrice': self.parse_number(entryPrice),
            'notional': self.parse_number(notional),
            'leverage': None,
            'unrealizedPnl': self.parse_number(unrealisedPnl),
            'contracts': self.parse_number(size),
            'contractSize': self.parse_number(contractSize),
            'marginRatio': None,
            'liquidationPrice': self.safe_number(position, 'estLiqPrice'),
            'markPrice': self.parse_number(markPrice),
            'collateral': None,
            'marginMode': 'cross',
            'marginType': None,
            'side': side,
            'percentage': None,
        }

    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)
