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

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

from ccxt.async_support.base.exchange import Exchange
from ccxt.abstract.hashkey import ImplicitAPI
import hashlib
from ccxt.base.types import Account, Any, Balances, Bool, Currencies, Currency, DepositAddress, Int, LastPrice, LastPrices, LedgerEntry, Leverage, LeverageTier, LeverageTiers, Market, Num, Order, OrderBook, OrderRequest, OrderSide, OrderType, Position, Str, Strings, Ticker, Tickers, FundingRate, FundingRates, Trade, TradingFeeInterface, TradingFees, Transaction, TransferEntry
from typing import List
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import AccountNotEnabled
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 OperationRejected
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidAddress
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import OrderImmediatelyFillable
from ccxt.base.errors import OrderNotFillable
from ccxt.base.errors import DuplicateOrderId
from ccxt.base.errors import ContractUnavailable
from ccxt.base.errors import NotSupported
from ccxt.base.errors import OperationFailed
from ccxt.base.errors import DDoSProtection
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import InvalidNonce
from ccxt.base.errors import RequestTimeout
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class hashkey(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(hashkey, self).describe(), {
            'id': 'hashkey',
            'name': 'HashKey Global',
            'countries': ['BM'],  # Bermuda
            'rateLimit': 100,
            'version': 'v1',
            'certified': True,
            'pro': True,
            'has': {
                'CORS': None,
                'spot': True,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'addMargin': False,
                'borrowCrossMargin': False,
                'borrowIsolatedMargin': False,
                'borrowMargin': False,
                'cancelAllOrders': True,
                'cancelAllOrdersAfter': False,
                'cancelOrder': True,
                'cancelOrders': True,
                'cancelWithdraw': False,
                'closeAllPositions': False,
                'closePosition': False,
                'createConvertTrade': False,
                'createDepositAddress': False,
                'createMarketBuyOrderWithCost': True,
                'createMarketOrder': True,
                'createMarketOrderWithCost': False,
                'createMarketSellOrderWithCost': False,
                'createOrder': True,
                'createOrderWithTakeProfitAndStopLoss': False,
                'createReduceOnlyOrder': True,
                'createStopLimitOrder': True,
                'createStopLossOrder': False,
                'createStopMarketOrder': True,
                'createStopOrder': True,
                'createTakeProfitOrder': False,
                'createTrailingAmountOrder': False,
                'createTrailingPercentOrder': False,
                'createTriggerOrder': True,
                'fetchAccounts': True,
                'fetchAllGreeks': False,
                'fetchBalance': True,
                'fetchBorrowInterest': False,
                'fetchBorrowRate': False,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchBorrowRates': False,
                'fetchBorrowRatesPerSymbol': False,
                'fetchCanceledAndClosedOrders': True,
                'fetchCanceledOrders': True,
                'fetchClosedOrder': True,
                'fetchClosedOrders': False,
                'fetchConvertCurrencies': False,
                'fetchConvertQuote': False,
                'fetchConvertTrade': False,
                'fetchConvertTradeHistory': False,
                'fetchCrossBorrowRate': False,
                'fetchCrossBorrowRates': False,
                'fetchCurrencies': True,
                'fetchDepositAddress': True,
                'fetchDepositAddresses': False,
                'fetchDepositAddressesByNetwork': False,
                'fetchDeposits': True,
                'fetchDepositsWithdrawals': False,
                'fetchFundingHistory': False,
                'fetchFundingInterval': False,
                'fetchFundingIntervals': False,
                'fetchFundingRate': True,
                'fetchFundingRateHistory': True,
                'fetchFundingRates': True,
                'fetchGreeks': False,
                'fetchIndexOHLCV': False,
                'fetchIsolatedBorrowRate': False,
                'fetchIsolatedBorrowRates': False,
                'fetchIsolatedPositions': False,
                'fetchLedger': True,
                'fetchLeverage': True,
                'fetchLeverages': False,
                'fetchLeverageTiers': True,
                'fetchLiquidations': False,
                'fetchLongShortRatio': False,
                'fetchLongShortRatioHistory': False,
                'fetchMarginAdjustmentHistory': False,
                'fetchMarginMode': False,
                'fetchMarginModes': False,
                'fetchMarketLeverageTiers': 'emulated',
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMarkPrice': False,
                'fetchMarkPrices': False,
                'fetchMyLiquidations': False,
                'fetchMySettlementHistory': False,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenInterest': False,
                'fetchOpenInterestHistory': False,
                'fetchOpenInterests': False,
                'fetchOpenOrder': False,
                'fetchOpenOrders': True,
                'fetchOption': False,
                'fetchOptionChain': False,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrders': False,
                'fetchOrderTrades': False,
                'fetchPosition': False,
                'fetchPositionHistory': False,
                'fetchPositionMode': False,
                'fetchPositions': True,
                'fetchPositionsForSymbol': True,
                'fetchPositionsHistory': False,
                'fetchPositionsRisk': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchSettlementHistory': False,
                'fetchStatus': True,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTime': True,
                'fetchTrades': True,
                'fetchTradingFee': True,  # emulated for spot markets
                'fetchTradingFees': True,  # for spot markets only
                'fetchTransactions': False,
                'fetchTransfers': False,
                'fetchUnderlyingAssets': False,
                'fetchVolatilityHistory': False,
                'fetchWithdrawals': True,
                'reduceMargin': False,
                'repayCrossMargin': False,
                'repayIsolatedMargin': False,
                'sandbox': False,
                'setLeverage': True,
                'setMargin': False,
                'setMarginMode': False,
                'setPositionMode': False,
                'transfer': True,
                'withdraw': True,
            },
            'timeframes': {
                '1m': '1m',
                '3m': '3m',
                '5m': '5m',
                '15m': '15m',
                '30m': '30m',
                '1h': '1h',
                '2h': '2h',
                '4h': '4h',
                '6h': '6h',
                '8h': '8h',
                '12h': '12h',
                '1d': '1d',
                '1w': '1w',
                '1M': '1M',
            },
            'urls': {
                'logo': 'https://github.com/user-attachments/assets/6dd6127b-cc19-4a13-9b29-a98d81f80e98',
                'api': {
                    'public': 'https://api-glb.hashkey.com',
                    'private': 'https://api-glb.hashkey.com',
                },
                'test': {
                    'public': 'https://api-glb.sim.hashkeydev.com',
                    'private': 'https://api-glb.sim.hashkeydev.com',
                },
                'www': 'https://global.hashkey.com/',
                'doc': 'https://hashkeyglobal-apidoc.readme.io/',
                'fees': 'https://support.global.hashkey.com/hc/en-us/articles/13199900083612-HashKey-Global-Fee-Structure',
                'referral': 'https://global.hashkey.com/en-US/register/invite?invite_code=82FQUN',
            },
            'api': {
                'public': {
                    'get': {
                        'api/v1/exchangeInfo': 5,
                        'quote/v1/depth': 1,
                        'quote/v1/trades': 1,
                        'quote/v1/klines': 1,
                        'quote/v1/ticker/24hr': 1,
                        'quote/v1/ticker/price': 1,
                        'quote/v1/ticker/bookTicker': 1,  # not unified
                        'quote/v1/depth/merged': 1,
                        'quote/v1/markPrice': 1,
                        'quote/v1/index': 1,
                        'api/v1/futures/fundingRate': 1,
                        'api/v1/futures/historyFundingRate': 1,
                        'api/v1/ping': 1,
                        'api/v1/time': 1,
                    },
                },
                'private': {
                    'get': {
                        'api/v1/spot/order': 1,
                        'api/v1/spot/openOrders': 1,
                        'api/v1/spot/tradeOrders': 5,
                        'api/v1/futures/leverage': 1,
                        'api/v1/futures/order': 1,
                        'api/v1/futures/openOrders': 1,
                        'api/v1/futures/userTrades': 1,
                        'api/v1/futures/positions': 1,
                        'api/v1/futures/historyOrders': 1,
                        'api/v1/futures/balance': 1,
                        'api/v1/futures/liquidationAssignStatus': 1,
                        'api/v1/futures/riskLimit': 1,
                        'api/v1/futures/commissionRate': 1,
                        'api/v1/futures/getBestOrder': 1,
                        'api/v1/account/vipInfo': 1,
                        'api/v1/account': 1,
                        'api/v1/account/trades': 5,
                        'api/v1/account/type': 5,
                        'api/v1/account/checkApiKey': 1,
                        'api/v1/account/balanceFlow': 5,
                        'api/v1/spot/subAccount/openOrders': 1,
                        'api/v1/spot/subAccount/tradeOrders': 1,
                        'api/v1/subAccount/trades': 1,
                        'api/v1/futures/subAccount/openOrders': 1,
                        'api/v1/futures/subAccount/historyOrders': 1,
                        'api/v1/futures/subAccount/userTrades': 1,
                        'api/v1/account/deposit/address': 1,
                        'api/v1/account/depositOrders': 1,
                        'api/v1/account/withdrawOrders': 1,
                    },
                    'post': {
                        'api/v1/userDataStream': 1,
                        'api/v1/spot/orderTest': 1,
                        'api/v1/spot/order': 1,
                        'api/v1.1/spot/order': 1,
                        'api/v1/spot/batchOrders': 5,
                        'api/v1/futures/leverage': 1,
                        'api/v1/futures/order': 1,
                        'api/v1/futures/position/trading-stop': 3,
                        'api/v1/futures/batchOrders': 5,
                        'api/v1/account/assetTransfer': 1,
                        'api/v1/account/authAddress': 1,
                        'api/v1/account/withdraw': 1,
                    },
                    'put': {
                        'api/v1/userDataStream': 1,
                    },
                    'delete': {
                        'api/v1/spot/order': 1,
                        'api/v1/spot/openOrders': 5,
                        'api/v1/spot/cancelOrderByIds': 5,
                        'api/v1/futures/order': 1,
                        'api/v1/futures/batchOrders': 1,
                        'api/v1/futures/cancelOrderByIds': 1,
                        'api/v1/userDataStream': 1,
                    },
                },
            },
            'fees': {
                'trading': {
                    'spot': {
                        'tierBased': True,
                        'percentage': True,
                        'feeSide': 'get',
                        'maker': self.parse_number('0.0012'),
                        'taker': self.parse_number('0.0012'),
                        'tiers': {
                            'maker': [
                                [self.parse_number('0'), self.parse_number('0.0012')],
                                [self.parse_number('1000000'), self.parse_number('0.00080')],
                                [self.parse_number('5000000'), self.parse_number('0.00070')],
                                [self.parse_number('10000000'), self.parse_number('0.00060')],
                                [self.parse_number('50000000'), self.parse_number('0.00040')],
                                [self.parse_number('200000000'), self.parse_number('0.00030')],
                                [self.parse_number('400000000'), self.parse_number('0.00010')],
                                [self.parse_number('800000000'), self.parse_number('0.00')],
                            ],
                            'taker': [
                                [self.parse_number('0'), self.parse_number('0.0012')],
                                [self.parse_number('1000000'), self.parse_number('0.00090')],
                                [self.parse_number('5000000'), self.parse_number('0.00085')],
                                [self.parse_number('10000000'), self.parse_number('0.00075')],
                                [self.parse_number('50000000'), self.parse_number('0.00065')],
                                [self.parse_number('200000000'), self.parse_number('0.00045')],
                                [self.parse_number('400000000'), self.parse_number('0.00040')],
                                [self.parse_number('800000000'), self.parse_number('0.00035')],
                            ],
                        },
                    },
                    'swap': {
                        'tierBased': True,
                        'percentage': True,
                        'feeSide': 'get',
                        'maker': self.parse_number('0.00025'),
                        'taker': self.parse_number('0.00060'),
                        'tiers': {
                            'maker': [
                                [self.parse_number('0'), self.parse_number('0.00025')],
                                [self.parse_number('1000000'), self.parse_number('0.00016')],
                                [self.parse_number('5000000'), self.parse_number('0.00014')],
                                [self.parse_number('10000000'), self.parse_number('0.00012')],
                                [self.parse_number('50000000'), self.parse_number('0.000080')],
                                [self.parse_number('200000000'), self.parse_number('0.000060')],
                                [self.parse_number('400000000'), self.parse_number('0.000020')],
                                [self.parse_number('800000000'), self.parse_number('0.00')],
                            ],
                            'taker': [
                                [self.parse_number('0'), self.parse_number('0.00060')],
                                [self.parse_number('1000000'), self.parse_number('0.00050')],
                                [self.parse_number('5000000'), self.parse_number('0.00045')],
                                [self.parse_number('10000000'), self.parse_number('0.00040')],
                                [self.parse_number('50000000'), self.parse_number('0.00035')],
                                [self.parse_number('200000000'), self.parse_number('0.00030')],
                                [self.parse_number('400000000'), self.parse_number('0.00025')],
                                [self.parse_number('800000000'), self.parse_number('0.00020')],
                            ],
                        },
                    },
                },
            },
            'options': {
                'broker': '10000700011',
                'recvWindow': None,
                'sandboxMode': False,
                'networks': {
                    'BTC': 'BTC',
                    'ERC20': 'ETH',
                    'AVAX': 'AvalancheC',
                    'SOL': 'Solana',
                    'MATIC': 'Polygon',
                    'ATOM': 'Cosmos',
                    'DOT': 'Polkadot',
                    'LTC': 'LTC',
                    'OPTIMISM': 'Optimism',
                    'ARB': 'Arbitrum',
                    'DOGE': 'Dogecoin',
                    'TRC20': 'Tron',
                    'ZKSYNC': 'zkSync',
                    'TON': 'TON',
                    'KLAYTN': 'Klaytn',
                    'MERLINCHAIN': 'Merlin Chain',
                },
                'networksById': {
                    'BTC': 'BTC',
                    'Bitcoin': 'BTC',
                    'ETH': 'ERC20',
                    'ERC20': 'ERC20',
                    'AvalancheC': 'AVAX',
                    'AVAX C-Chain': 'AVAX',
                    'Solana': 'SOL',
                    'Cosmos': 'ATOM',
                    'Arbitrum': 'ARB',
                    'Polygon': 'MATIC',
                    'Optimism': 'OPTIMISM',
                    'Polkadot': 'DOT',
                    'LTC': 'LTC',
                    'Litecoin': 'LTC',
                    'Dogecoin': 'DOGE',
                    'Merlin Chain': 'MERLINCHAIN',
                    'zkSync': 'ZKSYNC',
                    'TRC20': 'TRC20',
                    'Tron': 'TRC20',
                    'TON': 'TON',
                    'BSC(BEP20)': 'BSC',
                    'Klaytn': 'KLAYTN',
                },
                'defaultNetwork': 'ERC20',
            },
            'features': {
                'default': {
                    'sandbox': True,
                    'createOrder': {
                        'marginMode': False,
                        'triggerPrice': False,
                        'triggerPriceType': None,
                        'triggerDirection': False,
                        'stopLossPrice': False,
                        'takeProfitPrice': False,
                        'attachedStopLossTakeProfit': None,
                        'timeInForce': {
                            'IOC': True,
                            'FOK': True,
                            'PO': True,
                            'GTD': False,
                        },
                        'hedged': False,
                        'trailing': False,
                        'leverage': False,
                        'marketBuyByCost': True,
                        'marketBuyRequiresPrice': True,  # todo fix
                        'selfTradePrevention': True,  # todo implement
                        'iceberg': False,
                    },
                    'createOrders': {
                        'max': 20,
                    },
                    'fetchMyTrades': {
                        'marginMode': False,
                        'limit': 1000,
                        'daysBack': 30,
                        'untilDays': 30,
                        'symbolRequired': False,
                    },
                    'fetchOrder': {
                        'marginMode': False,
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOpenOrders': {
                        'marginMode': False,
                        'limit': 1000,
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOrders': None,
                    'fetchClosedOrders': None,  # todo
                    'fetchOHLCV': {
                        'limit': 1000,
                    },
                },
                'spot': {
                    'extends': 'default',
                },
                'forDerivatives': {
                    'extends': 'default',
                    'createOrder': {
                        'triggerPrice': True,
                        'selfTradePrevention': True,
                    },
                    'fetchOpenOrders': {
                        'trigger': True,
                        'limit': 500,
                    },
                },
                'swap': {
                    'linear': {
                        'extends': 'forDerivatives',
                    },
                    'inverse': None,
                },
                'future': {
                    'linear': None,
                    'inverse': None,
                },
            },
            'commonCurrencies': {},
            'exceptions': {
                'exact': {
                    '0001': BadRequest,  # Required field '%s' missing or invalid.
                    '0002': AuthenticationError,  # Incorrect signature
                    '0003': RateLimitExceeded,  # Rate limit exceeded
                    '0102': AuthenticationError,  # Invalid APIKey
                    '0103': AuthenticationError,  # APIKey expired
                    '0104': PermissionDenied,  # The accountId defined is not permissible
                    '0201': ExchangeError,  # Instrument not found
                    '0202': PermissionDenied,  # Invalid IP
                    '0206': BadRequest,  # Unsupported order type
                    '0207': BadRequest,  # Invalid price
                    '0209': BadRequest,  # Invalid price precision
                    '0210': BadRequest,  # Price outside of allowed range
                    '0211': OrderNotFound,  # Order not found
                    '0401': InsufficientFunds,  # Insufficient asset
                    '0402': BadRequest,  # Invalid asset
                    '-1000': ExchangeError,  # An unknown error occurred while processing the request
                    '-1001': ExchangeError,  # Internal error
                    '-100010': BadSymbol,  # Invalid Symbols!
                    '-100012': BadSymbol,  # Parameter symbol [str] missing!
                    '-1002': AuthenticationError,  # Unauthorized operation
                    '-1004': BadRequest,  # Bad request
                    '-1005': PermissionDenied,  # No permission
                    '-1006': ExchangeError,  # Execution status unknown
                    '-1007': RequestTimeout,  # Timeout waiting for response from server
                    '-1014': InvalidOrder,  # Unsupported order combination
                    '-1015': InvalidOrder,  # Too many new orders
                    '-1020': OperationRejected,  # Unsupported operation
                    '-1021': InvalidNonce,  # Timestamp for self request is outside of the recvWindow
                    '-1024': BadRequest,  # Duplicate request
                    '-1101': ExchangeNotAvailable,  # Feature has been offline
                    '-1115': InvalidOrder,  # Invalid timeInForce
                    '-1117': InvalidOrder,  # Invalid order side
                    '-1123': InvalidOrder,  # Invalid client order id
                    '-1124': InvalidOrder,  # Invalid price
                    '-1126': InvalidOrder,  # Invalid quantity
                    '-1129': BadRequest,  # Invalid parameters, quantity and amount are not allowed to be sent at the same time.
                    '-1130': BadRequest,  # Illegal parameter '%s'
                    '-1132': BadRequest,  # Order price greater than the maximum
                    '-1133': BadRequest,  # Order price lower than the minimum
                    '-1135': BadRequest,  # Order quantity greater than the maximum
                    '-1136': BadRequest,  # Order quantity lower than the minimum
                    '-1138': InvalidOrder,  # Order has been partially cancelled
                    '-1137': InvalidOrder,  # Order quantity precision too large
                    '-1139': OrderImmediatelyFillable,  # Order has been filled
                    '-1140': InvalidOrder,  # Order amount lower than the minimum
                    '-1141': DuplicateOrderId,  # Duplicate order
                    '-1142': OrderNotFillable,  # Order has been cancelled
                    '-1143': OrderNotFound,  # Order not found on order book
                    '-1144': OperationRejected,  # Order has been locked
                    '-1145': NotSupported,  # Cancellation on self order type not supported
                    '-1146': RequestTimeout,  # Order creation timeout
                    '-1147': RequestTimeout,  # Order cancellation timeout
                    '-1148': InvalidOrder,  # Order amount precision too large
                    '-1149': OperationRejected,  # Order creation failed
                    '-1150': OperationFailed,  # Order cancellation failed
                    '-1151': OperationRejected,  # The trading pair is not open yet
                    '-1152': AccountNotEnabled,  # User does not exist
                    '-1153': InvalidOrder,  # Invalid price type
                    '-1154': InvalidOrder,  # Invalid position side
                    '-1155': OperationRejected,  # The trading pair is not available for api trading
                    '-1156': OperationFailed,  # Limit maker order creation failed
                    '-1157': OperationFailed,  # Modify futures margin failed
                    '-1158': OperationFailed,  # Reduce margin is forbidden
                    '-1159': AccountNotEnabled,  # Finance account already exists
                    '-1160': AccountNotEnabled,  # Account does not exist
                    '-1161': OperationFailed,  # Balance transfer failed
                    '-1162': ContractUnavailable,  # Unsupport contract address
                    '-1163': InvalidAddress,  # Illegal withdrawal address
                    '-1164': OperationFailed,  # Withdraw failed
                    '-1165': ArgumentsRequired,  # Withdrawal amount cannot be null
                    '-1166': OperationRejected,  # Withdrawal amount exceeds the daily limit
                    '-1167': BadRequest,  # Withdrawal amount less than the minimum
                    '-1168': BadRequest,  # Illegal withdrawal amount
                    '-1169': PermissionDenied,  # Withdraw not allowed
                    '-1170': PermissionDenied,  # Deposit not allowed
                    '-1171': PermissionDenied,  # Withdrawal address not in whitelist
                    '-1172': BadRequest,  # Invalid from account id
                    '-1173': BadRequest,  # Invalid to account i
                    '-1174': PermissionDenied,  # Transfer not allowed between the same account
                    '-1175': BadRequest,  # Invalid fiat deposit status
                    '-1176': BadRequest,  # Invalid fiat withdrawal status
                    '-1177': InvalidOrder,  # Invalid fiat order type
                    '-1178': AccountNotEnabled,  # Brokerage account does not exist
                    '-1179': AccountSuspended,  # Address owner is not True
                    '-1181': ExchangeError,  # System error
                    '-1193': OperationRejected,  # Order creation count exceeds the limit
                    '-1194': OperationRejected,  # Market order creation forbidden
                    '-1195': BadRequest,  # Market order long position cannot exceed %s above the market price
                    '-1196': BadRequest,  # Market order short position cannot be below %s of the market price
                    '-1200': BadRequest,  # Order buy quantity too small
                    '-1201': BadRequest,  # Order buy quantity too large
                    '-1202': BadRequest,  # Order sell quantity too small
                    '-1203': BadRequest,  # Order sell quantity too large
                    '-1204': BadRequest,  # From account must be a main account
                    '-1205': AccountNotEnabled,  # Account not authorized
                    '-1206': BadRequest,  # Order amount greater than the maximum
                    '-1207': BadRequest,  # The status of deposit is invalid
                    '-1208': BadRequest,  # The orderType of fiat is invalid
                    '-1209': BadRequest,  # The status of withdraw is invalid
                    '-2001': ExchangeNotAvailable,  # Platform is yet to open trading
                    '-2002': OperationFailed,  # The number of open orders exceeds the limit 300
                    '-2003': OperationFailed,  # Position size cannot meet target leverage
                    '-2004': OperationFailed,  # Adjust leverage fail
                    '-2005': RequestTimeout,  # Adjust leverage timeout
                    '-2010': OperationRejected,  # New order rejected
                    '-2011': OperationRejected,  # Order cancellation rejected
                    '-2016': OperationRejected,  # API key creation exceeds the limit
                    '-2017': OperationRejected,  # Open orders exceeds the limit of the trading pair
                    '-2018': OperationRejected,  # Trade user creation exceeds the limit
                    '-2019': PermissionDenied,  # Trader and omnibus user not allowed to login app
                    '-2020': PermissionDenied,  # Not allowed to trade self trading pair
                    '-2021': PermissionDenied,  # Not allowed to trade self trading pair
                    '-2022': OperationRejected,  # Order batch size exceeds the limit
                    '-2023': AuthenticationError,  # Need to pass KYC verification
                    '-2024': AccountNotEnabled,  # Fiat account does not exist
                    '-2025': AccountNotEnabled,  # Custody account not exist
                    '-2026': BadRequest,  # Invalid type
                    '-2027': OperationRejected,  # Exceed maximum time range of 30 days
                    '-2028': OperationRejected,  # The search is limited to data within the last one month
                    '-2029': OperationRejected,  # The search is limited to data within the last three months
                    '-2030': InsufficientFunds,  # Insufficient margin
                    '-2031': NotSupported,  # Leverage reduction is not supported in Isolated Margin Mode with open positions
                    '-2032': OperationRejected,  # After the transaction, your %s position will account for %s of the total position, which poses concentration risk. Do you want to continue with the transaction?
                    '-2033': OperationFailed,  # Order creation failed. Please verify if the order parameters comply with the trading rules
                    '-2034': InsufficientFunds,  # Trade account holding limit is zero
                    '-2035': OperationRejected,  # The sub account has been frozen and cannot transfer
                    '-2036': NotSupported,  # We do not support queries for records exceeding 30 days
                    '-2037': ExchangeError,  # Position and order data error
                    '-2038': InsufficientFunds,  # Insufficient margin
                    '-2039': NotSupported,  # Leverage reduction is not supported in Isolated Margin Mode with open positions
                    '-2040': ExchangeNotAvailable,  # There is a request being processed. Please try again later
                    '-2041': BadRequest,  # Token does not exist
                    '-2042': OperationRejected,  # You have passed the trade limit, please pay attention to the risks
                    '-2043': OperationRejected,  # Maximum allowed leverage reached, please lower your leverage
                    '-2044': BadRequest,  # This order price is unreasonable to exceed(or be lower than) the liquidation price
                    '-2045': BadRequest,  # Price too low, please order again!
                    '-2046': BadRequest,  # Price too high, please order again!
                    '-2048': BadRequest,  # Exceed the maximum number of conditional orders of %s
                    '-2049': BadRequest,  # Create stop order buy price too big
                    '-2050': BadRequest,  # Create stop order sell price too small
                    '-2051': OperationRejected,  # Create order rejected
                    '-2052': OperationRejected,  # Create stop profit-loss plan order reject
                    '-2053': OperationRejected,  # Position not enough
                    '-2054': BadRequest,  # Invalid long stop profit price
                    '-2055': BadRequest,  # Invalid long stop loss price
                    '-2056': BadRequest,  # Invalid short stop profit price
                    '-2057': BadRequest,  # Invalid short stop loss price
                    '-3117': PermissionDenied,  # Invalid permission
                    '-3143': PermissionDenied,  # According to KYC and risk assessment, your trading account has exceeded the limit.
                    '-3144': PermissionDenied,  # Currently, your trading account has exceeded its limit and is temporarily unable to perform transfers
                    '-3145': DDoSProtection,  # Please DO NOT submit request too frequently
                    '-4001': BadRequest,  # Invalid asset
                    '-4002': BadRequest,  # Withdrawal amount less than Minimum Withdrawal Amount
                    '-4003': InsufficientFunds,  # Insufficient Balance
                    '-4004': BadRequest,  # Invalid bank account number
                    '-4005': BadRequest,  # Assets are not listed
                    '-4006': AccountNotEnabled,  # KYC is not certified
                    '-4007': NotSupported,  # Withdrawal channels are not supported
                    '-4008': AccountNotEnabled,  # This currency does not support self customer type
                    '-4009': PermissionDenied,  # No withdrawal permission
                    '-4010': PermissionDenied,  # Withdrawals on the same day exceed the maximum limit for a single day
                    '-4011': ExchangeError,  # System error
                    '-4012': ExchangeError,  # Parameter error
                    '-4013': OperationFailed,  # Withdraw repeatly
                },
                'broad': {},
            },
            'precisionMode': TICK_SIZE,
        })

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

        https://hashkeyglobal-apidoc.readme.io/reference/check-server-time

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        """
        response = await self.publicGetApiV1Time(params)
        #
        #     {
        #         "serverTime": 1721661553214
        #     }
        #
        return self.safe_integer(response, 'serverTime')

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

        https://hashkeyglobal-apidoc.readme.io/reference/test-connectivity

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
        """
        response = await self.publicGetApiV1Ping(params)
        #
        # {}
        #
        return {
            'status': 'ok',
            'updated': None,
            'eta': None,
            'url': None,
            'info': response,
        }

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

        https://hashkeyglobal-apidoc.readme.io/reference/exchangeinfo

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.symbol]: the id of the market to fetch
        :returns dict[]: an array of objects representing market data
        """
        request: dict = {}
        response = await self.publicGetApiV1ExchangeInfo(self.extend(request, params))
        #
        #     {
        #         "timezone": "UTC",
        #         "serverTime": "1721661653952",
        #         "brokerFilters": [],
        #         "symbols": [
        #             {
        #                 "symbol": "BTCUSDT",
        #                 "symbolName": "BTCUSDT",
        #                 "status": "TRADING",
        #                 "baseAsset": "BTC",
        #                 "baseAssetName": "BTC",
        #                 "baseAssetPrecision": "0.00001",
        #                 "quoteAsset": "USDT",
        #                 "quoteAssetName": "USDT",
        #                 "quotePrecision": "0.0000001",
        #                 "retailAllowed": True,
        #                 "piAllowed": True,
        #                 "corporateAllowed": True,
        #                 "omnibusAllowed": True,
        #                 "icebergAllowed": False,
        #                 "isAggregate": False,
        #                 "allowMargin": False,
        #                 "filters": [
        #                     {
        #                         "minPrice": "0.01",
        #                         "maxPrice": "100000.00000000",
        #                         "tickSize": "0.01",
        #                         "filterType": "PRICE_FILTER"
        #                     },
        #                     {
        #                         "minQty": "0.00001",
        #                         "maxQty": "8",
        #                         "stepSize": "0.00001",
        #                         "marketOrderMinQty": "0.00001",
        #                         "marketOrderMaxQty": "4",
        #                         "filterType": "LOT_SIZE"
        #                     },
        #                     {
        #                         "minNotional": "1",
        #                         "filterType": "MIN_NOTIONAL"
        #                     },
        #                     {
        #                         "minAmount": "1",
        #                         "maxAmount": "400000",
        #                         "minBuyPrice": "0",
        #                         "marketOrderMinAmount": "1",
        #                         "marketOrderMaxAmount": "200000",
        #                         "filterType": "TRADE_AMOUNT"
        #                     },
        #                     {
        #                         "maxSellPrice": "0",
        #                         "buyPriceUpRate": "0.1",
        #                         "sellPriceDownRate": "0.1",
        #                         "filterType": "LIMIT_TRADING"
        #                     },
        #                     {
        #                         "buyPriceUpRate": "0.1",
        #                         "sellPriceDownRate": "0.1",
        #                         "filterType": "MARKET_TRADING"
        #                     },
        #                     {
        #                         "noAllowMarketStartTime": "1710485700000",
        #                         "noAllowMarketEndTime": "1710486000000",
        #                         "limitOrderStartTime": "0",
        #                         "limitOrderEndTime": "0",
        #                         "limitMinPrice": "0",
        #                         "limitMaxPrice": "0",
        #                         "filterType": "OPEN_QUOTE"
        #                     }
        #                 ]
        #             }
        #         ],
        #         "options": [],
        #         "contracts": [
        #             {
        #                 "filters": [
        #                     {
        #                         "minPrice": "0.1",
        #                         "maxPrice": "100000.00000000",
        #                         "tickSize": "0.1",
        #                         "filterType": "PRICE_FILTER"
        #                     },
        #                     {
        #                         "minQty": "0.001",
        #                         "maxQty": "10",
        #                         "stepSize": "0.001",
        #                         "marketOrderMinQty": "0",
        #                         "marketOrderMaxQty": "0",
        #                         "filterType": "LOT_SIZE"
        #                     },
        #                     {
        #                         "minNotional": "0",
        #                         "filterType": "MIN_NOTIONAL"
        #                     },
        #                     {
        #                         "maxSellPrice": "999999",
        #                         "buyPriceUpRate": "0.05",
        #                         "sellPriceDownRate": "0.05",
        #                         "maxEntrustNum": 200,
        #                         "maxConditionNum": 200,
        #                         "filterType": "LIMIT_TRADING"
        #                     },
        #                     {
        #                         "buyPriceUpRate": "0.05",
        #                         "sellPriceDownRate": "0.05",
        #                         "filterType": "MARKET_TRADING"
        #                     },
        #                     {
        #                         "noAllowMarketStartTime": "0",
        #                         "noAllowMarketEndTime": "0",
        #                         "limitOrderStartTime": "0",
        #                         "limitOrderEndTime": "0",
        #                         "limitMinPrice": "0",
        #                         "limitMaxPrice": "0",
        #                         "filterType": "OPEN_QUOTE"
        #                     }
        #                 ],
        #                 "exchangeId": "301",
        #                 "symbol": "BTCUSDT-PERPETUAL",
        #                 "symbolName": "BTCUSDT-PERPETUAL",
        #                 "status": "TRADING",
        #                 "baseAsset": "BTCUSDT-PERPETUAL",
        #                 "baseAssetPrecision": "0.001",
        #                 "quoteAsset": "USDT",
        #                 "quoteAssetPrecision": "0.1",
        #                 "icebergAllowed": False,
        #                 "inverse": False,
        #                 "index": "USDT",
        #                 "marginToken": "USDT",
        #                 "marginPrecision": "0.0001",
        #                 "contractMultiplier": "0.001",
        #                 "underlying": "BTC",
        #                 "riskLimits": [
        #                     {
        #                         "riskLimitId": "200000722",
        #                         "quantity": "1000.00",
        #                         "initialMargin": "0.10",
        #                         "maintMargin": "0.005",
        #                         "isWhite": False
        #                     },
        #                     {
        #                         "riskLimitId": "200000723",
        #                         "quantity": "2000.00",
        #                         "initialMargin": "0.10",
        #                         "maintMargin": "0.01",
        #                         "isWhite": False
        #                     }
        #                 ]
        #             }
        #         ],
        #         "coins": [
        #            {
        #                 "orgId": "9001",
        #                 "coinId": "BTC",
        #                 "coinName": "BTC",
        #                 "coinFullName": "Bitcoin",
        #                 "allowWithdraw": True,
        #                 "allowDeposit": True,
        #                 "tokenType": "CHAIN_TOKEN",
        #                 "chainTypes": [
        #                     {
        #                         "chainType": "Bitcoin",
        #                         "withdrawFee": "0",
        #                         "minWithdrawQuantity": "0.002",
        #                         "maxWithdrawQuantity": "0",
        #                         "minDepositQuantity": "0.0005",
        #                         "allowDeposit": True,
        #                         "allowWithdraw": True
        #                     }
        #                 ]
        #             }
        #         ]
        #     }
        #
        spotMarkets = self.safe_list(response, 'symbols', [])
        swapMarkets = self.safe_list(response, 'contracts', [])
        markets = self.array_concat(spotMarkets, swapMarkets)
        if self.is_empty(markets):
            markets = [response]  # if user provides params.symbol the exchange returns a single object insted of list of objects
        return self.parse_markets(markets)

    def parse_market(self, market: dict) -> Market:
        # spot
        #     {
        #         "symbol": "BTCUSDT",
        #         "symbolName": "BTCUSDT",
        #         "status": "TRADING",
        #         "baseAsset": "BTC",
        #         "baseAssetName": "BTC",
        #         "baseAssetPrecision": "0.00001",
        #         "quoteAsset": "USDT",
        #         "quoteAssetName": "USDT",
        #         "quotePrecision": "0.0000001",
        #         "retailAllowed": True,
        #         "piAllowed": True,
        #         "corporateAllowed": True,
        #         "omnibusAllowed": True,
        #         "icebergAllowed": False,
        #         "isAggregate": False,
        #         "allowMargin": False,
        #         "filters": [
        #             {
        #                 "minPrice": "0.01",
        #                 "maxPrice": "100000.00000000",
        #                 "tickSize": "0.01",
        #                 "filterType": "PRICE_FILTER"
        #             },
        #             {
        #                 "minQty": "0.00001",
        #                 "maxQty": "8",
        #                 "stepSize": "0.00001",
        #                 "marketOrderMinQty": "0.00001",
        #                 "marketOrderMaxQty": "4",
        #                 "filterType": "LOT_SIZE"
        #             },
        #             {
        #                 "minNotional": "1",
        #                 "filterType": "MIN_NOTIONAL"
        #             },
        #             {
        #                 "minAmount": "1",
        #                 "maxAmount": "400000",
        #                 "minBuyPrice": "0",
        #                 "marketOrderMinAmount": "1",
        #                 "marketOrderMaxAmount": "200000",
        #                 "filterType": "TRADE_AMOUNT"
        #             },
        #             {
        #                 "maxSellPrice": "0",
        #                 "buyPriceUpRate": "0.1",
        #                 "sellPriceDownRate": "0.1",
        #                 "filterType": "LIMIT_TRADING"
        #             },
        #             {
        #                 "buyPriceUpRate": "0.1",
        #                 "sellPriceDownRate": "0.1",
        #                 "filterType": "MARKET_TRADING"
        #             },
        #             {
        #                 "noAllowMarketStartTime": "1710485700000",
        #                 "noAllowMarketEndTime": "1710486000000",
        #                 "limitOrderStartTime": "0",
        #                 "limitOrderEndTime": "0",
        #                 "limitMinPrice": "0",
        #                 "limitMaxPrice": "0",
        #                 "filterType": "OPEN_QUOTE"
        #             }
        #         ]
        #     }
        #
        # swap
        #     {
        #         "filters": [
        #             {
        #                 "minPrice": "0.1",
        #                 "maxPrice": "100000.00000000",
        #                 "tickSize": "0.1",
        #                 "filterType": "PRICE_FILTER"
        #             },
        #             {
        #                 "minQty": "0.001",
        #                 "maxQty": "10",
        #                 "stepSize": "0.001",
        #                 "marketOrderMinQty": "0",
        #                 "marketOrderMaxQty": "0",
        #                 "filterType": "LOT_SIZE"
        #             },
        #             {
        #                 "minNotional": "0",
        #                 "filterType": "MIN_NOTIONAL"
        #             },
        #             {
        #                 "maxSellPrice": "999999",
        #                 "buyPriceUpRate": "0.05",
        #                 "sellPriceDownRate": "0.05",
        #                 "maxEntrustNum": 200,
        #                 "maxConditionNum": 200,
        #                 "filterType": "LIMIT_TRADING"
        #             },
        #             {
        #                 "buyPriceUpRate": "0.05",
        #                 "sellPriceDownRate": "0.05",
        #                 "filterType": "MARKET_TRADING"
        #             },
        #             {
        #                 "noAllowMarketStartTime": "0",
        #                 "noAllowMarketEndTime": "0",
        #                 "limitOrderStartTime": "0",
        #                 "limitOrderEndTime": "0",
        #                 "limitMinPrice": "0",
        #                 "limitMaxPrice": "0",
        #                 "filterType": "OPEN_QUOTE"
        #             }
        #         ],
        #         "exchangeId": "301",
        #         "symbol": "BTCUSDT-PERPETUAL",
        #         "symbolName": "BTCUSDT-PERPETUAL",
        #         "status": "TRADING",
        #         "baseAsset": "BTCUSDT-PERPETUAL",
        #         "baseAssetPrecision": "0.001",
        #         "quoteAsset": "USDT",
        #         "quoteAssetPrecision": "0.1",
        #         "icebergAllowed": False,
        #         "inverse": False,
        #         "index": "USDT",
        #         "marginToken": "USDT",
        #         "marginPrecision": "0.0001",
        #         "contractMultiplier": "0.001",
        #         "underlying": "BTC",
        #         "riskLimits": [
        #             {
        #                 "riskLimitId": "200000722",
        #                 "quantity": "1000.00",
        #                 "initialMargin": "0.10",
        #                 "maintMargin": "0.005",
        #                 "isWhite": False
        #             },
        #             {
        #                 "riskLimitId": "200000723",
        #                 "quantity": "2000.00",
        #                 "initialMargin": "0.10",
        #                 "maintMargin": "0.01",
        #                 "isWhite": False
        #             }
        #         ]
        #     }
        #
        marketId = self.safe_string(market, 'symbol')
        quoteId = self.safe_string(market, 'quoteAsset')
        quote = self.safe_currency_code(quoteId)
        settleId = self.safe_string(market, 'marginToken')
        settle = self.safe_currency_code(settleId)
        baseId = self.safe_string(market, 'baseAsset')
        marketType = 'spot'
        isSpot = True
        isSwap = False
        suffix = ''
        parts = marketId.split('-')
        secondPart = self.safe_string(parts, 1)
        if secondPart == 'PERPETUAL':
            marketType = 'swap'
            isSpot = False
            isSwap = True
            baseId = self.safe_string(market, 'underlying')
            suffix += ':' + settleId
        base = self.safe_currency_code(baseId)
        symbol = base + '/' + quote + suffix
        status = self.safe_string(market, 'status')
        active = status == 'TRADING'
        isLinear: Bool = None
        subType = None
        isInverse = self.safe_bool(market, 'inverse')
        if isInverse is not None:
            if isInverse:
                isLinear = False
                subType = 'inverse'
            else:
                isLinear = True
                subType = 'linear'
        filtersList = self.safe_list(market, 'filters', [])
        filters = self.index_by(filtersList, 'filterType')
        priceFilter = self.safe_dict(filters, 'PRICE_FILTER', {})
        amountFilter = self.safe_dict(filters, 'LOT_SIZE', {})
        costFilter = self.safe_dict(filters, 'MIN_NOTIONAL', {})
        minCostString = self.omit_zero(self.safe_string(costFilter, 'min_notional'))
        contractSizeString = self.safe_string(market, 'contractMultiplier')
        amountPrecisionString = self.safe_string(amountFilter, 'stepSize')
        amountMinLimitString = self.safe_string(amountFilter, 'minQty')
        amountMaxLimitString = self.safe_string(amountFilter, 'maxQty')
        minLeverage: Int = None
        maxLeverage: Int = None
        if isSwap:
            amountPrecisionString = Precise.string_div(amountPrecisionString, contractSizeString)
            amountMinLimitString = Precise.string_div(amountMinLimitString, contractSizeString)
            amountMaxLimitString = Precise.string_div(amountMaxLimitString, contractSizeString)
            riskLimits = self.safe_list(market, 'riskLimits')
            if riskLimits is not None:
                first = self.safe_dict(riskLimits, 0)
                arrayLength = len(riskLimits)
                last = self.safe_dict(riskLimits, arrayLength - 1)
                minInitialMargin = self.safe_string(first, 'initialMargin')
                maxInitialMargin = self.safe_string(last, 'initialMargin')
                if Precise.string_gt(minInitialMargin, maxInitialMargin):
                    minInitialMargin, maxInitialMargin = [maxInitialMargin, minInitialMargin]
                minLeverage = self.parse_to_int(Precise.string_div('1', maxInitialMargin))
                maxLeverage = self.parse_to_int(Precise.string_div('1', minInitialMargin))
        tradingFees = self.safe_dict(self.fees, 'trading')
        fees = self.safe_dict(tradingFees, 'spot') if isSpot else self.safe_dict(tradingFees, 'swap')
        return self.safe_market_structure({
            'id': marketId,
            'symbol': symbol,
            'base': base,
            'quote': quote,
            'baseId': baseId,
            'quoteId': quoteId,
            'active': active,
            'type': marketType,
            'subType': subType,
            'spot': isSpot,
            'margin': self.safe_bool(market, 'allowMargin'),
            'swap': isSwap,
            'future': False,
            'option': False,
            'contract': isSwap,
            'settle': settle,
            'settleId': settleId,
            'contractSize': self.parse_number(contractSizeString),
            'linear': isLinear,
            'inverse': isInverse,
            'taker': self.safe_number(fees, 'taker'),
            'maker': self.safe_number(fees, 'maker'),
            'percentage': self.safe_bool(fees, 'percentage'),
            'tierBased': self.safe_bool(fees, 'tierBased'),
            'feeSide': self.safe_string(fees, 'feeSide'),
            'expiry': None,
            'expiryDatetime': None,
            'strike': None,
            'optionType': None,
            'precision': {
                'amount': self.parse_number(amountPrecisionString),
                'price': self.safe_number(priceFilter, 'tickSize'),
            },
            'limits': {
                'amount': {
                    'min': self.parse_number(amountMinLimitString),
                    'max': self.parse_number(amountMaxLimitString),
                },
                'price': {
                    'min': self.safe_number(priceFilter, 'minPrice'),
                    'max': self.safe_number(priceFilter, 'maxPrice'),
                },
                'leverage': {
                    'min': minLeverage,
                    'max': maxLeverage,
                },
                'cost': {
                    'min': self.parse_number(minCostString),
                    'max': None,
                },
            },
            'created': None,
            'info': market,
        })

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

        https://hashkeyglobal-apidoc.readme.io/reference/exchangeinfo

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        """
        response = await self.publicGetApiV1ExchangeInfo(params)
        coins = self.safe_list(response, 'coins')
        #
        #     {
        #         ...
        #         "coins": [
        #             {
        #                 "orgId": "9001",
        #                 "coinId": "BTC",
        #                 "coinName": "BTC",
        #                 "coinFullName": "Bitcoin",
        #                 "allowWithdraw": True,
        #                 "allowDeposit": True,
        #                 "tokenType": "CHAIN_TOKEN",
        #                 "chainTypes": [
        #                     {
        #                         "chainType": "Bitcoin",
        #                         "withdrawFee": "0",
        #                         "minWithdrawQuantity": "0.002",
        #                         "maxWithdrawQuantity": "0",
        #                         "minDepositQuantity": "0.0005",
        #                         "allowDeposit": True,
        #                         "allowWithdraw": True
        #                     }
        #                 ]
        #             }
        #         ]
        #     }
        #
        result: dict = {}
        for i in range(0, len(coins)):
            currecy = coins[i]
            currencyId = self.safe_string(currecy, 'coinId')
            code = self.safe_currency_code(currencyId)
            networks = self.safe_list(currecy, 'chainTypes')
            parsedNetworks: dict = {}
            for j in range(0, len(networks)):
                network = networks[j]
                networkId = self.safe_string(network, 'chainType')
                networkCode = self.network_code_to_id(networkId)
                parsedNetworks[networkCode] = {
                    'id': networkId,
                    'network': networkCode,
                    'limits': {
                        'withdraw': {
                            'min': self.safe_number(network, 'minWithdrawQuantity'),
                            'max': self.parse_number(self.omit_zero(self.safe_string(network, 'maxWithdrawQuantity'))),
                        },
                        'deposit': {
                            'min': self.safe_number(network, 'minDepositQuantity'),
                            'max': None,
                        },
                    },
                    'active': None,
                    'deposit': self.safe_bool(network, 'allowDeposit'),
                    'withdraw': self.safe_bool(network, 'allowWithdraw'),
                    'fee': self.safe_number(network, 'withdrawFee'),
                    'precision': None,
                    'info': network,
                }
            rawType = self.safe_string(currecy, 'tokenType')
            type = 'fiat' if (rawType == 'REAL_MONEY') else 'crypto'
            result[code] = self.safe_currency_structure({
                'id': currencyId,
                'code': code,
                'precision': None,
                'type': type,
                'name': self.safe_string(currecy, 'coinFullName'),
                'active': None,
                'deposit': self.safe_bool(currecy, 'allowDeposit'),
                'withdraw': self.safe_bool(currecy, 'allowWithdraw'),
                'fee': None,
                'limits': {
                    'deposit': {
                        'min': None,
                        'max': None,
                    },
                    'withdraw': {
                        'min': None,
                        'max': None,
                    },
                },
                'networks': parsedNetworks,
                'info': currecy,
            })
        return result

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

        https://hashkeyglobal-apidoc.readme.io/reference/get-order-book

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return(maximum value is 200)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit
        response = await self.publicGetQuoteV1Depth(self.extend(request, params))
        #
        #     {
        #         "t": 1721681436393,
        #         "b": [
        #             ["67902.49", "0.00112"],
        #             ["67901.08", "0.01014"]
        #             ...
        #         ],
        #         "a": [
        #             ["67905.99", "0.87134"],
        #             ["67906", "0.57361"]
        #             ...
        #         ]
        #     }
        #
        timestamp = self.safe_integer(response, 't')
        return self.parse_order_book(response, symbol, timestamp, 'b', 'a')

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

        https://hashkeyglobal-apidoc.readme.io/reference/get-recent-trade-list

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch(maximum value is 100)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit
        response = await self.publicGetQuoteV1Trades(self.extend(request, params))
        #
        #     [
        #         {
        #             "t": 1721682745779,
        #             "p": "67835.99",
        #             "q": "0.00017",
        #             "ibm": True
        #         },
        #         ...
        #     ]
        #
        return self.parse_trades(response, market, since, limit)

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

        https://hashkeyglobal-apidoc.readme.io/reference/get-account-trade-list
        https://hashkeyglobal-apidoc.readme.io/reference/query-futures-trades
        https://hashkeyglobal-apidoc.readme.io/reference/get-sub-account-user

        :param str symbol: *is mandatory for swap markets* unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum amount of trades to fetch(default 200, max 500)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.type]: 'spot' or 'swap' - the type of the market to fetch trades for(default 'spot')
        :param int [params.until]: the latest time in ms to fetch trades for, only supports the last 30 days timeframe
        :param str [params.fromId]: srarting trade id
        :param str [params.toId]: ending trade id
        :param str [params.clientOrderId]: *spot markets only* filter trades by orderId
        :param str [params.accountId]: account id to fetch the orders from
        :returns Trade[]: a list of `trade structures <https://github.com/ccxt/ccxt/wiki/Manual#trade-structure>`
        """
        methodName = 'fetchMyTrades'
        await self.load_markets()
        request: dict = {}
        market: Market = None
        if symbol is not None:
            market = self.market(symbol)
        marketType = 'spot'
        marketType, params = self.handle_market_type_and_params(methodName, market, params)
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            request['limit'] = limit
        until: Int = None
        until, params = self.handle_option_and_params(params, methodName, 'until')
        if until is not None:
            request['endTime'] = until
        accountId: Str = None
        accountId, params = self.handle_option_and_params(params, methodName, 'accountId')
        response = None
        if marketType == 'spot':
            if market is not None:
                request['symbol'] = market['id']
            if accountId is not None:
                request['accountId'] = accountId
            response = await self.privateGetApiV1AccountTrades(self.extend(request, params))
            #
            #     [
            #         {
            #             "id": "1739352552862964736",
            #             "clientOrderId": "1722082982086472",
            #             "ticketId": "1739352552795029504",
            #             "symbol": "ETHUSDT",
            #             "symbolName": "ETHUSDT",
            #             "orderId": "1739352552762301440",
            #             "matchOrderId": "0",
            #             "price": "3289.96",
            #             "qty": "0.001",
            #             "commission": "0.0000012",
            #             "commissionAsset": "ETH",
            #             "time": "1722082982097",
            #             "isBuyer": True,
            #             "isMaker": False,
            #             "fee": {
            #                 "feeCoinId": "ETH",
            #                 "feeCoinName": "ETH",
            #                 "fee": "0.0000012"
            #             },
            #             "feeCoinId": "ETH",
            #             "feeAmount": "0.0000012",
            #             "makerRebate": "0"
            #         },
            #         ...
            #     ]
            #
        elif marketType == 'swap':
            if symbol is None:
                raise ArgumentsRequired(self.id + ' ' + methodName + '() requires a symbol argument for swap markets')
            request['symbol'] = market['id']
            if accountId is not None:
                request['subAccountId'] = accountId
                response = await self.privateGetApiV1FuturesSubAccountUserTrades(self.extend(request, params))
            else:
                response = await self.privateGetApiV1FuturesUserTrades(self.extend(request, params))
                #
                #     [
                #         {
                #             "time": "1722429951648",
                #             "tradeId": "1742263144691139328",
                #             "orderId": "1742263144028363776",
                #             "symbol": "ETHUSDT-PERPETUAL",
                #             "price": "3327.54",
                #             "quantity": "4",
                #             "commissionAsset": "USDT",
                #             "commission": "0.00798609",
                #             "makerRebate": "0",
                #             "type": "LIMIT",
                #             "side": "BUY_OPEN",
                #             "realizedPnl": "0",
                #             "isMarker": False
                #         }
                #     ]
                #
        else:
            raise NotSupported(self.id + ' ' + methodName + '() is not supported for ' + marketType + ' type of markets')
        return self.parse_trades(response, market, since, limit)

    def parse_trade(self, trade: dict, market: Market = None) -> Trade:
        #
        # fetchTrades
        #
        #     {
        #         "t": 1721682745779,
        #         "p": "67835.99",
        #         "q": "0.00017",
        #         "ibm": True
        #     }
        #
        # fetchMyTrades spot
        #
        #     {
        #         "id": "1739352552862964736",
        #         "clientOrderId": "1722082982086472",
        #         "ticketId": "1739352552795029504",
        #         "symbol": "ETHUSDT",
        #         "symbolName": "ETHUSDT",
        #         "orderId": "1739352552762301440",
        #         "matchOrderId": "0",
        #         "price": "3289.96",
        #         "qty": "0.001",
        #         "commission": "0.0000012",
        #         "commissionAsset": "ETH",
        #         "time": "1722082982097",
        #         "isBuyer": True,
        #         "isMaker": False,
        #         "fee": {
        #             "feeCoinId": "ETH",
        #             "feeCoinName": "ETH",
        #             "fee": "0.0000012"
        #         },
        #         "feeCoinId": "ETH",
        #         "feeAmount": "0.0000012",
        #         "makerRebate": "0"
        #     }
        #
        # fetchMyTrades swap
        #     {
        #         "time": "1722429951648",
        #         "tradeId": "1742263144691139328",
        #         "orderId": "1742263144028363776",
        #         "symbol": "ETHUSDT-PERPETUAL",
        #         "price": "3327.54",
        #         "quantity": "4",
        #         "commissionAsset": "USDT",
        #         "commission": "0.00798609",
        #         "makerRebate": "0",
        #         "type": "LIMIT",
        #         "side": "BUY_OPEN",
        #         "realizedPnl": "0",
        #         "isMarker": False
        #     }
        timestamp = self.safe_integer_2(trade, 't', 'time')
        marketId = self.safe_string(trade, 'symbol')
        market = self.safe_market(marketId, market)
        side = self.safe_string_lower(trade, 'side')  # swap trades have side param
        if side is not None:
            side = self.safe_string(side.split('_'), 0)
        isBuyer = self.safe_bool(trade, 'isBuyer')
        if isBuyer is not None:
            side = 'buy' if isBuyer else 'sell'
        takerOrMaker = None
        isMaker = self.safe_bool_n(trade, ['isMaker', 'isMarker'])
        if isMaker is not None:
            takerOrMaker = 'maker' if isMaker else 'taker'
        isBuyerMaker = self.safe_bool(trade, 'ibm')
        # if public trade
        if isBuyerMaker is not None:
            takerOrMaker = 'taker'
            side = 'sell' if isBuyerMaker else 'buy'
        feeCost = self.safe_string(trade, 'commission')
        feeCurrncyId = self.safe_string(trade, 'commissionAsset')
        feeInfo = self.safe_dict(trade, 'fee')
        fee = None
        if feeInfo is not None:
            feeCost = self.safe_string(feeInfo, 'fee')
            feeCurrncyId = self.safe_string(feeInfo, 'feeCoinId')
        if feeCost is not None:
            fee = {
                'cost': self.parse_number(feeCost),
                'currency': self.safe_currency_code(feeCurrncyId),
            }
        return self.safe_trade({
            'id': self.safe_string_2(trade, 'id', 'tradeId'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': market['symbol'],
            'side': side,
            'price': self.safe_string_2(trade, 'p', 'price'),
            'amount': self.safe_string_n(trade, ['q', 'qty', 'quantity']),
            'cost': None,
            'takerOrMaker': takerOrMaker,
            'type': None,
            'order': self.safe_string(trade, 'orderId'),
            'fee': fee,
            'info': trade,
        }, market)

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

        https://hashkeyglobal-apidoc.readme.io/reference/get-kline

        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest candle to fetch
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        methodName = 'fetchOHLCV'
        await self.load_markets()
        paginate = False
        paginate, params = self.handle_option_and_params(params, methodName, 'paginate')
        if paginate:
            return await self.fetch_paginated_call_deterministic('fetchOHLCV', symbol, since, limit, timeframe, params, 1000)
        market = self.market(symbol)
        timeframe = self.safe_string(self.timeframes, timeframe, timeframe)
        request: dict = {
            'symbol': market['id'],
            'interval': timeframe,
        }
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            request['limit'] = limit
        until: Int = None
        until, params = self.handle_option_and_params(params, methodName, 'until')
        if until is not None:
            request['endTime'] = until
        response = await self.publicGetQuoteV1Klines(self.extend(request, params))
        #
        #     [
        #         [
        #             1721684280000,
        #             "67832.49",
        #             "67862.5",
        #             "67832.49",
        #             "67861.44",
        #             "0.01122",0,
        #             "761.2763533",68,
        #             "0.00561",
        #             "380.640643"
        #         ],
        #         ...
        #     ]
        #
        return self.parse_ohlcvs(response, market, timeframe, since, limit)

    def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
        #
        #     [
        #         1721684280000,
        #         "67832.49",
        #         "67862.5",
        #         "67832.49",
        #         "67861.44",
        #         "0.01122",0,
        #         "761.2763533",68,
        #         "0.00561",
        #         "380.640643"
        #     ]
        #
        return [
            self.safe_integer(ohlcv, 0),
            self.safe_number(ohlcv, 1),
            self.safe_number(ohlcv, 2),
            self.safe_number(ohlcv, 3),
            self.safe_number(ohlcv, 4),
            self.safe_number(ohlcv, 5),
        ]

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

        https://hashkeyglobal-apidoc.readme.io/reference/get-24hr-ticker-price-change

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = await self.publicGetQuoteV1Ticker24hr(self.extend(request, params))
        #
        #     [
        #         {
        #             "t": 1721685896846,
        #             "s": "BTCUSDT-PERPETUAL",
        #             "c": "67756.7",
        #             "h": "68479.9",
        #             "l": "66594.3",
        #             "o": "68279.7",
        #             "b": "67756.6",
        #             "a": "67756.7",
        #             "v": "1604722",
        #             "qv": "108827258.7761"
        #         }
        #     ]
        #
        ticker = self.safe_dict(response, 0, {})
        return self.parse_ticker(ticker, market)

    async def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
        """
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://hashkeyglobal-apidoc.readme.io/reference/get-24hr-ticker-price-change

        :param str[] [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 exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        await self.load_markets()
        symbols = self.market_symbols(symbols)
        response = await self.publicGetQuoteV1Ticker24hr(params)
        return self.parse_tickers(response, symbols)

    def parse_ticker(self, ticker, market: Market = None) -> Ticker:
        #
        #     {
        #         "t": 1721685896846,
        #         "s": "BTCUSDT-PERPETUAL",
        #         "c": "67756.7",
        #         "h": "68479.9",
        #         "l": "66594.3",
        #         "o": "68279.7",
        #         "b": "67756.6",
        #         "a": "67756.7",
        #         "v": "1604722",
        #         "qv": "108827258.7761"
        #     }
        #
        timestamp = self.safe_integer(ticker, 't')
        marketId = self.safe_string(ticker, 's')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        last = self.safe_string(ticker, 'c')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': self.safe_string(ticker, 'h'),
            'low': self.safe_string(ticker, 'l'),
            'bid': self.safe_string(ticker, 'b'),
            'bidVolume': None,
            'ask': self.safe_string(ticker, 'a'),
            'askVolume': None,
            'vwap': None,
            'open': self.safe_string(ticker, 'o'),
            'close': last,
            'last': last,
            'previousClose': None,
            'change': None,
            'percentage': None,
            'average': None,
            'baseVolume': self.safe_string(ticker, 'v'),
            'quoteVolume': self.safe_string(ticker, 'qv'),
            'info': ticker,
        }, market)

    async def fetch_last_prices(self, symbols: Strings = None, params={}) -> LastPrices:
        """
        fetches the last price for multiple markets

        https://hashkeyglobal-apidoc.readme.io/reference/get-symbol-price-ticker

        :param str[] [symbols]: unified symbols of the markets to fetch the last prices
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.symbol]: the id of the market to fetch last price for
        :returns dict: a dictionary of lastprices structures
        """
        await self.load_markets()
        symbols = self.market_symbols(symbols)
        request: dict = {}
        response = await self.publicGetQuoteV1TickerPrice(self.extend(request, params))
        #
        #     [
        #         {
        #             "s": "BTCUSDT-PERPETUAL",
        #             "p": "64871"
        #         },
        #         ...
        #     ]
        #
        return self.parse_last_prices(response, symbols)

    def parse_last_price(self, entry, market: Market = None) -> LastPrice:
        marketId = self.safe_string(entry, 's')
        market = self.safe_market(marketId, market)
        return {
            'symbol': market['symbol'],
            'timestamp': None,
            'datetime': None,
            'price': self.safe_number(entry, 'p'),
            'side': None,
            'info': entry,
        }

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

        https://hashkeyglobal-apidoc.readme.io/reference/get-account-information

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.accountId]: account ID, for Master Key only
        :param str [params.type]: 'spot' or 'swap' - the type of the market to fetch balance for(default 'spot')
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        """
        await self.load_markets()
        request: dict = {}
        methodName = 'fetchBalance'
        marketType = 'spot'
        marketType, params = self.handle_market_type_and_params(methodName, None, params, marketType)
        if marketType == 'swap':
            response = await self.privateGetApiV1FuturesBalance(params)
            #
            #     [
            #         {
            #             "balance": "30.63364672",
            #             "availableBalance": "28.85635534",
            #             "positionMargin": "4.3421",
            #             "orderMargin": "0",
            #             "asset": "USDT",
            #             "crossUnRealizedPnl": "2.5649"
            #         }
            #     ]
            #
            balance = self.safe_dict(response, 0, {})
            return self.parse_swap_balance(balance)
        elif marketType == 'spot':
            response = await self.privateGetApiV1Account(self.extend(request, params))
            #
            #     {
            #         "balances": [
            #             {
            #                 "asset":"USDT",
            #                 "assetId":"USDT",
            #                 "assetName":"USDT",
            #                 "total":"40",
            #                 "free":"40",
            #                 "locked":"0"
            #             },
            #             ...
            #         ],
            #         "userId": "1732885739572845312"
            #     }
            #
            return self.parse_balance(response)
        else:
            raise NotSupported(self.id + ' ' + methodName + '() is not supported for ' + marketType + ' type of markets')

    def parse_balance(self, balance) -> Balances:
        #
        #     {
        #         "balances": [
        #             {
        #                 "asset":"USDT",
        #                 "assetId":"USDT",
        #                 "assetName":"USDT",
        #                 "total":"40",
        #                 "free":"40",
        #                 "locked":"0"
        #             },
        #             ...
        #         ],
        #         "userId": "1732885739572845312"
        #     }
        #
        result: dict = {
            'info': balance,
        }
        balances = self.safe_list(balance, 'balances', [])
        for i in range(0, len(balances)):
            balanceEntry = balances[i]
            currencyId = self.safe_string(balanceEntry, 'asset')
            code = self.safe_currency_code(currencyId)
            account = self.account()
            account['total'] = self.safe_string(balanceEntry, 'total')
            account['free'] = self.safe_string(balanceEntry, 'free')
            account['used'] = self.safe_string(balanceEntry, 'locked')
            result[code] = account
        return self.safe_balance(result)

    def parse_swap_balance(self, balance) -> Balances:
        #
        #     {
        #         "balance": "30.63364672",
        #         "availableBalance": "28.85635534",
        #         "positionMargin": "4.3421",
        #         "orderMargin": "0",
        #         "asset": "USDT",
        #         "crossUnRealizedPnl": "2.5649"
        #     }
        #
        currencyId = self.safe_string(balance, 'asset')
        code = self.safe_currency_code(currencyId)
        account = self.account()
        account['total'] = self.safe_string(balance, 'balance')
        positionMargin = self.safe_string(balance, 'positionMargin')
        orderMargin = self.safe_string(balance, 'orderMargin')
        account['used'] = Precise.string_add(positionMargin, orderMargin)
        result: dict = {
            'info': balance,
        }
        result[code] = account
        return self.safe_balance(result)

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

        https://hashkeyglobal-apidoc.readme.io/reference/get-deposit-address

        :param str code: unified currency code(default is 'USDT')
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.network]: network for fetch deposit address(default is 'ETH')
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        """
        await self.load_markets()
        currency = self.currency(code)
        request: dict = {
            'coin': currency['id'],
        }
        networkCode: Str = None
        networkCode, params = self.handle_network_code_and_params(params)
        if networkCode is None:
            networkCode = self.default_network_code(code)
        request['chainType'] = self.network_code_to_id(networkCode, code)
        response = await self.privateGetApiV1AccountDepositAddress(self.extend(request, params))
        #
        #     {
        #         "canDeposit": True,
        #         "address": "0x61AAd7F763e2C7fF1CC996918740F67f9dC8BF4e",
        #         "addressExt": "",
        #         "minQuantity": "1",
        #         "needAddressTag": False,
        #         "requiredConfirmTimes": 64,
        #         "canWithdrawConfirmTimes": 64,
        #         "coinType": "ERC20_TOKEN"
        #     }
        #
        depositAddress = self.parse_deposit_address(response, currency)
        depositAddress['network'] = networkCode
        return depositAddress

    def parse_deposit_address(self, depositAddress, currency: Currency = None) -> DepositAddress:
        #
        #     {
        #         "canDeposit": True,
        #         "address": "0x61AAd7F763e2C7fF1CC996918740F67f9dC8BF4e",
        #         "addressExt": "",
        #         "minQuantity": "1",
        #         "needAddressTag": False,
        #         "requiredConfirmTimes": 64,
        #         "canWithdrawConfirmTimes": 64,
        #         "coinType": "ERC20_TOKEN"
        #     }
        #
        address = self.safe_string(depositAddress, 'address')
        self.check_address(address)
        tag = self.safe_string(depositAddress, 'addressExt')
        if tag == '':
            tag = None
        return {
            'info': depositAddress,
            'currency': currency['code'],
            'network': None,
            'address': address,
            'tag': tag,
        }

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

        https://hashkeyglobal-apidoc.readme.io/reference/get-deposit-history

        :param str code: unified currency code of the currency transferred
        :param int [since]: the earliest time in ms to fetch transfers for(default 24 hours ago)
        :param int [limit]: the maximum number of transfer structures to retrieve(default 50, max 200)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch transfers for(default time now)
        :param int [params.fromId]: starting ID(To be released)
        :returns dict[]: a list of `transfer structures <https://docs.ccxt.com/#/?id=transfer-structure>`
        """
        methodName = 'fetchDeposits'
        await self.load_markets()
        request: dict = {}
        currency: Currency = None
        if code is not None:
            currency = self.currency(code)
            request['coin'] = currency['id']
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            request['limit'] = limit
        until: Int = None
        until, params = self.handle_option_and_params(params, methodName, 'until')
        if until is not None:
            request['endTime'] = until
        response = await self.privateGetApiV1AccountDepositOrders(self.extend(request, params))
        #
        #     [
        #         {
        #             "time": "1721641082163",
        #             "coin": "TRXUSDT",
        #             "coinName": "TRXUSDT",
        #             "address": "TBA6CypYJizwA9XdC7Ubgc5F1bxrQ7SqPt",
        #             "quantity": "86.00000000000000000000",
        #             "status": 4,
        #             "statusCode": "4",
        #             "txId": "0970c14da4d7412295fa7b21c03a08da319e746a0d59ef14462a74183d118da4"
        #         }
        #     ]
        #
        return self.parse_transactions(response, currency, since, limit, {'type': 'deposit'})

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

        https://hashkeyglobal-apidoc.readme.io/reference/withdrawal-records

        :param str code: unified currency code of the currency transferred
        :param int [since]: the earliest time in ms to fetch transfers for(default 24 hours ago)
        :param int [limit]: the maximum number of transfer structures to retrieve(default 50, max 200)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch transfers for(default time now)
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        methodName = 'fetchWithdrawals'
        await self.load_markets()
        request: dict = {}
        currency: Currency = None
        if code is not None:
            currency = self.currency(code)
            request['coin'] = currency['id']
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            request['limit'] = limit
        until: Int = None
        until, params = self.handle_option_and_params(params, methodName, 'until')
        if until is not None:
            request['endTime'] = until
        response = await self.privateGetApiV1AccountWithdrawOrders(self.extend(request, params))
        #
        #     [
        #         {
        #             "time": "1723545505366",
        #             "id": "W611267400947572736",
        #             "coin": "USDT",
        #             "coinId": "USDT",
        #             "coinName": "USDT",
        #             "address": "TQbkBMnWnJNGTAUpFS4kvv4NRLzUAnGAes",
        #             "quantity": "2.00000000",
        #             "arriveQuantity": "2.00000000",
        #             "txId": "f83f94e7d2e81fbec98c66c25d6615872cc2d426145629b6cf22e5e0a0753715",
        #             "addressUrl": "TQbkBMnWnJNGTAUpFS4kvv4NRLzUAnGAes",
        #             "feeCoinId": "USDT",
        #             "feeCoinName": "USDT",
        #             "fee": "1.00000000",
        #             "remark": "",
        #             "platform": ""
        #         }
        #     ]
        #
        return self.parse_transactions(response, currency, since, limit, {'type': 'withdrawal'})

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

        https://hashkeyglobal-apidoc.readme.io/reference/withdraw

        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.network]: network for withdraw
        :param str [params.clientOrderId]: client order id
        :param str [params.platform]: the platform to withdraw to(hashkey, HashKey HK)
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        tag, params = self.handle_withdraw_tag_and_params(tag, params)
        await self.load_markets()
        currency = self.currency(code)
        request: dict = {
            'coin': currency['id'],
            'address': address,
            'quantity': amount,
        }
        if tag is not None:
            request['addressExt'] = tag
        networkCode: Str = None
        networkCode, params = self.handle_network_code_and_params(params)
        if networkCode is not None:
            request['chainType'] = self.network_code_to_id(networkCode)
        response = await self.privatePostApiV1AccountWithdraw(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #         "id": "0",
        #         "orderId": "W611267400947572736",
        #         "accountId": "1732885739589466115"
        #     }
        #
        return self.parse_transaction(response, currency)

    def parse_transaction(self, transaction, currency: Currency = None) -> Transaction:
        #
        #  fetchDeposits
        #     {
        #         "time": "1721641082163",
        #         "coin": "TRXUSDT",  # todo how to parse it?
        #         "coinName": "TRXUSDT",
        #         "address": "TBA6CypYJizwA9XdC7Ubgc5F1bxrQ7SqPt",
        #         "quantity": "86.00000000000000000000",
        #         "status": 4,
        #         "statusCode": "4",
        #         "txId": "0970c14da4d7412295fa7b21c03a08da319e746a0d59ef14462a74183d118da4"
        #     }
        #
        # fetchWithdrawals
        #     {
        #         "time": "1723545505366",
        #         "id": "W611267400947572736",
        #         "coin": "USDT",
        #         "coinId": "USDT",
        #         "coinName": "USDT",
        #         "address": "TQbkBMnWnJNGTAUpFS4kvv4NRLzUAnGAes",
        #         "quantity": "2.00000000",
        #         "arriveQuantity": "2.00000000",
        #         "txId": "f83f94e7d2e81fbec98c66c25d6615872cc2d426145629b6cf22e5e0a0753715",
        #         "addressUrl": "TQbkBMnWnJNGTAUpFS4kvv4NRLzUAnGAes",
        #         "feeCoinId": "USDT",
        #         "feeCoinName": "USDT",
        #         "fee": "1.00000000",
        #         "remark": "",
        #         "platform": ""
        #     }
        #
        # withdraw
        #     {
        #         "success": True,
        #         "id": "0",
        #         "orderId": "W611267400947572736",
        #         "accountId": "1732885739589466115"
        #     }
        #
        id = self.safe_string_2(transaction, 'id', 'orderId')
        address = self.safe_string(transaction, 'address')
        status = self.safe_string(transaction, 'status')  # for fetchDeposits
        if status is None:
            success = self.safe_bool(transaction, 'success', False)  # for withdraw
            if success:
                status = 'ok'
            else:
                addressUrl = self.safe_string(transaction, 'addressUrl')  # for fetchWithdrawals
                if addressUrl is not None:
                    status = 'ok'
        txid = self.safe_string(transaction, 'txId')
        coin = self.safe_string(transaction, 'coin')
        code = self.safe_currency_code(coin, currency)
        timestamp = self.safe_integer(transaction, 'time')
        amount = self.safe_number(transaction, 'quantity')
        feeCost = self.safe_number(transaction, 'fee')
        fee = None
        if feeCost is not None:
            fee = {
                'cost': feeCost,
                'currency': code,
            }
        return {
            'info': transaction,
            'id': id,
            'txid': txid,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'network': None,
            'address': address,
            'addressTo': None,
            'addressFrom': None,
            'tag': None,
            'tagTo': None,
            'tagFrom': None,
            'type': None,
            'amount': amount,
            'currency': code,
            'status': self.parse_transaction_status(status),
            'updated': None,
            'internal': None,
            'comment': None,
            'fee': fee,
        }

    def parse_transaction_status(self, status):
        statuses: dict = {
            '1': 'pending',
            '2': 'pending',
            '3': 'failed',
            '4': 'ok',
            '5': 'pending',
            '6': 'ok',
            '7': 'failed',
            '8': 'cancelled',
            '9': 'failed',
            '10': 'failed',
            'successful': 'ok',
            'success': 'ok',
        }
        return self.safe_string(statuses, status, status)

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

        https://hashkeyglobal-apidoc.readme.io/reference/new-account-transfer

        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account id to transfer from
        :param str toAccount: account id to transfer to
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.clientOrderId]: a unique id for the transfer
        :param str [params.remark]: a note for the transfer
        :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        """
        await self.load_markets()
        currency = self.currency(code)
        request: dict = {
            'coin': currency['id'],
            'quantity': self.currency_to_precision(code, amount),
            'fromAccountId': fromAccount,
            'toAccountId': toAccount,
        }
        response = await self.privatePostApiV1AccountAssetTransfer(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #         "timestamp": 1722260230773,
        #         "clientOrderId": "",
        #         "orderId": "1740839420695806720"
        #     }
        #
        return self.parse_transfer(response, currency)

    def parse_transfer(self, transfer, currency: Currency = None):
        timestamp = self.safe_integer(transfer, 'timestamp')
        currencyId = self.safe_string(currency, 'id')
        status: Str = None
        success = self.safe_bool(transfer, 'success', False)
        if success:
            status = 'ok'
        return {
            'id': self.safe_string(transfer, 'orderId'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'currency': self.safe_currency_code(currencyId, currency),
            'amount': None,
            'fromAccount': None,
            'toAccount': None,
            'status': status,
            'info': transfer,
        }

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

        https://hashkeyglobal-apidoc.readme.io/reference/query-sub-account

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `account structures <https://docs.ccxt.com/#/?id=account-structure>` indexed by the account type
        """
        await self.load_markets()
        response = await self.privateGetApiV1AccountType(params)
        #
        #     [
        #         {
        #             "accountId": "1732885739589466112",
        #             "accountLabel": "Main Trading Account",
        #             "accountType": 1,
        #             "accountIndex": 0
        #         },
        #         ...
        #     ]
        #
        return self.parse_accounts(response, params)

    def parse_account(self, account):
        accountLabel = self.safe_string(account, 'accountLabel')
        label = ''
        if accountLabel == 'Main Trading Account' or accountLabel == 'Main Future Account':
            label = 'main'
        elif accountLabel == 'Sub Main Trading Account' or accountLabel == 'Sub Main Future Account':
            label = 'sub'
        accountType = self.parse_account_type(self.safe_string(account, 'accountType'))
        type = label + ' ' + accountType
        return {
            'id': self.safe_string(account, 'accountId'),
            'type': type,
            'code': None,
            'info': account,
        }

    def parse_account_type(self, type):
        types: dict = {
            '1': 'spot account',
            '3': 'swap account',
            '5': 'custody account',
            '6': 'fiat account',
        }
        return self.safe_string(types, type, type)

    def encode_account_type(self, type):
        types = {
            'spot': '1',
            'swap': '3',
            'custody': '5',
        }
        return self.safe_integer(types, type, type)

    def encode_flow_type(self, type):
        types = {
            'trade': '1',
            'fee': '3',
            'transfer': '51',
            'deposit': '900',
            'withdraw': '904',
        }
        return self.safe_integer(types, type, type)

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

        https://hashkeyglobal-apidoc.readme.io/reference/get-account-transaction-list

        :param str [code]: unified currency code, default is None(not used)
        :param int [since]: timestamp in ms of the earliest ledger entry, default is None
        :param int [limit]: max number of ledger entries to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch entries for
        :param int [params.flowType]: trade, fee, transfer, deposit, withdrawal
        :param int [params.accountType]: spot, swap, custody
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
        """
        methodName = 'fetchLedger'
        if since is None:
            raise ArgumentsRequired(self.id + ' ' + methodName + '() requires a since argument')
        until: Int = None
        until, params = self.handle_option_and_params(params, methodName, 'until')
        if until is None:
            raise ArgumentsRequired(self.id + ' ' + methodName + '() requires an until argument')
        await self.load_markets()
        currency = self.currency(code)
        request = {}
        request['startTime'] = since
        if limit is not None:
            request['limit'] = limit
        request['endTime'] = until
        flowType = None
        flowType, params = self.handle_option_and_params(params, methodName, 'flowType')
        if flowType is not None:
            request['flowType'] = self.encode_flow_type(flowType)
        accountType = None
        accountType, params = self.handle_option_and_params(params, methodName, 'accountType')
        if accountType is not None:
            request['accountType'] = self.encode_account_type(accountType)
        response = await self.privateGetApiV1AccountBalanceFlow(self.extend(request, params))
        #
        #     [
        #         {
        #             "id": "1740844413612065537",
        #             "accountId": "1732885739589466112",
        #             "coin": "USDT",
        #             "coinId": "USDT",
        #             "coinName": "USDT",
        #             "flowTypeValue": 51,
        #             "flowType": "USER_ACCOUNT_TRANSFER",
        #             "flowName": "",
        #             "change": "-1",
        #             "total": "8.015680088",
        #             "created": "1722260825765"
        #         },
        #         ...
        #     ]
        #
        return self.parse_ledger(response, currency, since, limit)

    def parse_ledger_entry_type(self, type):
        types: dict = {
            '1': 'trade',  # transfer
            '2': 'fee',  # trade
            '51': 'transfer',
            '900': 'deposit',
            '904': 'withdraw',
        }
        return self.safe_string(types, type, type)

    def parse_ledger_entry(self, item: dict, currency: Currency = None) -> LedgerEntry:
        #
        #     {
        #         "id": "1740844413612065537",
        #         "accountId": "1732885739589466112",
        #         "coin": "USDT",
        #         "coinId": "USDT",
        #         "coinName": "USDT",
        #         "flowTypeValue": 51,
        #         "flowType": "USER_ACCOUNT_TRANSFER",
        #         "flowName": "",
        #         "change": "-1",
        #         "total": "8.015680088",
        #         "created": "1722260825765"
        #     }
        #
        id = self.safe_string(item, 'id')
        account = self.safe_string(item, 'accountId')
        timestamp = self.safe_integer(item, 'created')
        type = self.parse_ledger_entry_type(self.safe_string(item, 'flowTypeValue'))
        currencyId = self.safe_string(item, 'coin')
        code = self.safe_currency_code(currencyId, currency)
        currency = self.safe_currency(currencyId, currency)
        amountString = self.safe_string(item, 'change')
        amount = self.parse_number(amountString)
        direction = 'in'
        if amountString.find('-') >= 0:
            direction = 'out'
        afterString = self.safe_string(item, 'total')
        after = self.parse_number(afterString)
        status = 'ok'
        return self.safe_ledger_entry({
            'info': item,
            'id': id,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'account': account,
            'direction': direction,
            'referenceId': None,
            'referenceAccount': None,
            'type': type,
            'currency': code,
            'symbol': None,
            'amount': amount,
            'before': None,
            'after': after,
            'status': status,
            'fee': None,
        }, currency)

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

        https://hashkeyglobal-apidoc.readme.io/reference/test-new-order
        https://hashkeyglobal-apidoc.readme.io/reference/create-order
        https://hashkeyglobal-apidoc.readme.io/reference/create-new-futures-order

        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit' or 'LIMIT_MAKER' for spot, 'market' or 'limit' or 'STOP' for swap
        :param str side: 'buy' or 'sell'
        :param float amount: how much of you want to trade in units of the base currency
        :param float [price]: the price that the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.cost]: *spot market buy only* the quote quantity that can be used alternative for the amount
        :param boolean [params.test]: *spot markets only* whether to use the test endpoint or not, default is False
        :param bool [params.postOnly]: if True, the order will only be posted to the order book and not executed immediately
        :param str [params.timeInForce]: "GTC" or "IOC" or "PO" for spot, 'GTC' or 'FOK' or 'IOC' or 'LIMIT_MAKER' or 'PO' for swap
        :param str [params.clientOrderId]: a unique id for the order - is mandatory for swap
        :param float [params.triggerPrice]: *swap markets only* The price at which a trigger order is triggered at
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        if market['spot']:
            return await self.create_spot_order(symbol, type, side, amount, price, params)
        elif market['swap']:
            return await self.create_swap_order(symbol, type, side, amount, price, params)
        else:
            raise NotSupported(self.id + ' createOrder() is not supported for ' + market['type'] + ' type of markets')

    async def create_market_buy_order_with_cost(self, symbol: str, cost: float, params={}) -> Order:
        """
        create a market buy order by providing the symbol and cost
        :param str symbol: unified symbol of the market to create an order in
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        if not market['spot']:
            raise NotSupported(self.id + ' createMarketBuyOrderWithCost() is supported for spot markets only')
        req = {
            'cost': cost,
        }
        return await self.create_order(symbol, 'market', 'buy', cost, None, self.extend(req, params))

    async def create_spot_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}) -> Order:
        """
        create a trade order on spot market

        https://hashkeyglobal-apidoc.readme.io/reference/test-new-order
        https://hashkeyglobal-apidoc.readme.io/reference/create-order

        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit' or 'LIMIT_MAKER'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of you want to trade in units of the base currency
        :param float [price]: the price that the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.cost]: *market buy only* the quote quantity that can be used alternative for the amount
        :param bool [params.test]: whether to use the test endpoint or not, default is False
        :param bool [params.postOnly]: if True, the order will only be posted to the order book and not executed immediately
        :param str [params.timeInForce]: 'GTC', 'IOC', or 'PO'
        :param str [params.clientOrderId]: a unique id for the order
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        triggerPrice = self.safe_string_2(params, 'stopPrice', 'triggerPrice')
        if triggerPrice is not None:
            raise NotSupported(self.id + ' trigger orders are not supported for spot markets')
        await self.load_markets()
        market = self.market(symbol)
        isMarketBuy = (type == 'market') and (side == 'buy')
        cost = self.safe_string(params, 'cost')
        if (not isMarketBuy) and (cost is not None):
            raise NotSupported(self.id + ' createOrder() supports cost parameter for spot market buy orders only')
        request: dict = self.create_spot_order_request(symbol, type, side, amount, price, params)
        response: dict = {}
        test = self.safe_bool(params, 'test')
        if test:
            params = self.omit(params, 'test')
            response = await self.privatePostApiV1SpotOrderTest(request)
        elif isMarketBuy and (cost is None):
            response = await self.privatePostApiV11SpotOrder(request)  # the endpoint for market buy orders by amount
            #
            #     {
            #         "accountId": "1732885739589466112",
            #         "symbol": "ETHUSDT",
            #         "symbolName": "ETHUSDT",
            #         "clientOrderId": "1722005792096557",
            #         "orderId": "1738705036219839744",
            #         "transactTime": "1722005792106",
            #         "price": "0",
            #         "origQty": "0.006",
            #         "executedQty": "0.0059",
            #         "status": "FILLED",
            #         "timeInForce": "IOC",
            #         "type": "MARKET",
            #         "side": "BUY",
            #         "reqAmount": "0",
            #         "concentration": ""
            #     }
            #
        else:
            response = await self.privatePostApiV1SpotOrder(request)  # the endpoint for market buy orders by cost and other orders
            #
            # market buy
            #     {
            #         "accountId": "1732885739589466112",
            #         "symbol": "ETHUSDT",
            #         "symbolName": "ETHUSDT",
            #         "clientOrderId": "1722004623170558",
            #         "orderId": "1738695230608169984",
            #         "transactTime": "1722004623186",
            #         "price": "0",
            #         "origQty": "0",
            #         "executedQty": "0.0061",
            #         "status": "FILLED",
            #         "timeInForce": "IOC",
            #         "type": "MARKET",
            #         "side": "BUY",
            #         "reqAmount": "20",
            #         "concentration": ""
            #     }
            #
            # market sell
            #     {
            #         "accountId": "1732885739589466112",
            #         "symbol": "ETHUSDT",
            #         "symbolName": "ETHUSDT",
            #         "clientOrderId": "1722005654516362",
            #         "orderId": "1738703882140316928",
            #         "transactTime": "1722005654529",
            #         "price": "0",
            #         "origQty": "0.006",
            #         "executedQty": "0.006",
            #         "status": "FILLED",
            #         "timeInForce": "IOC",
            #         "type": "MARKET",
            #         "side": "SELL",
            #         "reqAmount": "0",
            #         "concentration": ""
            #     }
            #
            # limit
            #     {
            #         "accountId": "1732885739589466112",
            #         "symbol": "ETHUSDT",
            #         "symbolName": "ETHUSDT",
            #         "clientOrderId": "1722006209978370",
            #         "orderId": "1738708541676585728",
            #         "transactTime": "1722006209989",
            #         "price": "5000",
            #         "origQty": "0.005",
            #         "executedQty": "0",
            #         "status": "NEW",
            #         "timeInForce": "GTC",
            #         "type": "LIMIT_MAKER",
            #         "side": "SELL",
            #         "reqAmount": "0",
            #         "concentration": ""
            #     }
            #
        return self.parse_order(response, market)

    def create_order_request(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}) -> dict:
        market = self.market(symbol)
        if market['spot']:
            return self.create_spot_order_request(symbol, type, side, amount, price, params)
        elif market['swap']:
            return self.create_swap_order_request(symbol, type, side, amount, price, params)
        else:
            raise NotSupported(self.id + ' ' + 'createOrderRequest() is not supported for ' + market['type'] + ' type of markets')

    def create_spot_order_request(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}) -> dict:
        """
 @ignore
        helper function to build request
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit' or 'LIMIT_MAKER'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of you want to trade in units of the base currency
        :param float [price]: the price that the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.cost]: *market buy only* the quote quantity that can be used alternative for the amount
        :param bool [params.postOnly]: if True, the order will only be posted to the order book and not executed immediately
        :param str [params.timeInForce]: "GTC", "IOC", or "PO"
        :param str [params.clientOrderId]: a unique id for the order
        :returns dict: request to be sent to the exchange
        """
        market = self.market(symbol)
        type = type.upper()
        request: dict = {
            'symbol': market['id'],
            'side': side.upper(),
            'type': type,
        }
        if amount is not None:
            request['quantity'] = self.amount_to_precision(symbol, amount)
        cost: Str = None
        cost, params = self.handle_param_string(params, 'cost')
        if cost is not None:
            request['quantity'] = self.cost_to_precision(symbol, cost)
        if price is not None:
            request['price'] = self.price_to_precision(symbol, price)
        isMarketOrder = type == 'MARKET'
        postOnly = False
        postOnly, params = self.handle_post_only(isMarketOrder, type == 'LIMIT_MAKER', params)
        if postOnly and (type == 'LIMIT'):
            request['type'] = 'LIMIT_MAKER'
        clientOrderId: Str = None
        clientOrderId, params = self.handle_param_string(params, 'clientOrderId')
        if clientOrderId is not None:
            params['newClientOrderId'] = clientOrderId
        return self.extend(request, params)

    def create_swap_order_request(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}) -> dict:
        """
 @ignore
        helper function to build request
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit' or 'STOP'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of you want to trade in units of the base currency
        :param float [price]: the price that the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.postOnly]: if True, the order will only be posted to the order book and not executed immediately
        :param bool [params.reduceOnly]: True or False whether the order is reduce only
        :param float [params.triggerPrice]: The price at which a trigger order is triggered at
        :param str [params.timeInForce]: 'GTC', 'FOK', 'IOC', 'LIMIT_MAKER' or 'PO'
        :param str [params.clientOrderId]: a unique id for the order
        :returns dict: request to be sent to the exchange
        """
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
            'type': 'LIMIT',
            'quantity': self.amount_to_precision(symbol, amount),
        }
        isMarketOrder = type == 'market'
        if isMarketOrder:
            request['priceType'] = 'MARKET'
        if price is not None:
            request['price'] = self.price_to_precision(symbol, price)
            request['priceType'] = 'INPUT'
        reduceOnly = False
        reduceOnly, params = self.handle_param_bool(params, 'reduceOnly', reduceOnly)
        suffix = '_OPEN'
        if reduceOnly:
            suffix = '_CLOSE'
        request['side'] = side.upper() + suffix
        timeInForce: Str = None
        timeInForce, params = self.handle_param_string(params, 'timeInForce')
        postOnly = False
        postOnly, params = self.handle_post_only(isMarketOrder, timeInForce == 'LIMIT_MAKER', params)
        if postOnly:
            timeInForce = 'LIMIT_MAKER'
        if timeInForce is not None:
            request['timeInForce'] = timeInForce
        clientOrderId = self.safe_string(params, 'clientOrderId')
        if clientOrderId is None:
            request['clientOrderId'] = self.uuid()
        triggerPrice = self.safe_string(params, 'triggerPrice')
        if triggerPrice is not None:
            request['stopPrice'] = self.price_to_precision(symbol, triggerPrice)
            request['type'] = 'STOP'
            params = self.omit(params, 'triggerPrice')
        return self.extend(request, params)

    async def create_swap_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}) -> Order:
        """
        create a trade order on swap market

        https://hashkeyglobal-apidoc.readme.io/reference/create-new-futures-order

        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit' or 'STOP'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of you want to trade in units of the base currency
        :param float [price]: the price that the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.postOnly]: if True, the order will only be posted to the order book and not executed immediately
        :param bool [params.reduceOnly]: True or False whether the order is reduce only
        :param float [params.triggerPrice]: The price at which a trigger order is triggered at
        :param str [params.timeInForce]: 'GTC', 'FOK', 'IOC', 'LIMIT_MAKER' or 'PO'
        :param str [params.clientOrderId]: a unique id for the order
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = self.create_swap_order_request(symbol, type, side, amount, price, params)
        response = await self.privatePostApiV1FuturesOrder(self.extend(request, params))
        #
        #     {
        #         "time": "1722429951611",
        #         "updateTime": "1722429951648",
        #         "orderId": "1742263144028363776",
        #         "clientOrderId": "1722429950315",
        #         "symbol": "ETHUSDT-PERPETUAL",
        #         "price": "3460.62",
        #         "leverage": "5",
        #         "origQty": "10",
        #         "executedQty": "10",
        #         "avgPrice": "0",
        #         "marginLocked": "6.9212",
        #         "type": "LIMIT",
        #         "side": "BUY_OPEN",
        #         "timeInForce": "IOC",
        #         "status": "FILLED",
        #         "priceType": "MARKET",
        #         "contractMultiplier": "0.00100000"
        #     }
        #
        return self.parse_order(response, market)

    async def create_orders(self, orders: List[OrderRequest], params={}):
        """
        create a list of trade orders(all orders should be of the same symbol)

        https://hashkeyglobal-apidoc.readme.io/reference/create-multiple-orders
        https://hashkeyglobal-apidoc.readme.io/reference/batch-create-new-futures-order

        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :param dict [params]: extra parameters specific to the api endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        ordersRequests = []
        for i in range(0, len(orders)):
            rawOrder = orders[i]
            symbol = self.safe_string(rawOrder, 'symbol')
            type = self.safe_string(rawOrder, 'type')
            side = self.safe_string(rawOrder, 'side')
            amount = self.safe_number(rawOrder, 'amount')
            price = self.safe_number(rawOrder, 'price')
            orderParams = self.safe_dict(rawOrder, 'params', {})
            orderRequest = self.create_order_request(symbol, type, side, amount, price, orderParams)
            clientOrderId = self.safe_string(orderRequest, 'clientOrderId')
            if clientOrderId is None:
                orderRequest['clientOrderId'] = self.uuid()  # both spot and swap endpoints require clientOrderId
            ordersRequests.append(orderRequest)
        firstOrder = ordersRequests[0]
        firstSymbol = self.safe_string(firstOrder, 'symbol')
        market = self.market(firstSymbol)
        request: dict = {
            'orders': ordersRequests,
        }
        response = None
        if market['spot']:
            response = await self.privatePostApiV1SpotBatchOrders(self.extend(request, params))
            #
            #     {
            #         "code": 0,
            #         "result": [
            #             {
            #                 "code": "0000",
            #                 "order": {
            #                     "accountId": "1732885739589466112",
            #                     "symbol": "ETHUSDT",
            #                     "symbolName": "ETHUSDT",
            #                     "clientOrderId": "1722701490163000",
            #                     "orderId": "1744540984757258752",
            #                     "transactTime": "1722701491385",
            #                     "price": "1500",
            #                     "origQty": "0.001",
            #                     "executedQty": "0",
            #                     "status": "NEW",
            #                     "timeInForce": "GTC",
            #                     "type": "LIMIT",
            #                     "side": "BUY",
            #                     "reqAmount": "0"
            #                 }
            #             }
            #         ],
            #         "concentration": ""
            #     }
            #
        elif market['swap']:
            response = await self.privatePostApiV1FuturesBatchOrders(self.extend(request, params))
            #
            #     {
            #         "code": "0000",
            #         "result": [
            #             {
            #                 "code": "0000",
            #                 "order": {
            #                     "time": "1722704251911",
            #                     "updateTime": "1722704251918",
            #                     "orderId": "1744564141727808768",
            #                     "clientOrderId": "1722704250648000",
            #                     "symbol": "ETHUSDT-PERPETUAL",
            #                     "price": "1500",
            #                     "leverage": "4",
            #                     "origQty": "1",
            #                     "executedQty": "0",
            #                     "avgPrice": "0",
            #                     "marginLocked": "0.375",
            #                     "type": "LIMIT",
            #                     "side": "BUY_OPEN",
            #                     "timeInForce": "GTC",
            #                     "status": "NEW",
            #                     "priceType": "INPUT",
            #                     "isLiquidationOrder": False,
            #                     "indexPrice": "0",
            #                     "liquidationType": ""
            #                 }
            #             },
            #             {
            #                 "code": "0207",
            #                 "msg": "Create limit order sell price too low"
            #             }
            #         ]
            #     }
            #
        else:
            raise NotSupported(self.id + ' ' + 'createOrderRequest() is not supported for ' + market['type'] + ' type of markets')
        result = self.safe_list(response, 'result', [])
        responseOrders = []
        for i in range(0, len(result)):
            responseEntry = self.safe_dict(result, i, {})
            responseOrder = self.safe_dict(responseEntry, 'order', {})
            responseOrders.append(responseOrder)
        return self.parse_orders(responseOrders)

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

        https://hashkeyglobal-apidoc.readme.io/reference/cancel-order
        https://hashkeyglobal-apidoc.readme.io/reference/cancel-futures-order

        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.type]: 'spot' or 'swap' - the type of the market to fetch entry for(default 'spot')
        :param str [params.clientOrderId]: a unique id for the order that can be used alternative for the id
        :param bool [params.trigger]: *swap markets only* True for canceling a trigger order(default False)
        :param bool [params.stop]: *swap markets only* an alternative for trigger param
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        methodName = 'cancelOrder'
        self.check_type_param(methodName, params)
        await self.load_markets()
        request: dict = {}
        clientOrderId = self.safe_string(params, 'clientOrderId')
        if clientOrderId is None:
            request['orderId'] = id
        market: Market = None
        if symbol is not None:
            market = self.market(symbol)
        marketType = 'spot'
        marketType, params = self.handle_market_type_and_params(methodName, market, params, marketType)
        response = None
        if marketType == 'spot':
            response = await self.privateDeleteApiV1SpotOrder(self.extend(request, params))
            #
            #     {
            #         "accountId": "1732885739589466112",
            #         "symbol": "ETHUSDT",
            #         "clientOrderId": "1722006209978370",
            #         "orderId": "1738708541676585728",
            #         "transactTime": "1722006209989",
            #         "price": "5000",
            #         "origQty": "0.005",
            #         "executedQty": "0",
            #         "status": "NEW",
            #         "timeInForce": "GTC",
            #         "type": "LIMIT_MAKER",
            #         "side": "SELL"
            #     }
            #
        elif marketType == 'swap':
            isTrigger = False
            isTrigger, params = self.handle_trigger_option_and_params(params, methodName, isTrigger)
            if isTrigger:
                request['type'] = 'STOP'
            else:
                request['type'] = 'LIMIT'
            if market is not None:
                request['symbol'] = market['id']
            response = await self.privateDeleteApiV1FuturesOrder(self.extend(request, params))
            #
            #     {
            #         "time": "1722432302919",
            #         "updateTime": "1722432302925",
            #         "orderId": "1742282868229463040",
            #         "clientOrderId": "1722432301670",
            #         "symbol": "ETHUSDT-PERPETUAL",
            #         "price": "4000",
            #         "leverage": "5",
            #         "origQty": "10",
            #         "executedQty": "0",
            #         "avgPrice": "0",
            #         "marginLocked": "0",
            #         "type": "LIMIT_MAKER",
            #         "side": "SELL_CLOSE",
            #         "timeInForce": "GTC",
            #         "status": "NEW",
            #         "priceType": "INPUT",
            #         "isLiquidationOrder": False,
            #         "indexPrice": "0",
            #         "liquidationType": ""
            #     }
            #
        else:
            raise NotSupported(self.id + ' ' + methodName + '() is not supported for ' + marketType + ' type of markets')
        return self.parse_order(response)

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

        https://hashkeyglobal-apidoc.readme.io/reference/cancel-all-open-orders
        https://hashkeyglobal-apidoc.readme.io/reference/batch-cancel-futures-order

        :param str 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 exchange API endpoint
        :param str [params.side]: 'buy' or 'sell'
        :returns dict: response from exchange
        """
        # Does not cancel trigger orders. For canceling trigger order use cancelOrder() or cancelOrders()
        methodName = 'cancelAllOrders'
        if symbol is None:
            raise ArgumentsRequired(self.id + ' ' + methodName + '() requires a symbol argument')
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        side = self.safe_string(params, 'side')
        if side is not None:
            request['side'] = side
        response = None
        if market['spot']:
            response = await self.privateDeleteApiV1SpotOpenOrders(self.extend(request, params))
            #
            #     {"success": True}
            #
        elif market['swap']:
            response = await self.privateDeleteApiV1FuturesBatchOrders(self.extend(request, params))
            #
            #     {"message": "success", "timestamp": "1723127222198", "code": "0000"}
            #
        else:
            raise NotSupported(self.id + ' ' + methodName + '() is not supported for ' + market['type'] + ' type of markets')
        order = self.safe_order(response)
        order['info'] = response
        return [order]

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

        https://hashkeyglobal-apidoc.readme.io/reference/cancel-multiple-orders
        https://hashkeyglobal-apidoc.readme.io/reference/batch-cancel-futures-order-by-order-id

        :param str[] ids: order ids
        :param str [symbol]: unified market symbol(not used by hashkey)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.type]: 'spot' or 'swap' - the type of the market to fetch entry for(default 'spot')
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        methodName = 'cancelOrders'
        await self.load_markets()
        request = {}
        orderIds = ','.join(ids)
        request['ids'] = orderIds
        market: Market = None
        if symbol is not None:
            market = self.market(symbol)
        marketType = 'spot'
        marketType, params = self.handle_market_type_and_params(methodName, market, params, marketType)
        response = None
        if marketType == 'spot':
            response = await self.privateDeleteApiV1SpotCancelOrderByIds(self.extend(request))
            #
            #     {
            #         "code": "0000",
            #         "result": []
            #     }
            #
        elif marketType == 'swap':
            response = self.privateDeleteApiV1FuturesCancelOrderByIds(self.extend(request))
        else:
            raise NotSupported(self.id + ' ' + methodName + '() is not supported for ' + marketType + ' type of markets')
        order = self.safe_order(response)
        order['info'] = response
        return [order]

    async def fetch_order(self, id: str, symbol: Str = None, params={}) -> Order:
        """
        fetches information on an order made by the user

        https://hashkeyglobal-apidoc.readme.io/reference/query-order
        https://hashkeyglobal-apidoc.readme.io/reference/get-futures-order

        :param str id: the order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.type]: 'spot' or 'swap' - the type of the market to fetch entry for(default 'spot')
        :param str [params.clientOrderId]: a unique id for the order that can be used alternative for the id
        :param str [params.accountId]: *spot markets only* account id to fetch the order from
        :param bool [params.trigger]: *swap markets only* True for fetching a trigger order(default False)
        :param bool [params.stop]: *swap markets only* an alternative for trigger param
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        methodName = 'fetchOrder'
        self.check_type_param(methodName, params)
        await self.load_markets()
        request: dict = {}
        clientOrderId: Str = None
        clientOrderId, params = self.handle_param_string(params, 'clientOrderId')
        if clientOrderId is None:
            request['orderId'] = id
        market: Market = None
        if symbol is not None:
            market = self.market(symbol)
        marketType = 'spot'
        marketType, params = self.handle_market_type_and_params(methodName, market, params, marketType)
        response = None
        if marketType == 'spot':
            if clientOrderId is not None:
                request['origClientOrderId'] = clientOrderId
            response = await self.privateGetApiV1SpotOrder(self.extend(request, params))
            #
            #     {
            #         "accountId": "1732885739589466112",
            #         "exchangeId": "301",
            #         "symbol": "ETHUSDT",
            #         "symbolName": "ETHUSDT",
            #         "clientOrderId": "1722004623170558",
            #         "orderId": "1738695230608169984",
            #         "price": "0",
            #         "origQty": "0",
            #         "executedQty": "0.0061",
            #         "cummulativeQuoteQty": "19.736489",
            #         "cumulativeQuoteQty": "19.736489",
            #         "avgPrice": "3235.49",
            #         "status": "FILLED",
            #         "timeInForce": "IOC",
            #         "type": "MARKET",
            #         "side": "BUY",
            #         "stopPrice": "0.0",
            #         "icebergQty": "0.0",
            #         "time": "1722004623186",
            #         "updateTime": "1722004623406",
            #         "isWorking": True,
            #         "reqAmount": "20",
            #         "feeCoin": "",
            #         "feeAmount": "0",
            #         "sumFeeAmount": "0"
            #     }
            #
        elif marketType == 'swap':
            isTrigger = False
            isTrigger, params = self.handle_trigger_option_and_params(params, methodName, isTrigger)
            if isTrigger:
                request['type'] = 'STOP'
            response = await self.privateGetApiV1FuturesOrder(self.extend(request, params))
            #
            #     {
            #         "time": "1722429951611",
            #         "updateTime": "1722429951700",
            #         "orderId": "1742263144028363776",
            #         "clientOrderId": "1722429950315",
            #         "symbol": "ETHUSDT-PERPETUAL",
            #         "price": "3460.62",
            #         "leverage": "5",
            #         "origQty": "10",
            #         "executedQty": "10",
            #         "avgPrice": "3327.52",
            #         "marginLocked": "0",
            #         "type": "LIMIT",
            #         "side": "BUY_OPEN",
            #         "timeInForce": "IOC",
            #         "status": "FILLED",
            #         "priceType": "MARKET",
            #         "isLiquidationOrder": False,
            #         "indexPrice": "0",
            #         "liquidationType": ""
            #     }
            #
        else:
            raise NotSupported(self.id + ' ' + methodName + '() is not supported for ' + marketType + ' type of markets')
        return self.parse_order(response)

    async def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
        fetch all unfilled currently open orders

        https://hashkeyglobal-apidoc.readme.io/reference/get-current-open-orders
        https://hashkeyglobal-apidoc.readme.io/reference/get-sub-account-open-orders
        https://hashkeyglobal-apidoc.readme.io/reference/sub
        https://hashkeyglobal-apidoc.readme.io/reference/query-open-futures-orders

        :param str [symbol]: unified market symbol of the market orders were made in - is mandatory for swap markets
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve - default 500, maximum 1000
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.type]: 'spot' or 'swap' - the type of the market to fetch entries for(default 'spot')
        :param str [params.orderId]: *spot markets only* the id of the order to fetch
        :param str [params.side]: *spot markets only* 'buy' or 'sell' - the side of the orders to fetch
        :param str [params.fromOrderId]: *swap markets only* the id of the order to start from
        :param bool [params.trigger]: *swap markets only* True for fetching trigger orders(default False)
        :param bool [params.stop]: *swap markets only* an alternative for trigger param
        :param str [params.accountId]: account id to fetch the orders from
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        methodName = 'fetchOpenOrders'
        self.check_type_param(methodName, params)
        await self.load_markets()
        market: Market = None
        if symbol is not None:
            market = self.market(symbol)
        marketType = 'spot'
        marketType, params = self.handle_market_type_and_params(methodName, market, params, marketType)
        params = self.extend({'methodName': methodName}, params)
        if marketType == 'spot':
            return await self.fetch_open_spot_orders(symbol, since, limit, params)
        elif marketType == 'swap':
            return await self.fetch_open_swap_orders(symbol, since, limit, params)
        else:
            raise NotSupported(self.id + ' ' + methodName + '() is not supported for ' + marketType + ' type of markets')

    async def fetch_open_spot_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
 @ignore
        fetch all unfilled currently open orders for spot markets

        https://hashkeyglobal-apidoc.readme.io/reference/get-current-open-orders
        https://hashkeyglobal-apidoc.readme.io/reference/sub

        :param str [symbol]: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve - default 500, maximum 1000
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.orderId]: the id of the order to fetch
        :param str [params.side]: 'buy' or 'sell' - the side of the orders to fetch
        :param str [params.accountId]: account id to fetch the orders from
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        methodName = 'fetchOpenSpotOrders'
        methodName, params = self.handle_param_string(params, 'methodName', methodName)
        market: Market = None
        request: dict = {}
        response = None
        accountId: Str = None
        accountId, params = self.handle_option_and_params(params, methodName, 'accountId')
        if accountId is not None:
            request['subAccountId'] = accountId
            response = await self.privateGetApiV1SpotSubAccountOpenOrders(self.extend(request, params))
        else:
            if symbol is not None:
                market = self.market(symbol)
                request['symbol'] = market['id']
            if limit is not None:
                request['limit'] = limit
            response = await self.privateGetApiV1SpotOpenOrders(self.extend(request, params))
            #
            #     [
            #         {
            #             "accountId": "1732885739589466112",
            #             "exchangeId": "301",
            #             "symbol": "ETHUSDT",
            #             "symbolName": "ETHUSDT",
            #             "clientOrderId": "1",
            #             "orderId": "1739491435386897152",
            #             "price": "2000",
            #             "origQty": "0.001",
            #             "executedQty": "0",
            #             "cummulativeQuoteQty": "0",
            #             "cumulativeQuoteQty": "0",
            #             "avgPrice": "0",
            #             "status": "NEW",
            #             "timeInForce": "GTC",
            #             "type": "LIMIT",
            #             "side": "BUY",
            #             "stopPrice": "0.0",
            #             "icebergQty": "0.0",
            #             "time": "1722099538193",
            #             "updateTime": "1722099538197",
            #             "isWorking": True,
            #             "reqAmount": "0"
            #         }
            #     ]
            #
        return self.parse_orders(response, market, since, limit)

    async def fetch_open_swap_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
 @ignore
        fetch all unfilled currently open orders for swap markets

        https://hashkeyglobal-apidoc.readme.io/reference/query-open-futures-orders
        https://hashkeyglobal-apidoc.readme.io/reference/get-sub-account-open-orders

        :param str symbol: *is mandatory* unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve - maximum 500
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.fromOrderId]: the id of the order to start from
        :param bool [params.trigger]: True for fetching trigger orders(default False)
        :param bool [params.stop]: an alternative for trigger param
        :param str [params.accountId]: account id to fetch the orders from
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        methodName = 'fetchOpenSwapOrders'
        methodName, params = self.handle_param_string(params, 'methodName', methodName)
        if symbol is None:
            raise ArgumentsRequired(self.id + ' ' + methodName + '() requires a symbol argument for swap market orders')
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        isTrigger = False
        isTrigger, params = self.handle_trigger_option_and_params(params, methodName, isTrigger)
        if isTrigger:
            request['type'] = 'STOP'
        else:
            request['type'] = 'LIMIT'
        if limit is not None:
            request['limit'] = limit
        response = None
        accountId: Str = None
        accountId, params = self.handle_option_and_params(params, methodName, 'accountId')
        if accountId is not None:
            request['subAccountId'] = accountId
            response = await self.privateGetApiV1FuturesSubAccountOpenOrders(self.extend(request, params))
        else:
            response = await self.privateGetApiV1FuturesOpenOrders(self.extend(request, params))
            # 'LIMIT'
            #     [
            #         {
            #             "time": "1722432302919",
            #             "updateTime": "1722432302925",
            #             "orderId": "1742282868229463040",
            #             "clientOrderId": "1722432301670",
            #             "symbol": "ETHUSDT-PERPETUAL",
            #             "price": "4000",
            #             "leverage": "5",
            #             "origQty": "10",
            #             "executedQty": "0",
            #             "avgPrice": "0",
            #             "marginLocked": "0",
            #             "type": "LIMIT_MAKER",
            #             "side": "SELL_CLOSE",
            #             "timeInForce": "GTC",
            #             "status": "NEW",
            #             "priceType": "INPUT",
            #             "isLiquidationOrder": False,
            #             "indexPrice": "0",
            #             "liquidationType": ""
            #         }
            #     ]
            #
            # 'STOP'
            #     [
            #         {
            #             "time": "1722433095688",
            #             "updateTime": "1722433095688",
            #             "orderId": "1742289518466225664",
            #             "accountId": "1735619524953226496",
            #             "clientOrderId": "1722433094438",
            #             "symbol": "ETHUSDT-PERPETUAL",
            #             "price": "3700",
            #             "leverage": "0",
            #             "origQty": "10",
            #             "type": "STOP",
            #             "side": "SELL_CLOSE",
            #             "status": "ORDER_NEW",
            #             "stopPrice": "3600"
            #         }
            #     ]
        return self.parse_orders(response, market, since, limit)

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

        https://hashkeyglobal-apidoc.readme.io/reference/get-all-orders
        https://hashkeyglobal-apidoc.readme.io/reference/query-futures-history-orders
        https://hashkeyglobal-apidoc.readme.io/reference/get-sub-account-history-orders

        :param str symbol: *is mandatory for swap markets* unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve - default 500, maximum 1000
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch entries for - only supports the last 90 days timeframe
        :param str [params.type]: 'spot' or 'swap' - the type of the market to fetch entries for(default 'spot')
        :param str [params.orderId]: *spot markets only* the id of the order to fetch
        :param str [params.side]: *spot markets only* 'buy' or 'sell' - the side of the orders to fetch
        :param str [params.fromOrderId]: *swap markets only* the id of the order to start from
        :param bool [params.trigger]: *swap markets only* the id of the order to start from True for fetching trigger orders(default False)
        :param bool [params.stop]: *swap markets only* the id of the order to start from an alternative for trigger param
        :param str [params.accountId]: account id to fetch the orders from
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        methodName = 'fetchCanceledAndClosedOrders'
        self.check_type_param(methodName, params)
        await self.load_markets()
        request: dict = {}
        if limit is not None:
            request['limit'] = limit
        if since is not None:
            request['startTime'] = since
        until: Int = None
        until, params = self.handle_option_and_params(params, methodName, 'until')
        if until is not None:
            request['endTime'] = until
        accountId: Str = None
        accountId, params = self.handle_option_and_params(params, methodName, 'accountId')
        market: Market = None
        if symbol is not None:
            market = self.market(symbol)
        marketType = 'spot'
        marketType, params = self.handle_market_type_and_params(methodName, market, params, marketType)
        response = None
        if marketType == 'spot':
            if market is not None:
                request['symbol'] = market['id']
            if accountId is not None:
                request['accountId'] = accountId
            response = await self.privateGetApiV1SpotTradeOrders(self.extend(request, params))
            #
            #     [
            #         {
            #             "accountId": "1732885739589466112",
            #             "exchangeId": "301",
            #             "symbol": "ETHUSDT",
            #             "symbolName": "ETHUSDT",
            #             "clientOrderId": "1722082982086472",
            #             "orderId": "1739352552762301440",
            #             "price": "0",
            #             "origQty": "0.001",
            #             "executedQty": "0.001",
            #             "cummulativeQuoteQty": "3.28996",
            #             "cumulativeQuoteQty": "3.28996",
            #             "avgPrice": "3289.96",
            #             "status": "FILLED",
            #             "timeInForce": "IOC",
            #             "type": "MARKET",
            #             "side": "BUY",
            #             "stopPrice": "0.0",
            #             "icebergQty": "0.0",
            #             "time": "1722082982093",
            #             "updateTime": "1722082982097",
            #             "isWorking": True,
            #             "reqAmount": "0"
            #         },
            #         ...
            #     ]
            #
        elif marketType == 'swap':
            if symbol is None:
                raise ArgumentsRequired(self.id + ' ' + methodName + '() requires a symbol argument for swap markets')
            request['symbol'] = market['id']
            isTrigger = False
            isTrigger, params = self.handle_trigger_option_and_params(params, methodName, isTrigger)
            if isTrigger:
                request['type'] = 'STOP'
            else:
                request['type'] = 'LIMIT'
            if accountId is not None:
                request['subAccountId'] = accountId
                response = await self.privateGetApiV1FuturesSubAccountHistoryOrders(self.extend(request, params))
            else:
                response = await self.privateGetApiV1FuturesHistoryOrders(self.extend(request, params))
                #
                #     [
                #         {
                #             "time": "1722429951611",
                #             "updateTime": "1722429951700",
                #             "orderId": "1742263144028363776",
                #             "clientOrderId": "1722429950315",
                #             "symbol": "ETHUSDT-PERPETUAL",
                #             "price": "3460.62",
                #             "leverage": "5",
                #             "origQty": "10",
                #             "executedQty": "10",
                #             "avgPrice": "3327.52",
                #             "marginLocked": "0",
                #             "type": "LIMIT",
                #             "side": "BUY_OPEN",
                #             "timeInForce": "IOC",
                #             "status": "FILLED",
                #             "priceType": "MARKET",
                #             "isLiquidationOrder": False,
                #             "indexPrice": "0",
                #             "liquidationType": ""
                #         }
                #     ]
                #
        else:
            raise NotSupported(self.id + ' ' + methodName + '() is not supported for ' + marketType + ' type of markets')
        return self.parse_orders(response, market, since, limit)

    def check_type_param(self, methodName, params):
        # some hashkey endpoints have a type param for swap markets that defines the type of an order
        # type param is reserved in ccxt for defining the type of the market
        # current method warns user if he provides the exchange specific value in type parameter
        paramsType = self.safe_string(params, 'type')
        if (paramsType is not None) and (paramsType != 'spot') and (paramsType != 'swap'):
            raise BadRequest(self.id + ' ' + methodName + '() type parameter can not be "' + paramsType + '". It should define the type of the market("spot" or "swap"). To define the type of an order use the trigger parameter(True for trigger orders)')

    def handle_trigger_option_and_params(self, params: object, methodName: str, defaultValue=None):
        isTrigger = defaultValue
        isTrigger, params = self.handle_option_and_params_2(params, methodName, 'stop', 'trigger', isTrigger)
        return [isTrigger, params]

    def parse_order(self, order: dict, market: Market = None) -> Order:
        #
        # createOrder spot
        #     {
        #         "accountId": "1732885739589466112",
        #         "symbol": "ETHUSDT",
        #         "symbolName": "ETHUSDT",
        #         "clientOrderId": "1722004623170558",
        #         "orderId": "1738695230608169984",
        #         "transactTime": "1722004623186",
        #         "price": "0",
        #         "origQty": "0",
        #         "executedQty": "0.0061",
        #         "status": "FILLED",
        #         "timeInForce": "IOC",
        #         "type": "MARKET",
        #         "side": "BUY",
        #         "reqAmount": "20",
        #         "concentration": ""
        #     }
        #
        # fetchOrder spot
        #     {
        #         "accountId": "1732885739589466112",
        #         "exchangeId": "301",
        #         "symbol": "ETHUSDT",
        #         "symbolName": "ETHUSDT",
        #         "clientOrderId": "1722004623170558",
        #         "orderId": "1738695230608169984",
        #         "price": "0",
        #         "origQty": "0",
        #         "executedQty": "0.0061",
        #         "cummulativeQuoteQty": "19.736489",
        #         "cumulativeQuoteQty": "19.736489",
        #         "avgPrice": "3235.49",
        #         "status": "FILLED",
        #         "timeInForce": "IOC",
        #         "type": "MARKET",
        #         "side": "BUY",
        #         "stopPrice": "0.0",
        #         "icebergQty": "0.0",
        #         "time": "1722004623186",
        #         "updateTime": "1722004623406",
        #         "isWorking": True,
        #         "reqAmount": "20",
        #         "feeCoin": "",
        #         "feeAmount": "0",
        #         "sumFeeAmount": "0"
        #     }
        #
        # cancelOrder
        #     {
        #         "accountId": "1732885739589466112",
        #         "symbol": "ETHUSDT",
        #         "clientOrderId": "1722006209978370",
        #         "orderId": "1738708541676585728",
        #         "transactTime": "1722006209989",
        #         "price": "5000",
        #         "origQty": "0.005",
        #         "executedQty": "0",
        #         "status": "NEW",
        #         "timeInForce": "GTC",
        #         "type": "LIMIT_MAKER",
        #         "side": "SELL"
        #     }
        #
        # createOrder swap
        #     {
        #         "time": "1722429951611",
        #         "updateTime": "1722429951648",
        #         "orderId": "1742263144028363776",
        #         "clientOrderId": "1722429950315",
        #         "symbol": "ETHUSDT-PERPETUAL",
        #         "price": "3460.62",
        #         "leverage": "5",
        #         "origQty": "10",
        #         "executedQty": "10",
        #         "avgPrice": "0",
        #         "marginLocked": "6.9212",
        #         "type": "LIMIT",
        #         "side": "BUY_OPEN",
        #         "timeInForce": "IOC",
        #         "status": "FILLED",
        #         "priceType": "MARKET",
        #         "contractMultiplier": "0.00100000"
        #     }
        #
        # fetchOrder swap
        #     {
        #         "time": "1722429951611",
        #         "updateTime": "1722429951700",
        #         "orderId": "1742263144028363776",
        #         "clientOrderId": "1722429950315",
        #         "symbol": "ETHUSDT-PERPETUAL",
        #         "price": "3460.62",
        #         "leverage": "5",
        #         "origQty": "10",
        #         "executedQty": "10",
        #         "avgPrice": "3327.52",
        #         "marginLocked": "0",
        #         "type": "LIMIT",
        #         "side": "BUY_OPEN",
        #         "timeInForce": "IOC",
        #         "status": "FILLED",
        #         "priceType": "MARKET",
        #         "isLiquidationOrder": False,
        #         "indexPrice": "0",
        #         "liquidationType": ""
        #     }
        #
        marketId = self.safe_string(order, 'symbol')
        market = self.safe_market(marketId, market)
        timestamp = self.safe_integer_2(order, 'transactTime', 'time')
        status = self.safe_string(order, 'status')
        type = self.safe_string(order, 'type')
        priceType = self.safe_string(order, 'priceType')
        if priceType == 'MARKET':
            type = 'market'
        price = self.omit_zero(self.safe_string(order, 'price'))
        if type == 'STOP':
            if price is None:
                type = 'market'
            else:
                type = 'limit'
        timeInForce = self.safe_string(order, 'timeInForce')
        postOnly: Bool = None
        type, timeInForce, postOnly = self.parse_order_type_time_in_force_and_post_only(type, timeInForce)
        average = self.omit_zero(self.safe_string(order, 'avgPrice'))
        if price is None:
            price = average
        side = self.safe_string_lower(order, 'side')
        reduceOnly: Bool = None
        side, reduceOnly = self.parse_order_side_and_reduce_only(side)
        feeCurrncyId = self.safe_string(order, 'feeCoin')
        if feeCurrncyId == '':
            feeCurrncyId = None
        return self.safe_order({
            'id': self.safe_string(order, 'orderId'),
            'clientOrderId': self.safe_string(order, 'clientOrderId'),
            'datetime': self.iso8601(timestamp),
            'timestamp': timestamp,
            'lastTradeTimestamp': None,
            'lastUpdateTimestamp': self.safe_integer(order, 'updateTime'),
            'status': self.parse_order_status(status),
            'symbol': market['symbol'],
            'type': type,
            'timeInForce': timeInForce,
            'side': side,
            'price': price,
            'average': average,
            'amount': self.omit_zero(self.safe_string(order, 'origQty')),
            'filled': self.safe_string(order, 'executedQty'),
            'remaining': None,
            'triggerPrice': self.omit_zero(self.safe_string(order, 'stopPrice')),
            'takeProfitPrice': None,
            'stopLossPrice': None,
            'cost': self.omit_zero(self.safe_string_2(order, 'cumulativeQuoteQty', 'cummulativeQuoteQty')),
            'trades': None,
            'fee': {
                'currency': self.safe_currency_code(feeCurrncyId),
                'amount': self.omit_zero(self.safe_string(order, 'feeAmount')),
            },
            'reduceOnly': reduceOnly,
            'postOnly': postOnly,
            'info': order,
        }, market)

    def parse_order_side_and_reduce_only(self, unparsed):
        parts = unparsed.split('_')
        side = parts[0]
        reduceOnly: Bool = None
        secondPart = self.safe_string(parts, 1)
        if secondPart is not None:
            if secondPart == 'open':
                reduceOnly = False
            elif (secondPart == 'close'):
                reduceOnly = True
        return [side, reduceOnly]

    def parse_order_status(self, status):
        statuses = {
            'NEW': 'open',
            'PARTIALLY_FILLED': 'open',
            'PARTIALLY_CANCELED': 'canceled',
            'FILLED': 'closed',
            'CANCELED': 'canceled',
            'ORDER_CANCELED': 'canceled',
            'PENDING_CANCEL': 'canceled',
            'REJECTED': 'rejected',
            'ORDER_NEW': 'open',
        }
        return self.safe_string(statuses, status, status)

    def parse_order_type_time_in_force_and_post_only(self, type, timeInForce):
        postOnly: Bool = None
        if type == 'LIMIT_MAKER':
            postOnly = True
        elif (timeInForce == 'LIMIT_MAKER') or (timeInForce == 'MAKER'):
            postOnly = True
            timeInForce = 'PO'
        type = self.parse_order_type(type)
        return [type, timeInForce, postOnly]

    def parse_order_type(self, type):
        types = {
            'MARKET': 'market',
            'LIMIT': 'limit',
            'LIMIT_MAKER': 'limit',
            'MARKET_OF_BASE': 'market',
        }
        return self.safe_string(types, type, type)

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

        https://hashkeyglobal-apidoc.readme.io/reference/get-futures-funding-rate

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
            'timestamp': self.milliseconds(),
        }
        response = await self.publicGetApiV1FuturesFundingRate(self.extend(request, params))
        #
        #     [
        #         {"symbol": "ETHUSDT-PERPETUAL", "rate": "0.0001", "nextSettleTime": "1722297600000"}
        #     ]
        #
        rate = self.safe_dict(response, 0, {})
        return self.parse_funding_rate(rate, market)

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

        https://hashkeyglobal-apidoc.readme.io/reference/get-futures-funding-rate

        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rates-structure>`, indexed by market symbols
        """
        await self.load_markets()
        symbols = self.market_symbols(symbols)
        request: dict = {
            'timestamp': self.milliseconds(),
        }
        response = await self.publicGetApiV1FuturesFundingRate(self.extend(request, params))
        #
        #     [
        #         {"symbol": "BTCUSDT-PERPETUAL", "rate": "0.0001", "nextSettleTime": "1722297600000"},
        #         {"symbol": "ETHUSDT-PERPETUAL", "rate": "0.0001", "nextSettleTime": "1722297600000"}
        #     ]
        #
        return self.parse_funding_rates(response, symbols)

    def parse_funding_rate(self, contract, market: Market = None) -> FundingRate:
        #
        #     {
        #         "symbol": "ETHUSDT-PERPETUAL",
        #         "rate": "0.0001",
        #         "nextSettleTime": "1722297600000"
        #     }
        #
        marketId = self.safe_string(contract, 'symbol')
        market = self.safe_market(marketId, market, None, 'swap')
        fundingRate = self.safe_number(contract, 'rate')
        fundingTimestamp = self.safe_integer(contract, 'nextSettleTime')
        return {
            'info': contract,
            'symbol': market['symbol'],
            'markPrice': None,
            'indexPrice': None,
            'interestRate': None,
            'estimatedSettlePrice': None,
            'timestamp': None,
            'datetime': None,
            'fundingRate': fundingRate,
            'fundingTimestamp': None,
            'fundingDatetime': None,
            'nextFundingRate': None,
            'nextFundingTimestamp': fundingTimestamp,
            'nextFundingDatetime': self.iso8601(fundingTimestamp),
            'previousFundingRate': None,
            'previousFundingTimestamp': None,
            'previousFundingDatetime': None,
            'interval': None,
        }

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

        https://hashkeyglobal-apidoc.readme.io/reference/get-futures-history-funding-rate

        :param str symbol: unified symbol of the market to fetch the funding rate history for
        :param int [since]: timestamp in ms of the earliest funding rate to fetch
        :param int [limit]: the maximum amount of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>` to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.fromId]: the id of the entry to start from
        :param int [params.endId]: the id of the entry to end with
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
        """
        await self.load_markets()
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchFundingRateHistory() requires a symbol argument')
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit
        response = await self.publicGetApiV1FuturesHistoryFundingRate(self.extend(request, params))
        #
        #     [
        #         {
        #             "id": "10698",
        #             "symbol": "ETHUSDT-PERPETUAL",
        #             "settleTime": "1722268800000",
        #             "settleRate": "0.0001"
        #         },
        #         ...
        #     ]
        #
        rates = []
        for i in range(0, len(response)):
            entry = response[i]
            timestamp = self.safe_integer(entry, 'settleTime')
            rates.append({
                'info': entry,
                'symbol': self.safe_symbol(self.safe_string(entry, 'symbol'), market, None, 'swap'),
                'fundingRate': self.safe_number(entry, 'settleRate'),
                'timestamp': timestamp,
                'datetime': self.iso8601(timestamp),
            })
        sorted = self.sort_by(rates, 'timestamp')
        return self.filter_by_since_limit(sorted, since, limit)

    async def fetch_positions(self, symbols: Strings = None, params={}) -> List[Position]:
        """
        fetch open positions for a market

        https://hashkeyglobal-apidoc.readme.io/reference/get-futures-positions

        fetch all open positions
        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.side]: 'LONG' or 'SHORT' - the direction of the position(if not provided, positions for both sides will be returned)
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        """
        methodName = 'fetchPositions'
        if (symbols is None):
            raise ArgumentsRequired(self.id + ' ' + methodName + '() requires a symbol argument with one single market symbol')
        else:
            symbolsLength = len(symbols)
            if symbolsLength != 1:
                raise NotSupported(self.id + ' ' + methodName + '() is supported for a symbol argument with one single market symbol only')
        await self.load_markets()
        return await self.fetch_positions_for_symbol(symbols[0], self.extend({'methodName': 'fetchPositions'}, params))

    async def fetch_positions_for_symbol(self, symbol: str, params={}) -> List[Position]:
        """
        fetch open positions for a single market

        https://hashkeyglobal-apidoc.readme.io/reference/get-futures-positions

        fetch all open positions for specific symbol
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.side]: 'LONG' or 'SHORT' - the direction of the position(if not provided, positions for both sides will be returned)
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        methodName = 'fetchPosition'
        methodName, params = self.handle_param_string(params, 'methodName', methodName)
        if not market['swap']:
            raise NotSupported(self.id + ' ' + methodName + '() supports swap markets only')
        request: dict = {
            'symbol': market['id'],
        }
        response = await self.privateGetApiV1FuturesPositions(self.extend(request, params))
        #
        #     [
        #         {
        #             "symbol": "ETHUSDT-PERPETUAL",
        #             "side": "LONG",
        #             "avgPrice": "3327.52",
        #             "position": "10",
        #             "available": "0",
        #             "leverage": "5",
        #             "lastPrice": "3324.44",
        #             "positionValue": "33.2752",
        #             "liquidationPrice": "-953.83",
        #             "margin": "6.9012",
        #             "marginRate": "",
        #             "unrealizedPnL": "-0.0288",
        #             "profitRate": "-0.0041",
        #             "realizedPnL": "-0.0199",
        #             "minMargin": "0.2173"
        #         }
        #     ]
        #
        return self.parse_positions(response, [symbol])

    def parse_position(self, position: dict, market: Market = None):
        marketId = self.safe_string(position, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        return self.safe_position({
            'symbol': symbol,
            'id': None,
            'timestamp': None,
            'datetime': None,
            'contracts': self.safe_number(position, 'position'),
            'contractSize': None,
            'side': self.safe_string_lower(position, 'side'),
            'notional': self.safe_number(position, 'positionValue'),
            'leverage': self.safe_integer(position, 'leverage'),
            'unrealizedPnl': self.safe_number(position, 'unrealizedPnL'),
            'realizedPnl': self.safe_number(position, 'realizedPnL'),
            'collateral': None,
            'entryPrice': self.safe_number(position, 'avgPrice'),
            'markPrice': None,
            'liquidationPrice': self.safe_number(position, 'liquidationPrice'),
            'marginMode': 'cross',
            'hedged': True,
            'maintenanceMargin': self.safe_number(position, 'minMargin'),
            'maintenanceMarginPercentage': None,
            'initialMargin': self.safe_number(position, 'margin'),
            'initialMarginPercentage': None,
            'marginRatio': None,
            'lastUpdateTimestamp': None,
            'lastPrice': self.safe_number(position, 'lastPrice'),
            'stopLossPrice': None,
            'takeProfitPrice': None,
            'percentage': None,
            'info': position,
        })

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

        https://hashkeyglobal-apidoc.readme.io/reference/query-futures-leverage-trade

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `leverage structure <https://docs.ccxt.com/#/?id=leverage-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = await self.privateGetApiV1FuturesLeverage(self.extend(request, params))
        #
        #     [
        #         {
        #             "symbolId": "ETHUSDT-PERPETUAL",
        #             "leverage": "5",
        #             "marginType": "CROSS"
        #         }
        #     ]
        #
        leverage = self.safe_dict(response, 0, {})
        return self.parse_leverage(leverage, market)

    def parse_leverage(self, leverage: dict, market: Market = None) -> Leverage:
        marginMode = self.safe_string_lower(leverage, 'marginType')
        leverageValue = self.safe_number(leverage, 'leverage')
        return {
            'info': leverage,
            'symbol': market['symbol'],
            'marginMode': marginMode,
            'longLeverage': leverageValue,
            'shortLeverage': leverageValue,
        }

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

        https://hashkeyglobal-apidoc.readme.io/reference/change-futures-leverage-trade

        :param float leverage: the rate of leverage
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' setLeverage() requires a symbol argument')
        await self.load_markets()
        request: dict = {
            'leverage': leverage,
        }
        market = self.market(symbol)
        request['symbol'] = market['id']
        response = await self.privatePostApiV1FuturesLeverage(self.extend(request, params))
        #
        #     {
        #         "code": "0000",
        #         "symbolId": "ETHUSDT-PERPETUAL",
        #         "leverage": "3"
        #     }
        #
        return self.parse_leverage(response, market)

    async def fetch_leverage_tiers(self, symbols: Strings = None, params={}) -> LeverageTiers:
        """
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes

        https://hashkeyglobal-apidoc.readme.io/reference/exchangeinfo

        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `leverage tiers structures <https://docs.ccxt.com/#/?id=leverage-tiers-structure>`, indexed by market symbols
        """
        await self.load_markets()
        response = await self.publicGetApiV1ExchangeInfo(params)
        # response is the same fetchMarkets()
        data = self.safe_list(response, 'contracts', [])
        symbols = self.market_symbols(symbols)
        return self.parse_leverage_tiers(data, symbols, 'symbol')

    def parse_market_leverage_tiers(self, info, market: Market = None) -> List[LeverageTier]:
        #
        #     {
        #         "filters": [
        #             {
        #                 "minPrice": "0.1",
        #                 "maxPrice": "100000.00000000",
        #                 "tickSize": "0.1",
        #                 "filterType": "PRICE_FILTER"
        #             },
        #             {
        #                 "minQty": "0.001",
        #                 "maxQty": "10",
        #                 "stepSize": "0.001",
        #                 "marketOrderMinQty": "0",
        #                 "marketOrderMaxQty": "0",
        #                 "filterType": "LOT_SIZE"
        #             },
        #             {
        #                 "minNotional": "0",
        #                 "filterType": "MIN_NOTIONAL"
        #             },
        #             {
        #                 "maxSellPrice": "999999",
        #                 "buyPriceUpRate": "0.05",
        #                 "sellPriceDownRate": "0.05",
        #                 "maxEntrustNum": 200,
        #                 "maxConditionNum": 200,
        #                 "filterType": "LIMIT_TRADING"
        #             },
        #             {
        #                 "buyPriceUpRate": "0.05",
        #                 "sellPriceDownRate": "0.05",
        #                 "filterType": "MARKET_TRADING"
        #             },
        #             {
        #                 "noAllowMarketStartTime": "0",
        #                 "noAllowMarketEndTime": "0",
        #                 "limitOrderStartTime": "0",
        #                 "limitOrderEndTime": "0",
        #                 "limitMinPrice": "0",
        #                 "limitMaxPrice": "0",
        #                 "filterType": "OPEN_QUOTE"
        #             }
        #         ],
        #         "exchangeId": "301",
        #         "symbol": "BTCUSDT-PERPETUAL",
        #         "symbolName": "BTCUSDT-PERPETUAL",
        #         "status": "TRADING",
        #         "baseAsset": "BTCUSDT-PERPETUAL",
        #         "baseAssetPrecision": "0.001",
        #         "quoteAsset": "USDT",
        #         "quoteAssetPrecision": "0.1",
        #         "icebergAllowed": False,
        #         "inverse": False,
        #         "index": "USDT",
        #         "marginToken": "USDT",
        #         "marginPrecision": "0.0001",
        #         "contractMultiplier": "0.001",
        #         "underlying": "BTC",
        #         "riskLimits": [
        #             {
        #                 "riskLimitId": "200000722",
        #                 "quantity": "1000.00",
        #                 "initialMargin": "0.10",
        #                 "maintMargin": "0.005",
        #                 "isWhite": False
        #             },
        #             {
        #                 "riskLimitId": "200000723",
        #                 "quantity": "2000.00",
        #                 "initialMargin": "0.10",
        #                 "maintMargin": "0.01",
        #                 "isWhite": False
        #             }
        #         ]
        #     }
        #
        riskLimits = self.safe_list(info, 'riskLimits', [])
        marketId = self.safe_string(info, 'symbol')
        market = self.safe_market(marketId, market)
        tiers = []
        for i in range(0, len(riskLimits)):
            tier = riskLimits[i]
            initialMarginRate = self.safe_string(tier, 'initialMargin')
            tiers.append({
                'tier': self.sum(i, 1),
                'symbol': self.safe_symbol(marketId, market),
                'currency': market['settle'],
                'minNotional': None,
                'maxNotional': self.safe_number(tier, 'quantity'),
                'maintenanceMarginRate': self.safe_number(tier, 'maintMargin'),
                'maxLeverage': self.parse_number(Precise.string_div('1', initialMarginRate)),
                'info': tier,
            })
        return tiers

    async def fetch_trading_fee(self, symbol: str, params={}) -> TradingFeeInterface:
        """
        fetch the trading fees for a market

        https://developers.binance.com/docs/wallet/asset/trade-fee  # spot
        https://hashkeyglobal-apidoc.readme.io/reference/get-futures-commission-rate-request-weight  # swap

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/#/?id=fee-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        methodName = 'fetchTradingFee'
        response = None
        if market['spot']:
            response = await self.fetch_trading_fees(params)
            return self.safe_dict(response, symbol)
        elif market['swap']:
            response = await self.privateGetApiV1FuturesCommissionRate(self.extend({'symbol': market['id']}, params))
            return self.parse_trading_fee(response, market)
            #
            #     {
            #         "openMakerFee": "0.00025",
            #         "openTakerFee": "0.0006",
            #         "closeMakerFee": "0.00025",
            #         "closeTakerFee": "0.0006"
            #     }
            #
        else:
            raise NotSupported(self.id + ' ' + methodName + '() is not supported for ' + market['type'] + ' type of markets')

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

        https://developers.binance.com/docs/wallet/asset/trade-fee

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>` indexed by market symbols
        """
        await self.load_markets()
        response = await self.privateGetApiV1AccountVipInfo(params)
        #
        #     {
        #         "code": 0,
        #         "vipLevel": "0",
        #         "tradeVol30Day": "67",
        #         "totalAssetBal": "0",
        #         "data": [
        #             {
        #                 "symbol": "UXLINKUSDT",
        #                 "productType": "Token-Token",
        #                 "buyMakerFeeCurrency": "UXLINK",
        #                 "buyTakerFeeCurrency": "UXLINK",
        #                 "sellMakerFeeCurrency": "USDT",
        #                 "sellTakerFeeCurrency": "USDT",
        #                 "actualMakerRate": "0.0012",
        #                 "actualTakerRate": "0.0012"
        #             },
        #             ...
        #         ],
        #         "updateTimestamp": "1722320137809"
        #     }
        #
        data = self.safe_list(response, 'data', [])
        result: dict = {}
        for i in range(0, len(data)):
            fee = self.safe_dict(data, i, {})
            parsedFee = self.parse_trading_fee(fee)
            result[parsedFee['symbol']] = parsedFee
        return result

    def parse_trading_fee(self, fee: dict, market: Market = None) -> TradingFeeInterface:
        #
        # spot
        #     {
        #         "symbol": "UXLINKUSDT",
        #         "productType": "Token-Token",
        #         "buyMakerFeeCurrency": "UXLINK",
        #         "buyTakerFeeCurrency": "UXLINK",
        #         "sellMakerFeeCurrency": "USDT",
        #         "sellTakerFeeCurrency": "USDT",
        #         "actualMakerRate": "0.0012",
        #         "actualTakerRate": "0.0012"
        #     }
        #
        # swap
        #     {
        #         "openMakerFee": "0.00025",
        #         "openTakerFee": "0.0006",
        #         "closeMakerFee": "0.00025",
        #         "closeTakerFee": "0.0006"
        #     }
        #
        marketId = self.safe_string(fee, 'symbol')
        market = self.safe_market(marketId, market)
        return {
            'info': fee,
            'symbol': market['symbol'],
            'maker': self.safe_number_2(fee, 'openMakerFee', 'actualMakerRate'),
            'taker': self.safe_number_2(fee, 'openTakerFee', 'actualTakerRate'),
            'percentage': True,
            'tierBased': True,
        }

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = self.urls['api'][api] + '/' + path
        query: Str = None
        if api == 'private':
            self.check_required_credentials()
            timestamp = self.milliseconds()
            additionalParams = {
                'timestamp': timestamp,
            }
            recvWindow = self.safe_integer(self.options, 'recvWindow')
            if recvWindow is not None:
                additionalParams['recvWindow'] = recvWindow
            headers = {
                'X-HK-APIKEY': self.apiKey,
                'Content-Type': 'application/x-www-form-urlencoded',
            }
            signature: Str = None
            if (method == 'POST') and ((path == 'api/v1/spot/batchOrders') or (path == 'api/v1/futures/batchOrders')):
                headers['Content-Type'] = 'application/json'
                body = self.json(self.safe_list(params, 'orders'))
                signature = self.hmac(self.encode(self.custom_urlencode(additionalParams)), self.encode(self.secret), hashlib.sha256)
                query = self.custom_urlencode(self.extend(additionalParams, {'signature': signature}))
                url += '?' + query
            else:
                totalParams = self.extend(additionalParams, params)
                signature = self.hmac(self.encode(self.custom_urlencode(totalParams)), self.encode(self.secret), hashlib.sha256)
                totalParams['signature'] = signature
                query = self.custom_urlencode(totalParams)
                if method == 'GET':
                    url += '?' + query
                else:
                    body = query
            headers['INPUT-SOURCE'] = self.safe_string(self.options, 'broker', '10000700011')
            headers['broker_sign'] = signature
        else:
            query = self.urlencode(params)
            if len(query) != 0:
                url += '?' + query
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def custom_urlencode(self, params: dict = {}) -> Str:
        result = self.urlencode(params)
        result = result.replace('%2C', ',')
        return result

    def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
        if response is None:
            return None
        errorInArray = False
        responseCodeString = self.safe_string(response, 'code', None)
        responseCodeInteger = self.safe_integer(response, 'code', None)  # some codes in response are returned as '0000' others
        if responseCodeInteger == 0:
            result = self.safe_list(response, 'result', [])  # for batch methods
            for i in range(0, len(result)):
                entry = self.safe_dict(result, i)
                entryCodeInteger = self.safe_integer(entry, 'code')
                if entryCodeInteger != 0:
                    errorInArray = True
                    responseCodeString = self.safe_string(entry, 'code')
        if (code != 200) or errorInArray:
            feedback = self.id + ' ' + body
            self.throw_broadly_matched_exception(self.exceptions['broad'], responseCodeString, feedback)
            self.throw_exactly_matched_exception(self.exceptions['exact'], responseCodeString, feedback)
            raise ExchangeError(feedback)
        return None
