# -*- 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.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import AccountSuspended
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import NotSupported
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import OnMaintenance
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class hitbtc3(Exchange):

    def describe(self):
        return self.deep_extend(super(hitbtc3, self).describe(), {
            'id': 'hitbtc3',
            'name': 'HitBTC',
            'countries': ['HK'],
            # 300 requests per second => 1000ms / 300 = 3.333(Trading: placing, replacing, deleting)
            # 30 requests per second =>( 1000ms / rateLimit ) / 30 = cost = 10(Market Data and other Public Requests)
            # 20 requests per second =>( 1000ms / rateLimit ) / 20 = cost = 15(All Other)
            'rateLimit': 3.333,  # TODO: optimize https://api.hitbtc.com/#rate-limiting
            'version': '3',
            'pro': False,
            'has': {
                'CORS': False,
                'spot': True,
                'margin': True,
                'swap': True,
                'future': False,
                'option': None,
                'addMargin': True,
                'cancelAllOrders': True,
                'cancelOrder': True,
                'createDepositAddress': True,
                'createOrder': True,
                'createReduceOnlyOrder': True,
                'createStopLimitOrder': True,
                'createStopMarketOrder': True,
                'createStopOrder': True,
                'editOrder': True,
                'fetchBalance': True,
                'fetchBorrowRate': None,
                'fetchBorrowRateHistories': None,
                'fetchBorrowRateHistory': None,
                'fetchBorrowRates': None,
                'fetchClosedOrders': True,
                'fetchCurrencies': True,
                'fetchDepositAddress': True,
                'fetchDeposits': True,
                'fetchDepositWithdrawFee': 'emulated',
                'fetchDepositWithdrawFees': True,
                'fetchFundingHistory': None,
                'fetchFundingRate': True,
                'fetchFundingRateHistory': True,
                'fetchFundingRates': False,
                'fetchIndexOHLCV': True,
                'fetchLeverage': True,
                'fetchLeverageTiers': None,
                'fetchMarketLeverageTiers': None,
                'fetchMarkets': True,
                'fetchMarkOHLCV': True,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenOrder': True,
                'fetchOpenOrders': True,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrderBooks': True,
                'fetchOrders': False,
                'fetchOrderTrades': True,
                'fetchPosition': True,
                'fetchPositions': True,
                'fetchPremiumIndexOHLCV': True,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTrades': True,
                'fetchTradingFee': True,
                'fetchTradingFees': True,
                'fetchTransactions': True,
                'fetchWithdrawals': True,
                'reduceMargin': True,
                'setLeverage': True,
                'setMarginMode': False,
                'setPositionMode': False,
                'transfer': True,
                'withdraw': True,
            },
            'precisionMode': TICK_SIZE,
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766555-8eaec20e-5edc-11e7-9c5b-6dc69fc42f5e.jpg',
                'test': {
                    'public': 'https://api.demo.hitbtc.com/api/3',
                    'private': 'https://api.demo.hitbtc.com/api/3',
                },
                'api': {
                    'public': 'https://api.hitbtc.com/api/3',
                    'private': 'https://api.hitbtc.com/api/3',
                },
                'www': 'https://hitbtc.com',
                'referral': 'https://hitbtc.com/?ref_id=5a5d39a65d466',
                'doc': [
                    'https://api.hitbtc.com',
                    'https://github.com/hitbtc-com/hitbtc-api/blob/master/APIv2.md',
                ],
                'fees': [
                    'https://hitbtc.com/fees-and-limits',
                    'https://support.hitbtc.com/hc/en-us/articles/115005148605-Fees-and-limits',
                ],
            },
            'api': {
                'public': {
                    'get': {
                        'public/currency': 10,
                        'public/symbol': 10,
                        'public/ticker': 10,
                        'public/price/rate': 10,
                        'public/trades': 10,
                        'public/orderbook': 10,
                        'public/candles': 10,
                        'public/futures/info': 10,
                        'public/futures/history/funding': 10,
                        'public/futures/candles/index_price': 10,
                        'public/futures/candles/mark_price': 10,
                        'public/futures/candles/premium_index': 10,
                        'public/futures/candles/open_interest': 10,
                    },
                },
                'private': {
                    'get': {
                        'spot/balance': 15,
                        'spot/order': 15,
                        'spot/order/{client_order_id}': 15,
                        'spot/fee': 15,
                        'spot/fee/{symbol}': 15,
                        'spot/history/order': 15,
                        'spot/history/trade': 15,
                        'margin/account': 15,
                        'margin/account/isolated/{symbol}': 15,
                        'margin/order': 15,
                        'margin/order/{client_order_id}': 15,
                        'margin/history/clearing': 15,
                        'margin/history/order': 15,
                        'margin/history/positions': 15,
                        'margin/history/trade': 15,
                        'futures/balance': 15,
                        'futures/account': 15,
                        'futures/account/isolated/{symbol}': 15,
                        'futures/order': 15,
                        'futures/order/{client_order_id}': 15,
                        'futures/fee': 15,
                        'futures/fee/{symbol}': 15,
                        'futures/history/clearing': 15,
                        'futures/history/order': 15,
                        'futures/history/positions': 15,
                        'futures/history/trade': 15,
                        'wallet/balance': 15,
                        'wallet/crypto/address': 15,
                        'wallet/crypto/address/recent-deposit': 15,
                        'wallet/crypto/address/recent-withdraw': 15,
                        'wallet/crypto/address/check-mine': 15,
                        'wallet/transactions': 15,
                        'wallet/crypto/check-offchain-available': 15,
                        'wallet/crypto/fee/estimate': 15,
                        'sub-account': 15,
                        'sub-account/acl': 15,
                        'sub-account/balance/{subAccID}': 15,
                        'sub-account/crypto/address/{subAccID}/{currency}': 15,
                    },
                    'post': {
                        'spot/order': 1,
                        'margin/order': 1,
                        'futures/order': 1,
                        'wallet/convert': 15,
                        'wallet/crypto/address': 15,
                        'wallet/crypto/withdraw': 15,
                        'wallet/transfer': 15,
                        'sub-account/freeze': 15,
                        'sub-account/activate': 15,
                        'sub-account/transfer': 15,
                        'sub-account/acl': 15,
                    },
                    'patch': {
                        'spot/order/{client_order_id}': 1,
                        'margin/order/{client_order_id}': 1,
                        'futures/order/{client_order_id}': 1,
                    },
                    'delete': {
                        'spot/order': 1,
                        'spot/order/{client_order_id}': 1,
                        'margin/position': 1,
                        'margin/position/isolated/{symbol}': 1,
                        'margin/order': 1,
                        'margin/order/{client_order_id}': 1,
                        'futures/position': 1,
                        'futures/position/isolated/{symbol}': 1,
                        'futures/order': 1,
                        'futures/order/{client_order_id}': 1,
                        'wallet/crypto/withdraw/{id}': 1,
                    },
                    'put': {
                        'margin/account/isolated/{symbol}': 1,
                        'futures/account/isolated/{symbol}': 1,
                        'wallet/crypto/withdraw/{id}': 1,
                    },
                },
            },
            'fees': {
                'trading': {
                    'tierBased': True,
                    'percentage': True,
                    'taker': self.parse_number('0.0009'),
                    'maker': self.parse_number('0.0009'),
                    'tiers': {
                        'maker': [
                            [self.parse_number('0'), self.parse_number('0.0009')],
                            [self.parse_number('10'), self.parse_number('0.0007')],
                            [self.parse_number('100'), self.parse_number('0.0006')],
                            [self.parse_number('500'), self.parse_number('0.0005')],
                            [self.parse_number('1000'), self.parse_number('0.0003')],
                            [self.parse_number('5000'), self.parse_number('0.0002')],
                            [self.parse_number('10000'), self.parse_number('0.0001')],
                            [self.parse_number('20000'), self.parse_number('0')],
                            [self.parse_number('50000'), self.parse_number('-0.0001')],
                            [self.parse_number('100000'), self.parse_number('-0.0001')],
                        ],
                        'taker': [
                            [self.parse_number('0'), self.parse_number('0.0009')],
                            [self.parse_number('10'), self.parse_number('0.0008')],
                            [self.parse_number('100'), self.parse_number('0.0007')],
                            [self.parse_number('500'), self.parse_number('0.0007')],
                            [self.parse_number('1000'), self.parse_number('0.0006')],
                            [self.parse_number('5000'), self.parse_number('0.0006')],
                            [self.parse_number('10000'), self.parse_number('0.0005')],
                            [self.parse_number('20000'), self.parse_number('0.0004')],
                            [self.parse_number('50000'), self.parse_number('0.0003')],
                            [self.parse_number('100000'), self.parse_number('0.0002')],
                        ],
                    },
                },
            },
            'timeframes': {
                '1m': 'M1',
                '3m': 'M3',
                '5m': 'M5',
                '15m': 'M15',
                '30m': 'M30',  # default
                '1h': 'H1',
                '4h': 'H4',
                '1d': 'D1',
                '1w': 'D7',
                '1M': '1M',
            },
            'exceptions': {
                'exact': {
                    '429': RateLimitExceeded,
                    '500': ExchangeError,
                    '503': ExchangeNotAvailable,
                    '504': ExchangeNotAvailable,
                    '600': PermissionDenied,
                    '800': ExchangeError,
                    '1002': AuthenticationError,
                    '1003': PermissionDenied,
                    '1004': AuthenticationError,
                    '1005': AuthenticationError,
                    '2001': BadSymbol,
                    '2002': BadRequest,
                    '2003': BadRequest,
                    '2010': BadRequest,
                    '2011': BadRequest,
                    '2012': BadRequest,
                    '2020': BadRequest,
                    '2022': BadRequest,
                    '10001': BadRequest,
                    '10021': AccountSuspended,
                    '10022': BadRequest,
                    '20001': InsufficientFunds,
                    '20002': OrderNotFound,
                    '20003': ExchangeError,
                    '20004': ExchangeError,
                    '20005': ExchangeError,
                    '20006': ExchangeError,
                    '20007': ExchangeError,
                    '20008': InvalidOrder,
                    '20009': InvalidOrder,
                    '20010': OnMaintenance,
                    '20011': ExchangeError,
                    '20012': ExchangeError,
                    '20014': ExchangeError,
                    '20016': ExchangeError,
                    '20031': ExchangeError,
                    '20032': ExchangeError,
                    '20033': ExchangeError,
                    '20034': ExchangeError,
                    '20040': ExchangeError,
                    '20041': ExchangeError,
                    '20042': ExchangeError,
                    '20043': ExchangeError,
                    '20044': PermissionDenied,
                    '20045': InvalidOrder,
                    '20080': ExchangeError,
                    '21001': ExchangeError,
                    '21003': AccountSuspended,
                    '21004': AccountSuspended,
                },
                'broad': {},
            },
            'options': {
                'networks': {
                    'ETH': 'USDT20',
                    'ERC20': 'USDT20',
                    'TRX': 'USDTRX',
                    'TRC20': 'USDTRX',
                    'OMNI': 'USDT',
                },
                'accountsByType': {
                    'spot': 'spot',
                    'funding': 'wallet',
                    'future': 'derivatives',
                },
            },
            'commonCurrencies': {
                'AUTO': 'Cube',
                'BCC': 'BCC',  # initial symbol for Bitcoin Cash, now inactive
                'BDP': 'BidiPass',
                'BET': 'DAO.Casino',
                'BIT': 'BitRewards',
                'BOX': 'BOX Token',
                'CPT': 'Cryptaur',  # conflict with CPT = Contents Protocol https://github.com/ccxt/ccxt/issues/4920 and https://github.com/ccxt/ccxt/issues/6081
                'GET': 'Themis',
                'GMT': 'GMT Token',
                'HSR': 'HC',
                'IQ': 'IQ.Cash',
                'LNC': 'LinkerCoin',
                'PLA': 'PlayChip',
                'PNT': 'Penta',
                'SBTC': 'Super Bitcoin',
                'STEPN': 'GMT',
                'STX': 'STOX',
                'TV': 'Tokenville',
                'USD': 'USDT',
                'XMT': 'MTL',
                'XPNT': 'PNT',
            },
        })

    def nonce(self):
        return self.milliseconds()

    def fetch_markets(self, params={}):
        """
        retrieves data on all markets for hitbtc3
        :param dict params: extra parameters specific to the exchange api endpoint
        :returns [dict]: an array of objects representing market data
        """
        response = self.publicGetPublicSymbol(params)
        #
        #     {
        #         "AAVEUSDT_PERP":{
        #             "type":"futures",
        #             "expiry":null,
        #             "underlying":"AAVE",
        #             "base_currency":null,
        #             "quote_currency":"USDT",
        #             "quantity_increment":"0.01",
        #             "tick_size":"0.001",
        #             "take_rate":"0.0005",
        #             "make_rate":"0.0002",
        #             "fee_currency":"USDT",
        #             "margin_trading":true,
        #             "max_initial_leverage":"50.00"
        #         },
        #         "MANAUSDT":{
        #             "type":"spot",
        #             "base_currency":"MANA",
        #             "quote_currency":"USDT",
        #             "quantity_increment":"1",
        #             "tick_size":"0.0000001",
        #             "take_rate":"0.0025",
        #             "make_rate":"0.001",
        #             "fee_currency":"USDT",
        #             "margin_trading":true,
        #             "max_initial_leverage":"5.00"
        #         },
        #     }
        #
        result = []
        ids = list(response.keys())
        for i in range(0, len(ids)):
            id = ids[i]
            market = self.safe_value(response, id)
            marketType = self.safe_string(market, 'type')
            expiry = self.safe_integer(market, 'expiry')
            contract = (marketType == 'futures')
            spot = (marketType == 'spot')
            marginTrading = self.safe_value(market, 'margin_trading', False)
            margin = spot and marginTrading
            future = (expiry is not None)
            swap = (contract and not future)
            option = False
            baseId = self.safe_string_2(market, 'base_currency', 'underlying')
            quoteId = self.safe_string(market, 'quote_currency')
            feeCurrencyId = self.safe_string(market, 'fee_currency')
            base = self.safe_currency_code(baseId)
            quote = self.safe_currency_code(quoteId)
            feeCurrency = self.safe_currency_code(feeCurrencyId)
            settleId = None
            settle = None
            symbol = base + '/' + quote
            type = 'spot'
            contractSize = None
            linear = None
            inverse = None
            if contract:
                contractSize = self.parse_number('1')
                settleId = feeCurrencyId
                settle = self.safe_currency_code(settleId)
                linear = ((quote is not None) and (quote == settle))
                inverse = not linear
                symbol = symbol + ':' + settle
                if future:
                    symbol = symbol + '-' + expiry
                    type = 'future'
                else:
                    type = 'swap'
            lotString = self.safe_string(market, 'quantity_increment')
            stepString = self.safe_string(market, 'tick_size')
            lot = self.parse_number(lotString)
            step = self.parse_number(stepString)
            result.append({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'settle': settle,
                'baseId': baseId,
                'quoteId': quoteId,
                'settleId': settleId,
                'type': type,
                'spot': spot,
                'margin': margin,
                'swap': swap,
                'future': future,
                'option': option,
                'active': True,
                'contract': contract,
                'linear': linear,
                'inverse': inverse,
                'taker': self.safe_number(market, 'take_rate'),
                'maker': self.safe_number(market, 'make_rate'),
                'contractSize': contractSize,
                'expiry': expiry,
                'expiryDatetime': None,
                'strike': None,
                'optionType': None,
                'feeCurrency': feeCurrency,
                'precision': {
                    'amount': lot,
                    'price': step,
                },
                'limits': {
                    'leverage': {
                        'min': self.parse_number('1'),
                        'max': self.safe_number(market, 'max_initial_leverage', 1),
                    },
                    'amount': {
                        'min': lot,
                        'max': None,
                    },
                    'price': {
                        'min': step,
                        'max': None,
                    },
                    'cost': {
                        'min': self.parse_number(Precise.string_mul(lotString, stepString)),
                        'max': None,
                    },
                },
                'info': market,
            })
        return result

    def fetch_currencies(self, params={}):
        """
        fetches all available currencies on an exchange
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :returns dict: an associative dictionary of currencies
        """
        response = self.publicGetPublicCurrency(params)
        #
        #     {
        #       "WEALTH": {
        #         "full_name": "ConnectWealth",
        #         "payin_enabled": False,
        #         "payout_enabled": False,
        #         "transfer_enabled": True,
        #         "precision_transfer": "0.001",
        #         "networks": [
        #           {
        #             "network": "ETH",
        #             "protocol": "ERC20",
        #             "default": True,
        #             "payin_enabled": False,
        #             "payout_enabled": False,
        #             "precision_payout": "0.001",
        #             "payout_fee": "0.016800000000",
        #             "payout_is_payment_id": False,
        #             "payin_payment_id": False,
        #             "payin_confirmations": "2"
        #           }
        #         ]
        #       }
        #     }
        #
        result = {}
        currencies = list(response.keys())
        for i in range(0, len(currencies)):
            currencyId = currencies[i]
            code = self.safe_currency_code(currencyId)
            entry = response[currencyId]
            name = self.safe_string(entry, 'full_name')
            precision = self.safe_number(entry, 'precision_transfer')
            payinEnabled = self.safe_value(entry, 'payin_enabled', False)
            payoutEnabled = self.safe_value(entry, 'payout_enabled', False)
            transferEnabled = self.safe_value(entry, 'transfer_enabled', False)
            active = payinEnabled and payoutEnabled and transferEnabled
            rawNetworks = self.safe_value(entry, 'networks', [])
            networks = {}
            fee = None
            depositEnabled = None
            withdrawEnabled = None
            for j in range(0, len(rawNetworks)):
                rawNetwork = rawNetworks[j]
                networkId = self.safe_string_2(rawNetwork, 'protocol', 'network')
                network = self.safe_network(networkId)
                fee = self.safe_number(rawNetwork, 'payout_fee')
                networkPrecision = self.safe_number(rawNetwork, 'precision_payout')
                payinEnabledNetwork = self.safe_value(entry, 'payin_enabled', False)
                payoutEnabledNetwork = self.safe_value(entry, 'payout_enabled', False)
                activeNetwork = payinEnabledNetwork and payoutEnabledNetwork
                if payinEnabledNetwork and not depositEnabled:
                    depositEnabled = True
                elif not payinEnabledNetwork:
                    depositEnabled = False
                if payoutEnabledNetwork and not withdrawEnabled:
                    withdrawEnabled = True
                elif not payoutEnabledNetwork:
                    withdrawEnabled = False
                networks[network] = {
                    'info': rawNetwork,
                    'id': networkId,
                    'network': network,
                    'fee': fee,
                    'active': activeNetwork,
                    'deposit': payinEnabledNetwork,
                    'withdraw': payoutEnabledNetwork,
                    'precision': networkPrecision,
                    'limits': {
                        'withdraw': {
                            'min': None,
                            'max': None,
                        },
                    },
                }
            networksKeys = list(networks.keys())
            networksLength = len(networksKeys)
            result[code] = {
                'info': entry,
                'code': code,
                'id': currencyId,
                'precision': precision,
                'name': name,
                'active': active,
                'deposit': depositEnabled,
                'withdraw': withdrawEnabled,
                'networks': networks,
                'fee': fee if (networksLength <= 1) else None,
                'limits': {
                    'amount': {
                        'min': None,
                        'max': None,
                    },
                },
            }
        return result

    def safe_network(self, networkId):
        if networkId is None:
            return None
        else:
            return networkId.upper()

    def create_deposit_address(self, code, params={}):
        """
        create a currency deposit address
        :param str code: unified currency code of the currency for the deposit address
        :param dict params: extra parameters specific to the hitbtc api endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>`
        """
        self.load_markets()
        currency = self.currency(code)
        request = {
            'currency': currency['id'],
        }
        network = self.safe_string_upper(params, 'network')
        if (network is not None) and (code == 'USDT'):
            networks = self.safe_value(self.options, 'networks')
            parsedNetwork = self.safe_string(networks, network)
            if parsedNetwork is not None:
                request['currency'] = parsedNetwork
            params = self.omit(params, 'network')
        response = self.privatePostWalletCryptoAddress(self.extend(request, params))
        #
        #  {"currency":"ETH","address":"0xd0d9aea60c41988c3e68417e2616065617b7afd3"}
        #
        currencyId = self.safe_string(response, 'currency')
        return {
            'currency': self.safe_currency_code(currencyId),
            'address': self.safe_string(response, 'address'),
            'tag': self.safe_string(response, 'payment_id'),
            'network': None,
            'info': response,
        }

    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 hitbtc3 api endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>`
        """
        self.load_markets()
        currency = self.currency(code)
        request = {
            'currency': currency['id'],
        }
        network = self.safe_string_upper(params, 'network')
        if (network is not None) and (code == 'USDT'):
            networks = self.safe_value(self.options, 'networks')
            parsedNetwork = self.safe_string(networks, network)
            if parsedNetwork is not None:
                request['currency'] = parsedNetwork
            params = self.omit(params, 'network')
        response = self.privateGetWalletCryptoAddress(self.extend(request, params))
        #
        #  [{"currency":"ETH","address":"0xd0d9aea60c41988c3e68417e2616065617b7afd3"}]
        #
        firstAddress = self.safe_value(response, 0)
        address = self.safe_string(firstAddress, 'address')
        currencyId = self.safe_string(firstAddress, 'currency')
        tag = self.safe_string(firstAddress, 'payment_id')
        parsedCode = self.safe_currency_code(currencyId)
        return {
            'info': response,
            'address': address,
            'tag': tag,
            'code': parsedCode,  # kept here for backward-compatibility, but will be removed soon
            'currency': parsedCode,
            'network': None,
        }

    def parse_balance(self, response):
        result = {'info': response}
        for i in range(0, len(response)):
            entry = response[i]
            currencyId = self.safe_string(entry, 'currency')
            code = self.safe_currency_code(currencyId)
            account = self.account()
            account['free'] = self.safe_string(entry, 'available')
            account['used'] = self.safe_string(entry, 'reserved')
            result[code] = account
        return self.safe_balance(result)

    def fetch_balance(self, params={}):
        """
        query for balance and get the amount of funds available for trading or funds locked in orders
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>`
        """
        type = self.safe_string_lower(params, 'type', 'spot')
        params = self.omit(params, ['type'])
        accountsByType = self.safe_value(self.options, 'accountsByType', {})
        account = self.safe_string(accountsByType, type, type)
        response = None
        if account == 'wallet':
            response = self.privateGetWalletBalance(params)
        elif account == 'spot':
            response = self.privateGetSpotBalance(params)
        elif account == 'derivatives':
            response = self.privateGetFuturesBalance(params)
        else:
            keys = list(accountsByType.keys())
            raise BadRequest(self.id + ' fetchBalance() type parameter must be one of ' + ', '.join(keys))
        #
        #     [
        #       {
        #         "currency": "PAXG",
        #         "available": "0",
        #         "reserved": "0",
        #         "reserved_margin": "0",
        #       },
        #       ...
        #     ]
        #
        return self.parse_balance(response)

    def fetch_ticker(self, symbol, params={}):
        """
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        response = self.fetch_tickers([symbol], params)
        return self.safe_value(response, symbol)

    def fetch_tickers(self, symbols=None, params={}):
        """
        fetches price tickers for multiple markets, statistical calculations with the information calculated over the past 24 hours each market
        :param [str]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        self.load_markets()
        symbols = self.market_symbols(symbols)
        request = {}
        if symbols is not None:
            marketIds = self.market_ids(symbols)
            delimited = ','.join(marketIds)
            request['symbols'] = delimited
        response = self.publicGetPublicTicker(self.extend(request, params))
        #
        #     {
        #       "BTCUSDT": {
        #         "ask": "63049.06",
        #         "bid": "63046.41",
        #         "last": "63048.36",
        #         "low": "62010.00",
        #         "high": "66657.99",
        #         "open": "64839.75",
        #         "volume": "15272.13278",
        #         "volume_quote": "976312127.6277998",
        #         "timestamp": "2021-10-22T04:25:47.573Z"
        #       }
        #     }
        #
        result = {}
        keys = list(response.keys())
        for i in range(0, len(keys)):
            marketId = keys[i]
            market = self.safe_market(marketId)
            symbol = market['symbol']
            entry = response[marketId]
            result[symbol] = self.parse_ticker(entry, market)
        return self.filter_by_array(result, 'symbol', symbols)

    def parse_ticker(self, ticker, market=None):
        #
        #     {
        #       "ask": "62756.01",
        #       "bid": "62754.09",
        #       "last": "62755.87",
        #       "low": "62010.00",
        #       "high": "66657.99",
        #       "open": "65089.27",
        #       "volume": "16719.50366",
        #       "volume_quote": "1063422878.8156828",
        #       "timestamp": "2021-10-22T07:29:14.585Z"
        #     }
        #
        timestamp = self.parse8601(ticker['timestamp'])
        symbol = self.safe_symbol(None, market)
        baseVolume = self.safe_string(ticker, 'volume')
        quoteVolume = self.safe_string(ticker, 'volume_quote')
        open = self.safe_string(ticker, 'open')
        last = self.safe_string(ticker, 'last')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': self.safe_string(ticker, 'high'),
            'low': self.safe_string(ticker, 'low'),
            'bid': self.safe_string(ticker, 'bid'),
            'bidVolume': None,
            'ask': self.safe_string(ticker, 'ask'),
            'askVolume': None,
            'vwap': None,
            'open': open,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': None,
            'percentage': None,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market)

    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 hitbtc3 api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html?#public-trades>`
        """
        self.load_markets()
        market = None
        request = {}
        if symbol is not None:
            market = self.market(symbol)
            # symbol is optional for hitbtc fetchTrades
            request['symbols'] = market['id']
        if limit is not None:
            request['limit'] = limit
        if since is not None:
            request['from'] = since
        response = self.publicGetPublicTrades(self.extend(request, params))
        marketIds = list(response.keys())
        trades = []
        for i in range(0, len(marketIds)):
            marketId = marketIds[i]
            market = self.market(marketId)
            rawTrades = response[marketId]
            parsed = self.parse_trades(rawTrades, market)
            trades = self.array_concat(trades, parsed)
        return trades

    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 hitbtc3 api endpoint
        :param str|None params['marginMode']: 'cross' or 'isolated' only 'isolated' is supported
        :param bool|None params['margin']: True for fetching margin trades
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
        """
        self.load_markets()
        market = None
        request = {}
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if limit is not None:
            request['limit'] = limit
        if since is not None:
            request['from'] = since
        marketType = None
        marketType, params = self.handle_market_type_and_params('fetchMyTrades', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateGetSpotHistoryTrade',
            'swap': 'privateGetFuturesHistoryTrade',
            'margin': 'privateGetMarginHistoryTrade',
        })
        marginMode, query = self.handle_margin_mode_and_params('fetchMyTrades', params)
        if marginMode is not None:
            method = 'privateGetMarginHistoryTrade'
        response = getattr(self, method)(self.extend(request, query))
        return self.parse_trades(response, market, since, limit)

    def parse_trade(self, trade, market=None):
        #
        # createOrder(market)
        #
        #  {
        #      id: '1569252895',
        #      position_id: '0',
        #      quantity: '10',
        #      price: '0.03919424',
        #      fee: '0.000979856000',
        #      timestamp: '2022-01-25T19:38:36.153Z',
        #      taker: True
        #  }
        #
        # fetchTrades
        #
        #  {
        #      id: 974786185,
        #      price: '0.032462',
        #      qty: '0.3673',
        #      side: 'buy',
        #      timestamp: '2020-10-16T12:57:39.846Z'
        #  }
        #
        # fetchMyTrades spot
        #
        #  {
        #      id: 277210397,
        #      clientOrderId: '6e102f3e7f3f4e04aeeb1cdc95592f1a',
        #      orderId: 28102855393,
        #      symbol: 'ETHBTC',
        #      side: 'sell',
        #      quantity: '0.002',
        #      price: '0.073365',
        #      fee: '0.000000147',
        #      timestamp: '2018-04-28T18:39:55.345Z',
        #      taker: True
        #  }
        #
        # fetchMyTrades swap and margin
        #
        #  {
        #      "id": 4718564,
        #      "order_id": 58730811958,
        #      "client_order_id": "475c47d97f867f09726186eb22b4c3d4",
        #      "symbol": "BTCUSDT_PERP",
        #      "side": "sell",
        #      "quantity": "0.0001",
        #      "price": "41118.51",
        #      "fee": "0.002055925500",
        #      "timestamp": "2022-03-17T05:23:17.795Z",
        #      "taker": True,
        #      "position_id": 2350122,
        #      "pnl": "0.002255000000",
        #      "liquidation": False
        #  }
        #
        timestamp = self.parse8601(trade['timestamp'])
        marketId = self.safe_string(trade, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        fee = None
        feeCostString = self.safe_string(trade, 'fee')
        taker = self.safe_value(trade, 'taker')
        takerOrMaker = None
        if taker is not None:
            takerOrMaker = 'taker' if taker else 'maker'
        if feeCostString is not None:
            info = self.safe_value(market, 'info', {})
            feeCurrency = self.safe_string(info, 'fee_currency')
            feeCurrencyCode = self.safe_currency_code(feeCurrency)
            fee = {
                'cost': feeCostString,
                'currency': feeCurrencyCode,
            }
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        orderId = self.safe_string_2(trade, 'clientOrderId', 'client_order_id')
        priceString = self.safe_string(trade, 'price')
        amountString = self.safe_string_2(trade, 'quantity', 'qty')
        side = self.safe_string(trade, 'side')
        id = self.safe_string(trade, 'id')
        return self.safe_trade({
            'info': trade,
            'id': id,
            'order': orderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': symbol,
            'type': None,
            'side': side,
            'takerOrMaker': takerOrMaker,
            'price': priceString,
            'amount': amountString,
            'cost': None,
            'fee': fee,
        }, market)

    def fetch_transactions_helper(self, types, code, since, limit, params):
        self.load_markets()
        request = {
            'types': types,
        }
        currency = None
        if code is not None:
            currency = self.currency(code)
            request['currencies'] = currency['id']
        if since is not None:
            request['from'] = self.iso8601(since)
        if limit is not None:
            request['limit'] = limit
        response = self.privateGetWalletTransactions(self.extend(request, params))
        #
        #     [
        #       {
        #         "id": "101609495",
        #         "created_at": "2018-03-06T22:05:06.507Z",
        #         "updated_at": "2018-03-06T22:11:45.03Z",
        #         "status": "SUCCESS",
        #         "type": "DEPOSIT",
        #         "subtype": "BLOCKCHAIN",
        #         "native": {
        #           "tx_id": "e20b0965-4024-44d0-b63f-7fb8996a6706",
        #           "index": "881652766",
        #           "currency": "ETH",
        #           "amount": "0.01418088",
        #           "hash": "d95dbbff3f9234114f1211ab0ba2a94f03f394866fd5749d74a1edab80e6c5d3",
        #           "address": "0xd9259302c32c0a0295d86a39185c9e14f6ba0a0d",
        #           "confirmations": "20",
        #           "senders": [
        #             "0x243bec9256c9a3469da22103891465b47583d9f1"
        #           ]
        #         }
        #       }
        #     ]
        #
        return self.parse_transactions(response, currency, since, limit, params)

    def parse_transaction_status(self, status):
        statuses = {
            'PENDING': 'pending',
            'FAILED': 'failed',
            'SUCCESS': 'ok',
        }
        return self.safe_string(statuses, status, status)

    def parse_transaction_type(self, type):
        types = {
            'DEPOSIT': 'deposit',
            'WITHDRAW': 'withdrawal',
        }
        return self.safe_string(types, type, type)

    def parse_transaction(self, transaction, currency=None):
        #
        # transaction
        #
        #     {
        #       "id": "101609495",
        #       "created_at": "2018-03-06T22:05:06.507Z",
        #       "updated_at": "2018-03-06T22:11:45.03Z",
        #       "status": "SUCCESS",
        #       "type": "DEPOSIT",  # DEPOSIT, WITHDRAW, ..
        #       "subtype": "BLOCKCHAIN",
        #       "native": {
        #         "tx_id": "e20b0965-4024-44d0-b63f-7fb8996a6706",
        #         "index": "881652766",
        #         "currency": "ETH",
        #         "amount": "0.01418088",
        #         "hash": "d95dbbff3f9234114f1211ab0ba2a94f03f394866fd5749d74a1edab80e6c5d3",
        #         "address": "0xd9259302c32c0a0295d86a39185c9e14f6ba0a0d",
        #         "confirmations": "20",
        #         "senders": [
        #           "0x243bec9256c9a3469da22103891465b47583d9f1"
        #         ],
        #         "fee": "1.22"  # only for WITHDRAW
        #       }
        #     }
        #
        # withdraw
        #
        #     {
        #         "id":"084cfcd5-06b9-4826-882e-fdb75ec3625d"
        #     }
        #
        id = self.safe_string(transaction, 'id')
        timestamp = self.parse8601(self.safe_string(transaction, 'created_at'))
        updated = self.parse8601(self.safe_string(transaction, 'updated_at'))
        type = self.parse_transaction_type(self.safe_string(transaction, 'type'))
        status = self.parse_transaction_status(self.safe_string(transaction, 'status'))
        native = self.safe_value(transaction, 'native', {})
        currencyId = self.safe_string(native, 'currency')
        code = self.safe_currency_code(currencyId)
        txhash = self.safe_string(native, 'hash')
        address = self.safe_string(native, 'address')
        addressTo = address
        tag = self.safe_string(native, 'payment_id')
        tagTo = tag
        sender = self.safe_value(native, 'senders')
        addressFrom = self.safe_string(sender, 0)
        amount = self.safe_number(native, 'amount')
        fee = {
            'currency': None,
            'cost': None,
            'rate': None,
        }
        feeCost = self.safe_number(native, 'fee')
        if feeCost is not None:
            fee['currency'] = code
            fee['cost'] = feeCost
        return {
            'info': transaction,
            'id': id,
            'txid': txhash,
            'type': type,
            'code': code,  # kept here for backward-compatibility, but will be removed soon
            'currency': code,
            'network': None,
            'amount': amount,
            'status': status,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'address': address,
            'addressFrom': addressFrom,
            'addressTo': addressTo,
            'tag': tag,
            'tagFrom': None,
            'tagTo': tagTo,
            'updated': updated,
            'comment': None,
            'fee': fee,
        }

    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 hitbtc3 api endpoint
        :returns dict: a list of `transaction structure <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        return self.fetch_transactions_helper('DEPOSIT,WITHDRAW', code, since, limit, params)

    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 hitbtc3 api endpoint
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        return self.fetch_transactions_helper('DEPOSIT', code, since, limit, params)

    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 hitbtc3 api endpoint
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        return self.fetch_transactions_helper('WITHDRAW', code, since, limit, params)

    def fetch_order_books(self, symbols=None, limit=None, params={}):
        """
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data for multiple markets
        :param [str]|None symbols: list of unified market symbols, all symbols fetched if None, default is None
        :param int|None limit: max number of entries per orderbook to return, default is None
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :returns dict: a dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbol
        """
        self.load_markets()
        request = {}
        if symbols is not None:
            marketIds = self.market_ids(symbols)
            request['symbols'] = ','.join(marketIds)
        if limit is not None:
            request['depth'] = limit
        response = self.publicGetPublicOrderbook(self.extend(request, params))
        result = {}
        marketIds = list(response.keys())
        for i in range(0, len(marketIds)):
            marketId = marketIds[i]
            orderbook = response[marketId]
            symbol = self.safe_symbol(marketId)
            timestamp = self.parse8601(self.safe_string(orderbook, 'timestamp'))
            result[symbol] = self.parse_order_book(response[marketId], symbol, timestamp, 'bid', 'ask')
        return result

    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 hitbtc3 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
        """
        result = self.fetch_order_books([symbol], limit, params)
        return result[symbol]

    def parse_trading_fee(self, fee, market=None):
        #
        #     {
        #         "symbol":"ARVUSDT",  # returned from fetchTradingFees only
        #         "take_rate":"0.0009",
        #         "make_rate":"0.0009"
        #     }
        #
        taker = self.safe_number(fee, 'take_rate')
        maker = self.safe_number(fee, 'make_rate')
        marketId = self.safe_string(fee, 'symbol')
        symbol = self.safe_symbol(marketId, market)
        return {
            'info': fee,
            'symbol': symbol,
            'taker': taker,
            'maker': maker,
        }

    def fetch_trading_fee(self, symbol, params={}):
        """
        fetch the trading fees for a market
        :param str symbol: unified market symbol
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/en/latest/manual.html#fee-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        method = self.get_supported_mapping(market['type'], {
            'spot': 'privateGetSpotFeeSymbol',
            'swap': 'privateGetFuturesFeeSymbol',
        })
        response = getattr(self, method)(self.extend(request, params))
        #
        #     {
        #         "take_rate":"0.0009",
        #         "make_rate":"0.0009"
        #     }
        #
        return self.parse_trading_fee(response, market)

    def fetch_trading_fees(self, symbols=None, params={}):
        """
        fetch the trading fees for multiple markets
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/en/latest/manual.html#fee-structure>` indexed by market symbols
        """
        self.load_markets()
        marketType, query = self.handle_market_type_and_params('fetchTradingFees', None, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateGetSpotFee',
            'swap': 'privateGetFuturesFee',
        })
        response = getattr(self, method)(query)
        #
        #     [
        #         {
        #             "symbol":"ARVUSDT",
        #             "take_rate":"0.0009",
        #             "make_rate":"0.0009"
        #         }
        #     ]
        #
        result = {}
        for i in range(0, len(response)):
            fee = self.parse_trading_fee(response[i])
            symbol = fee['symbol']
            result[symbol] = fee
        return result

    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 hitbtc3 api endpoint
        :returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbols': market['id'],
            'period': self.safe_string(self.timeframes, timeframe, timeframe),
        }
        if since is not None:
            request['from'] = self.iso8601(since)
        if limit is not None:
            request['limit'] = limit
        price = self.safe_string(params, 'price')
        params = self.omit(params, 'price')
        method = 'publicGetPublicCandles'
        if price == 'mark':
            method = 'publicGetPublicFuturesCandlesMarkPrice'
        elif price == 'index':
            method = 'publicGetPublicFuturesCandlesIndexPrice'
        elif price == 'premiumIndex':
            method = 'publicGetPublicFuturesCandlesPremiumIndex'
        response = getattr(self, method)(self.extend(request, params))
        #
        # Spot and Swap
        #
        #     {
        #         "ETHUSDT": [
        #             {
        #                 "timestamp": "2021-10-25T07:38:00.000Z",
        #                 "open": "4173.391",
        #                 "close": "4170.923",
        #                 "min": "4170.923",
        #                 "max": "4173.986",
        #                 "volume": "0.1879",
        #                 "volume_quote": "784.2517846"
        #             }
        #         ]
        #     }
        #
        # Mark, Index and Premium Index
        #
        #     {
        #         "BTCUSDT_PERP": [
        #             {
        #                 "timestamp": "2022-04-01T01:28:00.000Z",
        #                 "open": "45146.39",
        #                 "close": "45219.43",
        #                 "min": "45146.39",
        #                 "max": "45219.43"
        #             },
        #         ]
        #     }
        #
        ohlcvs = self.safe_value(response, market['id'])
        return self.parse_ohlcvs(ohlcvs, market, timeframe, since, limit)

    def parse_ohlcv(self, ohlcv, market=None):
        #
        # Spot and Swap
        #
        #     {
        #         "timestamp":"2015-08-20T19:01:00.000Z",
        #         "open":"0.006",
        #         "close":"0.006",
        #         "min":"0.006",
        #         "max":"0.006",
        #         "volume":"0.003",
        #         "volume_quote":"0.000018"
        #     }
        #
        # Mark, Index and Premium Index
        #
        #     {
        #         "timestamp": "2022-04-01T01:28:00.000Z",
        #         "open": "45146.39",
        #         "close": "45219.43",
        #         "min": "45146.39",
        #         "max": "45219.43"
        #     },
        #
        return [
            self.parse8601(self.safe_string(ohlcv, 'timestamp')),
            self.safe_number(ohlcv, 'open'),
            self.safe_number(ohlcv, 'max'),
            self.safe_number(ohlcv, 'min'),
            self.safe_number(ohlcv, 'close'),
            self.safe_number(ohlcv, 'volume'),
        ]

    def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches information on multiple closed 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 hitbtc3 api endpoint
        :param str|None params['marginMode']: 'cross' or 'isolated' only 'isolated' is supported
        :param bool|None params['margin']: True for fetching margin orders
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        market = None
        request = {}
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            request['from'] = self.iso8601(since)
        if limit is not None:
            request['limit'] = limit
        marketType = None
        marketType, params = self.handle_market_type_and_params('fetchClosedOrders', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateGetSpotHistoryOrder',
            'swap': 'privateGetFuturesHistoryOrder',
            'margin': 'privateGetMarginHistoryOrder',
        })
        marginMode, query = self.handle_margin_mode_and_params('fetchClosedOrders', params)
        if marginMode is not None:
            method = 'privateGetMarginHistoryOrder'
        response = getattr(self, method)(self.extend(request, query))
        parsed = self.parse_orders(response, market, since, limit)
        return self.filter_by_array(parsed, 'status', ['closed', 'canceled'], False)

    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 hitbtc3 api endpoint
        :param str|None params['marginMode']: 'cross' or 'isolated' only 'isolated' is supported
        :param bool|None params['margin']: True for fetching a margin order
        :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        market = None
        if symbol is not None:
            market = self.market(symbol)
        marketType = None
        marketType, params = self.handle_market_type_and_params('fetchOrder', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateGetSpotHistoryOrder',
            'swap': 'privateGetFuturesHistoryOrder',
            'margin': 'privateGetMarginHistoryOrder',
        })
        marginMode, query = self.handle_margin_mode_and_params('fetchOrder', params)
        if marginMode is not None:
            method = 'privateGetMarginHistoryOrder'
        request = {
            'client_order_id': id,
        }
        response = getattr(self, method)(self.extend(request, query))
        #
        #     [
        #       {
        #         "id": "685965182082",
        #         "client_order_id": "B3CBm9uGg9oYQlw96bBSEt38-6gbgBO0",
        #         "symbol": "BTCUSDT",
        #         "side": "buy",
        #         "status": "new",
        #         "type": "limit",
        #         "time_in_force": "GTC",
        #         "quantity": "0.00010",
        #         "quantity_cumulative": "0",
        #         "price": "50000.00",
        #         "price_average": "0",
        #         "created_at": "2021-10-26T11:40:09.287Z",
        #         "updated_at": "2021-10-26T11:40:09.287Z"
        #       }
        #     ]
        #
        order = self.safe_value(response, 0)
        return self.parse_order(order, market)

    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 hitbtc3 api endpoint
        :param str|None params['marginMode']: 'cross' or 'isolated' only 'isolated' is supported
        :param bool|None params['margin']: True for fetching margin trades
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
        """
        self.load_markets()
        market = None
        if symbol is not None:
            market = self.market(symbol)
        request = {
            'order_id': id,  # exchange assigned order id as oppose to the client order id
        }
        marketType = None
        marketType, params = self.handle_market_type_and_params('fetchOrderTrades', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateGetSpotHistoryTrade',
            'swap': 'privateGetFuturesHistoryTrade',
            'margin': 'privateGetMarginHistoryTrade',
        })
        marginMode, query = self.handle_margin_mode_and_params('fetchOrderTrades', params)
        if marginMode is not None:
            method = 'privateGetMarginHistoryTrade'
        response = getattr(self, method)(self.extend(request, query))
        #
        # Spot
        #
        #     [
        #       {
        #         "id": 1393448977,
        #         "order_id": 653496804534,
        #         "client_order_id": "065f6f0ff9d54547848454182263d7b4",
        #         "symbol": "DICEETH",
        #         "side": "buy",
        #         "quantity": "1.4",
        #         "price": "0.00261455",
        #         "fee": "0.000003294333",
        #         "timestamp": "2021-09-19T05:35:56.601Z",
        #         "taker": True
        #       }
        #     ]
        #
        # Swap and Margin
        #
        #     [
        #         {
        #             "id": 4718551,
        #             "order_id": 58730748700,
        #             "client_order_id": "dcbcd8549e3445ee922665946002ef67",
        #             "symbol": "BTCUSDT_PERP",
        #             "side": "buy",
        #             "quantity": "0.0001",
        #             "price": "41095.96",
        #             "fee": "0.002054798000",
        #             "timestamp": "2022-03-17T05:23:02.217Z",
        #             "taker": True,
        #             "position_id": 2350122,
        #             "pnl": "0",
        #             "liquidation": False
        #         }
        #     ]
        #
        return self.parse_trades(response, market, since, limit)

    def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetch all unfilled currently open orders
        :param str|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch open orders for
        :param int|None limit: the maximum number of  open orders structures to retrieve
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :param str|None params['marginMode']: 'cross' or 'isolated' only 'isolated' is supported
        :param bool|None params['margin']: True for fetching open margin orders
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        market = None
        request = {}
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        marketType = None
        marketType, params = self.handle_market_type_and_params('fetchOpenOrders', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateGetSpotOrder',
            'swap': 'privateGetFuturesOrder',
            'margin': 'privateGetMarginOrder',
        })
        marginMode, query = self.handle_margin_mode_and_params('fetchOpenOrders', params)
        if marginMode is not None:
            method = 'privateGetMarginOrder'
        response = getattr(self, method)(self.extend(request, query))
        #
        #     [
        #       {
        #         "id": "488953123149",
        #         "client_order_id": "103ad305301e4c3590045b13de15b36e",
        #         "symbol": "BTCUSDT",
        #         "side": "buy",
        #         "status": "new",
        #         "type": "limit",
        #         "time_in_force": "GTC",
        #         "quantity": "0.00001",
        #         "quantity_cumulative": "0",
        #         "price": "0.01",
        #         "post_only": False,
        #         "created_at": "2021-04-13T13:06:16.567Z",
        #         "updated_at": "2021-04-13T13:06:16.567Z"
        #       }
        #     ]
        #
        return self.parse_orders(response, market, since, limit)

    def fetch_open_order(self, id, symbol=None, params={}):
        """
        fetch an open order by it's id
        :param str id: order id
        :param str|None symbol: unified market symbol, default is None
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :param str|None params['marginMode']: 'cross' or 'isolated' only 'isolated' is supported
        :param bool|None params['margin']: True for fetching an open margin order
        :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        market = None
        if symbol is not None:
            market = self.market(symbol)
        marketType = None
        marketType, params = self.handle_market_type_and_params('fetchOpenOrder', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateGetSpotOrderClientOrderId',
            'swap': 'privateGetFuturesOrderClientOrderId',
            'margin': 'privateGetMarginOrderClientOrderId',
        })
        marginMode, query = self.handle_margin_mode_and_params('fetchOpenOrder', params)
        if marginMode is not None:
            method = 'privateGetMarginOrderClientOrderId'
        request = {
            'client_order_id': id,
        }
        response = getattr(self, method)(self.extend(request, query))
        return self.parse_order(response, market)

    def cancel_all_orders(self, symbol=None, params={}):
        """
        cancel all open orders
        :param str|None symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :param str|None params['marginMode']: 'cross' or 'isolated' only 'isolated' is supported
        :param bool|None params['margin']: True for canceling margin orders
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        market = None
        request = {}
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        marketType = None
        marketType, params = self.handle_market_type_and_params('cancelAllOrders', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateDeleteSpotOrder',
            'swap': 'privateDeleteFuturesOrder',
            'margin': 'privateDeleteMarginOrder',
        })
        marginMode, query = self.handle_margin_mode_and_params('cancelAllOrders', params)
        if marginMode is not None:
            method = 'privateDeleteMarginOrder'
        response = getattr(self, method)(self.extend(request, query))
        return self.parse_orders(response, market)

    def cancel_order(self, id, symbol=None, params={}):
        """
        cancels an open order
        :param str id: order id
        :param str|None symbol: unified symbol of the market the order was made in
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :param str|None params['marginMode']: 'cross' or 'isolated' only 'isolated' is supported
        :param bool|None params['margin']: True for canceling a margin order
        :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        market = None
        request = {
            'client_order_id': id,
        }
        if symbol is not None:
            market = self.market(symbol)
        marketType = None
        marketType, params = self.handle_market_type_and_params('cancelOrder', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateDeleteSpotOrderClientOrderId',
            'swap': 'privateDeleteFuturesOrderClientOrderId',
            'margin': 'privateDeleteMarginOrderClientOrderId',
        })
        marginMode, query = self.handle_margin_mode_and_params('cancelOrder', params)
        if marginMode is not None:
            method = 'privateDeleteMarginOrderClientOrderId'
        response = getattr(self, method)(self.extend(request, query))
        return self.parse_order(response, market)

    def edit_order(self, id, symbol, type, side, amount, price=None, params={}):
        self.load_markets()
        market = None
        request = {
            'client_order_id': id,
            'quantity': self.amount_to_precision(symbol, amount),
        }
        if (type == 'limit') or (type == 'stopLimit'):
            if price is None:
                raise ExchangeError(self.id + ' editOrder() limit order requires price')
            request['price'] = self.price_to_precision(symbol, price)
        if symbol is not None:
            market = self.market(symbol)
        marketType = None
        marketType, params = self.handle_market_type_and_params('editOrder', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'privatePatchSpotOrderClientOrderId',
            'swap': 'privatePatchFuturesOrderClientOrderId',
            'margin': 'privatePatchMarginOrderClientOrderId',
        })
        marginMode, query = self.handle_margin_mode_and_params('editOrder', params)
        if marginMode is not None:
            method = 'privatePatchMarginOrderClientOrderId'
        response = getattr(self, method)(self.extend(request, query))
        return self.parse_order(response, market)

    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 hitbtc3 api endpoint
        :param str|None params['marginMode']: 'cross' or 'isolated' only 'isolated' is supported, defaults to spot-margin endpoint if self is set
        :param bool|None params['margin']: True for creating a margin order
        :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'type': type,
            'side': side,
            'quantity': self.amount_to_precision(symbol, amount),
            'symbol': market['id'],
            # 'client_order_id': 'r42gdPjNMZN-H_xs8RKl2wljg_dfgdg4',  # Optional
            # 'time_in_force': 'GTC',  # Optional GTC, IOC, FOK, Day, GTD
            # 'price': self.price_to_precision(symbol, price),  # Required if type is limit, stopLimit, or takeProfitLimit
            # 'stop_price': self.safe_number(params, 'stop_price'),  # Required if type is stopLimit, stopMarket, takeProfitLimit, takeProfitMarket
            # 'expire_time': '2021-06-15T17:01:05.092Z',  # Required if timeInForce is GTD
            # 'strict_validate': False,
            # 'post_only': False,  # Optional
            # 'reduce_only': False,  # Optional
            # 'display_quantity': '0',  # Optional
            # 'take_rate': 0.001,  # Optional
            # 'make_rate': 0.001,  # Optional
        }
        reduceOnly = self.safe_value(params, 'reduceOnly')
        if reduceOnly is not None:
            if (market['type'] != 'swap') and (market['type'] != 'margin'):
                raise InvalidOrder(self.id + ' createOrder() does not support reduce_only for ' + market['type'] + ' orders, reduce_only orders are supported for swap and margin markets only')
        if reduceOnly is True:
            request['reduce_only'] = reduceOnly
        timeInForce = self.safe_string_2(params, 'timeInForce', 'time_in_force')
        expireTime = self.safe_string(params, 'expire_time')
        stopPrice = self.safe_number_2(params, 'stopPrice', 'stop_price')
        if (type == 'limit') or (type == 'stopLimit') or (type == 'takeProfitLimit'):
            if price is None:
                raise ExchangeError(self.id + ' createOrder() requires a price argument for limit orders')
            request['price'] = self.price_to_precision(symbol, price)
        if (timeInForce == 'GTD'):
            if expireTime is None:
                raise ExchangeError(self.id + ' createOrder() requires an expire_time parameter for a GTD order')
            request['expire_time'] = expireTime
        if (type == 'stopLimit') or (type == 'stopMarket') or (type == 'takeProfitLimit') or (type == 'takeProfitMarket'):
            if stopPrice is None:
                raise ExchangeError(self.id + ' createOrder() requires a stopPrice parameter for stop-loss and take-profit orders')
            request['stop_price'] = self.price_to_precision(symbol, stopPrice)
        marketType = None
        marketType, params = self.handle_market_type_and_params('createOrder', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'privatePostSpotOrder',
            'swap': 'privatePostFuturesOrder',
            'margin': 'privatePostMarginOrder',
        })
        marginMode, query = self.handle_margin_mode_and_params('createOrder', params)
        if marginMode is not None:
            method = 'privatePostMarginOrder'
        response = getattr(self, method)(self.extend(request, query))
        return self.parse_order(response, market)

    def parse_order_status(self, status):
        statuses = {
            'new': 'open',
            'suspended': 'open',
            'partiallyFilled': 'open',
            'filled': 'closed',
            'canceled': 'canceled',
            'expired': 'failed',
        }
        return self.safe_string(statuses, status, status)

    def parse_order(self, order, market=None):
        #
        # limit
        #     {
        #       "id": 488953123149,
        #       "client_order_id": "103ad305301e4c3590045b13de15b36e",
        #       "symbol": "BTCUSDT",
        #       "side": "buy",
        #       "status": "new",
        #       "type": "limit",
        #       "time_in_force": "GTC",
        #       "quantity": "0.00001",
        #       "quantity_cumulative": "0",
        #       "price": "0.01",
        #       "price_average": "0.01",
        #       "post_only": False,
        #       "created_at": "2021-04-13T13:06:16.567Z",
        #       "updated_at": "2021-04-13T13:06:16.567Z"
        #     }
        #
        # market
        #     {
        #       "id": "685877626834",
        #       "client_order_id": "Yshl7G-EjaREyXQYaGbsmdtVbW-nzQwu",
        #       "symbol": "BTCUSDT",
        #       "side": "buy",
        #       "status": "filled",
        #       "type": "market",
        #       "time_in_force": "GTC",
        #       "quantity": "0.00010",
        #       "quantity_cumulative": "0.00010",
        #       "post_only": False,
        #       "created_at": "2021-10-26T08:55:55.1Z",
        #       "updated_at": "2021-10-26T08:55:55.1Z",
        #       "trades": [
        #         {
        #           "id": "1437229630",
        #           "position_id": "0",
        #           "quantity": "0.00010",
        #           "price": "62884.78",
        #           "fee": "0.005659630200",
        #           "timestamp": "2021-10-26T08:55:55.1Z",
        #           "taker": True
        #         }
        #       ]
        #     }
        #
        # swap and margin
        #
        #     {
        #         "id": 58418961892,
        #         "client_order_id": "r42gdPjNMZN-H_xs8RKl2wljg_dfgdg4",
        #         "symbol": "BTCUSDT_PERP",
        #         "side": "buy",
        #         "status": "new",
        #         "type": "limit",
        #         "time_in_force": "GTC",
        #         "quantity": "0.0005",
        #         "quantity_cumulative": "0",
        #         "price": "30000.00",
        #         "post_only": False,
        #         "reduce_only": False,
        #         "created_at": "2022-03-16T08:16:53.039Z",
        #         "updated_at": "2022-03-16T08:16:53.039Z"
        #     }
        #
        id = self.safe_string(order, 'client_order_id')
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        side = self.safe_string(order, 'side')
        type = self.safe_string(order, 'type')
        amount = self.safe_string(order, 'quantity')
        price = self.safe_string(order, 'price')
        average = self.safe_string(order, 'price_average')
        created = self.safe_string(order, 'created_at')
        timestamp = self.parse8601(created)
        updated = self.safe_string(order, 'updated_at')
        lastTradeTimestamp = None
        if updated != created:
            lastTradeTimestamp = self.parse8601(updated)
        filled = self.safe_string(order, 'quantity_cumulative')
        status = self.parse_order_status(self.safe_string(order, 'status'))
        marketId = self.safe_string(order, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        postOnly = self.safe_value(order, 'post_only')
        timeInForce = self.safe_string(order, 'time_in_force')
        rawTrades = self.safe_value(order, 'trades')
        return self.safe_order({
            'info': order,
            'id': id,
            'clientOrderId': id,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': lastTradeTimestamp,
            'symbol': symbol,
            'price': price,
            'amount': amount,
            'type': type,
            'side': side,
            'timeInForce': timeInForce,
            'postOnly': postOnly,
            'reduceOnly': self.safe_value(order, 'reduce_only'),
            'filled': filled,
            'remaining': None,
            'cost': None,
            'status': status,
            'average': average,
            'trades': rawTrades,
            'fee': None,
        }, market)

    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 hitbtc3 api endpoint
        :returns dict: a `transfer structure <https://docs.ccxt.com/en/latest/manual.html#transfer-structure>`
        """
        # account can be "spot", "wallet", or "derivatives"
        self.load_markets()
        currency = self.currency(code)
        requestAmount = self.currency_to_precision(code, amount)
        accountsByType = self.safe_value(self.options, 'accountsByType', {})
        fromAccount = fromAccount.lower()
        toAccount = toAccount.lower()
        fromId = self.safe_string(accountsByType, fromAccount, fromAccount)
        toId = self.safe_string(accountsByType, toAccount, toAccount)
        if fromId == toId:
            raise BadRequest(self.id + ' transfer() fromAccount and toAccount arguments cannot be the same account')
        request = {
            'currency': currency['id'],
            'amount': requestAmount,
            'source': fromId,
            'destination': toId,
        }
        response = self.privatePostWalletTransfer(self.extend(request, params))
        #
        #     [
        #         '2db6ebab-fb26-4537-9ef8-1a689472d236'
        #     ]
        #
        return self.parse_transfer(response, currency)

    def parse_transfer(self, transfer, currency=None):
        #
        # transfer
        #
        #     [
        #         '2db6ebab-fb26-4537-9ef8-1a689472d236'
        #     ]
        #
        timestamp = self.milliseconds()
        return {
            'id': self.safe_string(transfer, 0),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'currency': self.safe_currency_code(None, currency),
            'amount': None,
            'fromAccount': None,
            'toAccount': None,
            'status': None,
            'info': transfer,
        }

    def convert_currency_network(self, code, amount, fromNetwork, toNetwork, params):
        self.load_markets()
        if code != 'USDT':
            raise ExchangeError(self.id + ' convertCurrencyNetwork() only supports USDT currently')
        networks = self.safe_value(self.options, 'networks', {})
        fromNetwork = fromNetwork.upper()
        toNetwork = toNetwork.upper()
        fromNetwork = self.safe_string(networks, fromNetwork)  # handle ETH>ERC20 alias
        toNetwork = self.safe_string(networks, toNetwork)  # handle ETH>ERC20 alias
        if fromNetwork == toNetwork:
            raise BadRequest(self.id + ' convertCurrencyNetwork() fromNetwork cannot be the same as toNetwork')
        if (fromNetwork is None) or (toNetwork is None):
            keys = list(networks.keys())
            raise ArgumentsRequired(self.id + ' convertCurrencyNetwork() requires a fromNetwork parameter and a toNetwork parameter, supported networks are ' + ', '.join(keys))
        request = {
            'from_currency': fromNetwork,
            'to_currency': toNetwork,
            'amount': self.currency_to_precision(code, amount),
        }
        response = self.privatePostWalletConvert(self.extend(request, params))
        # {"result":["587a1868-e62d-4d8e-b27c-dbdb2ee96149","e168df74-c041-41f2-b76c-e43e4fed5bc7"]}
        return {
            'info': response,
        }

    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 hitbtc3 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)
        self.load_markets()
        self.check_address(address)
        currency = self.currency(code)
        request = {
            'currency': currency['id'],
            'amount': amount,
            'address': address,
        }
        if tag is not None:
            request['payment_id'] = tag
        networks = self.safe_value(self.options, 'networks', {})
        network = self.safe_string_upper(params, 'network')
        if (network is not None) and (code == 'USDT'):
            parsedNetwork = self.safe_string(networks, network)
            if parsedNetwork is not None:
                request['currency'] = parsedNetwork
            params = self.omit(params, 'network')
        response = self.privatePostWalletCryptoWithdraw(self.extend(request, params))
        #
        #     {
        #         "id":"084cfcd5-06b9-4826-882e-fdb75ec3625d"
        #     }
        #
        return self.parse_transaction(response, currency)

    def fetch_funding_rate_history(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches historical funding rate prices
        :param str|None symbol: unified symbol of the market to fetch the funding rate history for
        :param int|None since: timestamp in ms of the earliest funding rate to fetch
        :param int|None limit: the maximum amount of `funding rate structures <https://docs.ccxt.com/en/latest/manual.html?#funding-rate-history-structure>` to fetch
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :returns [dict]: a list of `funding rate structures <https://docs.ccxt.com/en/latest/manual.html?#funding-rate-history-structure>`
        """
        self.load_markets()
        market = None
        request = {
            # all arguments are optional
            # 'symbols': Comma separated list of symbol codes,
            # 'sort': 'DESC' or 'ASC'
            # 'from': 'Datetime or Number',
            # 'till': 'Datetime or Number',
            # 'limit': 100,
            # 'offset': 0,
        }
        if symbol is not None:
            market = self.market(symbol)
            symbol = market['symbol']
            request['symbols'] = market['id']
        if since is not None:
            request['from'] = since
        if limit is not None:
            request['limit'] = limit
        response = self.publicGetPublicFuturesHistoryFunding(self.extend(request, params))
        #
        #    {
        #        "BTCUSDT_PERP": [
        #            {
        #                "timestamp": "2021-07-29T16:00:00.271Z",
        #                "funding_rate": "0.0001",
        #                "avg_premium_index": "0.000061858585213222",
        #                "next_funding_time": "2021-07-30T00:00:00.000Z",
        #                "interest_rate": "0.0001"
        #            },
        #            ...
        #        ],
        #        ...
        #    }
        #
        contracts = list(response.keys())
        rates = []
        for i in range(0, len(contracts)):
            marketId = contracts[i]
            market = self.safe_market(marketId)
            fundingRateData = response[marketId]
            for i in range(0, len(fundingRateData)):
                entry = fundingRateData[i]
                symbol = self.safe_symbol(market['symbol'])
                fundingRate = self.safe_number(entry, 'funding_rate')
                datetime = self.safe_string(entry, 'timestamp')
                rates.append({
                    'info': entry,
                    'symbol': symbol,
                    'fundingRate': fundingRate,
                    'timestamp': self.parse8601(datetime),
                    'datetime': datetime,
                })
        sorted = self.sort_by(rates, 'timestamp')
        return self.filter_by_symbol_since_limit(sorted, symbol, since, limit)

    def fetch_positions(self, symbols=None, params={}):
        """
        fetch all open positions
        :param [str]|None symbols: not used by hitbtc3 fetchPositions()
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :param str|None params['marginMode']: 'cross' or 'isolated' only 'isolated' is supported, defaults to spot-margin endpoint if self is set
        :param bool|None params['margin']: True for fetching spot-margin positions
        :returns [dict]: a list of `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        """
        self.load_markets()
        request = {}
        marketType = None
        marketType, params = self.handle_market_type_and_params('fetchPositions', None, params)
        method = self.get_supported_mapping(marketType, {
            'swap': 'privateGetFuturesAccount',
            'margin': 'privateGetMarginAccount',
        })
        marginMode, query = self.handle_margin_mode_and_params('fetchPositions', params)
        if marginMode is not None:
            method = 'privateGetMarginAccount'
        response = getattr(self, method)(self.extend(request, query))
        #
        #     [
        #         {
        #             "symbol": "ETHUSDT_PERP",
        #             "type": "isolated",
        #             "leverage": "10.00",
        #             "created_at": "2022-03-19T07:54:35.24Z",
        #             "updated_at": "2022-03-19T07:54:58.922Z",
        #             currencies": [
        #                 {
        #                     "code": "USDT",
        #                     "margin_balance": "7.478100643043",
        #                     "reserved_orders": "0",
        #                     "reserved_positions": "0.303530761300"
        #                 }
        #             ],
        #             "positions": [
        #                 {
        #                     "id": 2470568,
        #                     "symbol": "ETHUSDT_PERP",
        #                     "quantity": "0.001",
        #                     "price_entry": "2927.509",
        #                     "price_margin_call": "0",
        #                     "price_liquidation": "0",
        #                     "pnl": "0",
        #                     "created_at": "2022-03-19T07:54:35.24Z",
        #                     "updated_at": "2022-03-19T07:54:58.922Z"
        #                 }
        #             ]
        #         },
        #     ]
        #
        result = []
        for i in range(0, len(response)):
            result.append(self.parse_position(response[i]))
        return result

    def fetch_position(self, symbol, params={}):
        """
        fetch data on a single open contract trade position
        :param str symbol: unified market symbol of the market the position is held in, default is None
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :param str|None params['marginMode']: 'cross' or 'isolated' only 'isolated' is supported, defaults to spot-margin endpoint if self is set
        :param bool|None params['margin']: True for fetching a spot-margin position
        :returns dict: a `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        """
        self.load_markets()
        marketType = None
        marketType, params = self.handle_market_type_and_params('fetchPosition', None, params)
        method = self.get_supported_mapping(marketType, {
            'swap': 'privateGetFuturesAccountIsolatedSymbol',
            'margin': 'privateGetMarginAccountIsolatedSymbol',
        })
        marginMode, query = self.handle_margin_mode_and_params('fetchPosition', params)
        if marginMode is not None:
            method = 'privateGetMarginAccountIsolatedSymbol'
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = getattr(self, method)(self.extend(request, query))
        #
        #     [
        #         {
        #             "symbol": "ETHUSDT_PERP",
        #             "type": "isolated",
        #             "leverage": "10.00",
        #             "created_at": "2022-03-19T07:54:35.24Z",
        #             "updated_at": "2022-03-19T07:54:58.922Z",
        #             currencies": [
        #                 {
        #                     "code": "USDT",
        #                     "margin_balance": "7.478100643043",
        #                     "reserved_orders": "0",
        #                     "reserved_positions": "0.303530761300"
        #                 }
        #             ],
        #             "positions": [
        #                 {
        #                     "id": 2470568,
        #                     "symbol": "ETHUSDT_PERP",
        #                     "quantity": "0.001",
        #                     "price_entry": "2927.509",
        #                     "price_margin_call": "0",
        #                     "price_liquidation": "0",
        #                     "pnl": "0",
        #                     "created_at": "2022-03-19T07:54:35.24Z",
        #                     "updated_at": "2022-03-19T07:54:58.922Z"
        #                 }
        #             ]
        #         },
        #     ]
        #
        return self.parse_position(response, market)

    def parse_position(self, position, market=None):
        #
        #     [
        #         {
        #             "symbol": "ETHUSDT_PERP",
        #             "type": "isolated",
        #             "leverage": "10.00",
        #             "created_at": "2022-03-19T07:54:35.24Z",
        #             "updated_at": "2022-03-19T07:54:58.922Z",
        #             currencies": [
        #                 {
        #                     "code": "USDT",
        #                     "margin_balance": "7.478100643043",
        #                     "reserved_orders": "0",
        #                     "reserved_positions": "0.303530761300"
        #                 }
        #             ],
        #             "positions": [
        #                 {
        #                     "id": 2470568,
        #                     "symbol": "ETHUSDT_PERP",
        #                     "quantity": "0.001",
        #                     "price_entry": "2927.509",
        #                     "price_margin_call": "0",
        #                     "price_liquidation": "0",
        #                     "pnl": "0",
        #                     "created_at": "2022-03-19T07:54:35.24Z",
        #                     "updated_at": "2022-03-19T07:54:58.922Z"
        #                 }
        #             ]
        #         },
        #     ]
        #
        marginMode = self.safe_string(position, 'type')
        leverage = self.safe_number(position, 'leverage')
        datetime = self.safe_string(position, 'updated_at')
        positions = self.safe_value(position, 'positions', [])
        liquidationPrice = None
        entryPrice = None
        contracts = None
        for i in range(0, len(positions)):
            entry = positions[i]
            liquidationPrice = self.safe_number(entry, 'price_liquidation')
            entryPrice = self.safe_number(entry, 'price_entry')
            contracts = self.safe_number(entry, 'quantity')
        currencies = self.safe_value(position, 'currencies', [])
        collateral = None
        for i in range(0, len(currencies)):
            entry = currencies[i]
            collateral = self.safe_number(entry, 'margin_balance')
        marketId = self.safe_string(position, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        return {
            'info': position,
            'id': None,
            'symbol': symbol,
            'notional': None,
            'marginMode': marginMode,
            'marginType': marginMode,
            'liquidationPrice': liquidationPrice,
            'entryPrice': entryPrice,
            'unrealizedPnl': None,
            'percentage': None,
            'contracts': contracts,
            'contractSize': None,
            'markPrice': None,
            'side': None,
            'hedged': None,
            'timestamp': self.parse8601(datetime),
            'datetime': datetime,
            'maintenanceMargin': None,
            'maintenanceMarginPercentage': None,
            'collateral': collateral,
            'initialMargin': None,
            'initialMarginPercentage': None,
            'leverage': leverage,
            'marginRatio': None,
        }

    def fetch_funding_rate(self, symbol, params={}):
        """
        fetch the current funding rate
        :param str symbol: unified market symbol
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/en/latest/manual.html#funding-rate-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        if not market['swap']:
            raise BadSymbol(self.id + ' fetchFundingRate() supports swap contracts only')
        request = {}
        if symbol is not None:
            symbol = market['symbol']
            request['symbols'] = market['id']
        response = self.publicGetPublicFuturesInfo(self.extend(request, params))
        #
        #     {
        #         "BTCUSDT_PERP": {
        #             "contract_type": "perpetual",
        #             "mark_price": "42307.43",
        #             "index_price": "42303.27",
        #             "funding_rate": "0.0001",
        #             "open_interest": "30.9826",
        #             "next_funding_time": "2022-03-22T16:00:00.000Z",
        #             "indicative_funding_rate": "0.0001",
        #             "premium_index": "0",
        #             "avg_premium_index": "0.000029587712038098",
        #             "interest_rate": "0.0001",
        #             "timestamp": "2022-03-22T08:08:26.687Z"
        #         }
        #     }
        #
        data = self.safe_value(response, market['id'], {})
        return self.parse_funding_rate(data, market)

    def parse_funding_rate(self, contract, market=None):
        #
        #     {
        #         "contract_type": "perpetual",
        #         "mark_price": "42307.43",
        #         "index_price": "42303.27",
        #         "funding_rate": "0.0001",
        #         "open_interest": "30.9826",
        #         "next_funding_time": "2022-03-22T16:00:00.000Z",
        #         "indicative_funding_rate": "0.0001",
        #         "premium_index": "0",
        #         "avg_premium_index": "0.000029587712038098",
        #         "interest_rate": "0.0001",
        #         "timestamp": "2022-03-22T08:08:26.687Z"
        #     }
        #
        fundingDateTime = self.safe_string(contract, 'next_funding_time')
        datetime = self.safe_string(contract, 'timestamp')
        return {
            'info': contract,
            'symbol': self.safe_symbol(None, market),
            'markPrice': self.safe_number(contract, 'mark_price'),
            'indexPrice': self.safe_number(contract, 'index_price'),
            'interestRate': self.safe_number(contract, 'interest_rate'),
            'estimatedSettlePrice': None,
            'timestamp': self.parse8601(datetime),
            'datetime': datetime,
            'fundingRate': self.safe_number(contract, 'funding_rate'),
            'fundingTimestamp': self.parse8601(fundingDateTime),
            'fundingDatetime': fundingDateTime,
            'nextFundingRate': self.safe_number(contract, 'indicative_funding_rate'),
            'nextFundingTimestamp': None,
            'nextFundingDatetime': None,
            'previousFundingRate': None,
            'previousFundingTimestamp': None,
            'previousFundingDatetime': None,
        }

    def modify_margin_helper(self, symbol, amount, type, params={}):
        self.load_markets()
        market = self.market(symbol)
        leverage = self.safe_string(params, 'leverage')
        if market['type'] == 'swap':
            if leverage is None:
                raise ArgumentsRequired(self.id + ' modifyMarginHelper() requires a leverage parameter for swap markets')
        amount = self.amount_to_precision(symbol, amount)
        request = {
            'symbol': market['id'],  # swap and margin
            'margin_balance': amount,  # swap and margin
            # 'leverage': '10',  # swap only required
            # 'strict_validate': False,  # swap and margin
        }
        if leverage is not None:
            request['leverage'] = leverage
        marketType = None
        marketType, params = self.handle_market_type_and_params('modifyMarginHelper', None, params)
        method = self.get_supported_mapping(marketType, {
            'swap': 'privatePutFuturesAccountIsolatedSymbol',
            'margin': 'privatePutMarginAccountIsolatedSymbol',
        })
        marginMode, query = self.handle_margin_mode_and_params('modifyMarginHelper', params)
        if marginMode is not None:
            method = 'privatePutMarginAccountIsolatedSymbol'
        response = getattr(self, method)(self.extend(request, query))
        #
        #     {
        #         "symbol": "BTCUSDT_PERP",
        #         "type": "isolated",
        #         "leverage": "8.00",
        #         "created_at": "2022-03-30T23:34:27.161Z",
        #         "updated_at": "2022-03-30T23:34:27.161Z",
        #         "currencies": [
        #             {
        #                 "code": "USDT",
        #                 "margin_balance": "7.000000000000",
        #                 "reserved_orders": "0",
        #                 "reserved_positions": "0"
        #             }
        #         ],
        #         "positions": null
        #     }
        #
        return self.extend(self.parse_margin_modification(response, market), {
            'amount': self.parse_number(amount),
            'type': type,
        })

    def parse_margin_modification(self, data, market=None):
        currencies = self.safe_value(data, 'currencies', [])
        currencyInfo = self.safe_value(currencies, 0)
        return {
            'info': data,
            'type': None,
            'amount': None,
            'code': self.safe_string(currencyInfo, 'code'),
            'symbol': market['symbol'],
            'status': None,
        }

    def reduce_margin(self, symbol, amount, params={}):
        """
        remove margin from a position
        :param str symbol: unified market symbol
        :param float amount: the amount of margin to remove
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :param str|None params['marginMode']: 'cross' or 'isolated' only 'isolated' is supported, defaults to the spot-margin endpoint if self is set
        :param bool|None params['margin']: True for reducing spot-margin
        :returns dict: a `margin structure <https://docs.ccxt.com/en/latest/manual.html#reduce-margin-structure>`
        """
        if amount != 0:
            raise BadRequest(self.id + ' reduceMargin() on hitbtc3 requires the amount to be 0 and that will remove the entire margin amount')
        return self.modify_margin_helper(symbol, amount, 'reduce', params)

    def add_margin(self, symbol, amount, params={}):
        """
        add margin
        :param str symbol: unified market symbol
        :param float amount: amount of margin to add
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :param str|None params['marginMode']: 'cross' or 'isolated' only 'isolated' is supported, defaults to the spot-margin endpoint if self is set
        :param bool|None params['margin']: True for adding spot-margin
        :returns dict: a `margin structure <https://docs.ccxt.com/en/latest/manual.html#add-margin-structure>`
        """
        return self.modify_margin_helper(symbol, amount, 'add', params)

    def fetch_leverage(self, symbol, params={}):
        """
        fetch the set leverage for a market
        :param str symbol: unified market symbol
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :param str|None params['marginMode']: 'cross' or 'isolated' only 'isolated' is supported, defaults to the spot-margin endpoint if self is set
        :param bool|None params['margin']: True for fetching spot-margin leverage
        :returns dict: a `leverage structure <https://docs.ccxt.com/en/latest/manual.html#leverage-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        method = self.get_supported_mapping(market['type'], {
            'spot': 'privateGetMarginAccountIsolatedSymbol',
            'margin': 'privateGetMarginAccountIsolatedSymbol',
            'swap': 'privateGetFuturesAccountIsolatedSymbol',
        })
        marginMode, query = self.handle_margin_mode_and_params('modifyMarginHelper', params)
        if marginMode is not None:
            method = 'privateGetMarginAccountIsolatedSymbol'
        response = getattr(self, method)(self.extend(request, query))
        #
        #     {
        #         "symbol": "BTCUSDT",
        #         "type": "isolated",
        #         "leverage": "12.00",
        #         "created_at": "2022-03-29T22:31:29.067Z",
        #         "updated_at": "2022-03-30T00:00:00.125Z",
        #         "currencies": [
        #             {
        #                 "code": "USDT",
        #                 "margin_balance": "20.824360374174",
        #                 "reserved_orders": "0",
        #                 "reserved_positions": "0.973330435000"
        #             }
        #         ],
        #         "positions": [
        #             {
        #                 "id": 631301,
        #                 "symbol": "BTCUSDT",
        #                 "quantity": "0.00022",
        #                 "price_entry": "47425.57",
        #                 "price_margin_call": "",
        #                 "price_liquidation": "0",
        #                 "pnl": "0",
        #                 "created_at": "2022-03-29T22:31:29.067Z",
        #                 "updated_at": "2022-03-30T00:00:00.125Z"
        #             }
        #         ]
        #     }
        #
        return self.safe_number(response, 'leverage')

    def set_leverage(self, leverage, symbol=None, params={}):
        """
        set the level of leverage for a market
        :param float leverage: the rate of leverage
        :param str symbol: unified market symbol
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :returns dict: response from the exchange
        """
        self.load_markets()
        if symbol is None:
            raise ArgumentsRequired(self.id + ' setLeverage() requires a symbol argument')
        if params['margin_balance'] is None:
            raise ArgumentsRequired(self.id + ' setLeverage() requires a margin_balance parameter that will transfer margin to the specified trading pair')
        market = self.market(symbol)
        amount = self.safe_number(params, 'margin_balance')
        maxLeverage = self.safe_integer(market['limits']['leverage'], 'max', 50)
        if market['type'] != 'swap':
            raise BadSymbol(self.id + ' setLeverage() supports swap contracts only')
        if (leverage < 1) or (leverage > maxLeverage):
            raise BadRequest(self.id + ' setLeverage() leverage should be between 1 and ' + str(maxLeverage) + ' for ' + symbol)
        request = {
            'symbol': market['id'],
            'leverage': str(leverage),
            'margin_balance': self.amount_to_precision(symbol, amount),
            # 'strict_validate': False,
        }
        return self.privatePutFuturesAccountIsolatedSymbol(self.extend(request, params))

    def fetch_deposit_withdraw_fees(self, codes=None, params={}):
        """
        fetch deposit and withdraw fees
        see https://api.hitbtc.com/#currencies
        :param [str]|None codes: list of unified currency codes
        :param dict params: extra parameters specific to the hitbtc3 api endpoint
        :returns [dict]: a list of `fees structures <https://docs.ccxt.com/en/latest/manual.html#fee-structure>`
        """
        self.load_markets()
        response = self.publicGetPublicCurrency(params)
        #
        #     {
        #       "WEALTH": {
        #         "full_name": "ConnectWealth",
        #         "payin_enabled": False,
        #         "payout_enabled": False,
        #         "transfer_enabled": True,
        #         "precision_transfer": "0.001",
        #         "networks": [
        #           {
        #             "network": "ETH",
        #             "protocol": "ERC20",
        #             "default": True,
        #             "payin_enabled": False,
        #             "payout_enabled": False,
        #             "precision_payout": "0.001",
        #             "payout_fee": "0.016800000000",
        #             "payout_is_payment_id": False,
        #             "payin_payment_id": False,
        #             "payin_confirmations": "2"
        #           }
        #         ]
        #       }
        #     }
        #
        return self.parse_deposit_withdraw_fees(response, codes)

    def parse_deposit_withdraw_fee(self, fee, currency=None):
        #
        #    {
        #         "full_name": "ConnectWealth",
        #         "payin_enabled": False,
        #         "payout_enabled": False,
        #         "transfer_enabled": True,
        #         "precision_transfer": "0.001",
        #         "networks": [
        #           {
        #             "network": "ETH",
        #             "protocol": "ERC20",
        #             "default": True,
        #             "payin_enabled": False,
        #             "payout_enabled": False,
        #             "precision_payout": "0.001",
        #             "payout_fee": "0.016800000000",
        #             "payout_is_payment_id": False,
        #             "payin_payment_id": False,
        #             "payin_confirmations": "2"
        #           }
        #         ]
        #    }
        #
        networks = self.safe_value(fee, 'networks', [])
        result = self.deposit_withdraw_fee(fee)
        for j in range(0, len(networks)):
            networkEntry = networks[j]
            networkId = self.safe_string(networkEntry, 'network')
            networkCode = self.network_id_to_code(networkId)
            withdrawFee = self.safe_number(networkEntry, 'payout_fee')
            isDefault = self.safe_value(networkEntry, 'default')
            withdrawResult = {
                'fee': withdrawFee,
                'percentage': False if (withdrawFee is not None) else None,
            }
            if isDefault is True:
                result['withdraw'] = withdrawResult
            result['networks'][networkCode] = {
                'withdraw': withdrawResult,
                'deposit': {
                    'fee': None,
                    'percentage': None,
                },
            }
        return result

    def handle_margin_mode_and_params(self, methodName, params={}, defaultValue=None):
        """
         * @ignore
        marginMode specified by params["marginMode"], self.options["marginMode"], self.options["defaultMarginMode"], params["margin"] = True or self.options["defaultType"] = 'margin'
        :param dict params: extra parameters specific to the exchange api endpoint
        :returns [str|None, dict]: the marginMode in lowercase
        """
        defaultType = self.safe_string(self.options, 'defaultType')
        isMargin = self.safe_value(params, 'margin', False)
        marginMode = None
        marginMode, params = super(hitbtc3, self).handle_margin_mode_and_params(methodName, params, defaultValue)
        if marginMode is not None:
            if marginMode != 'isolated':
                raise NotSupported(self.id + ' only isolated margin is supported')
        else:
            if (defaultType == 'margin') or (isMargin is True):
                marginMode = 'isolated'
        return [marginMode, params]

    def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
        #
        #     {
        #       "error": {
        #         "code": 20001,
        #         "message": "Insufficient funds",
        #         "description": "Check that the funds are sufficient, given commissions"
        #       }
        #     }
        #
        #     {
        #       "error": {
        #         "code": "600",
        #         "message": "Action not allowed"
        #       }
        #     }
        #
        error = self.safe_value(response, 'error')
        errorCode = self.safe_string(error, 'code')
        if errorCode is not None:
            feedback = self.id + ' ' + body
            message = self.safe_string_2(error, 'message', 'description')
            self.throw_exactly_matched_exception(self.exceptions['exact'], errorCode, feedback)
            self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback)
            raise ExchangeError(feedback)

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        query = self.omit(params, self.extract_params(path))
        implodedPath = self.implode_params(path, params)
        url = self.urls['api'][api] + '/' + implodedPath
        getRequest = None
        keys = list(query.keys())
        queryLength = len(keys)
        headers = {
            'Content-Type': 'application/json',
        }
        if method == 'GET':
            if queryLength:
                getRequest = '?' + self.urlencode(query)
                url = url + getRequest
        else:
            body = self.json(params)
        if api == 'private':
            self.check_required_credentials()
            timestamp = str(self.nonce())
            payload = [method, '/api/3/' + implodedPath]
            if method == 'GET':
                if getRequest is not None:
                    payload.append(getRequest)
            else:
                payload.append(body)
            payload.append(timestamp)
            payloadString = ''.join(payload)
            signature = self.hmac(self.encode(payloadString), self.encode(self.secret), hashlib.sha256, 'hex')
            secondPayload = self.apiKey + ':' + signature + ':' + timestamp
            encoded = self.decode(self.string_to_base64(secondPayload))
            headers['Authorization'] = 'HS256 ' + encoded
        return {'url': url, 'method': method, 'body': body, 'headers': headers}
