# -*- 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.kucoin import kucoin
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import AccountSuspended
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import NotSupported
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import InvalidNonce
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class kucoinfutures(kucoin):

    def describe(self):
        return self.deep_extend(super(kucoinfutures, self).describe(), {
            'id': 'kucoinfutures',
            'name': 'KuCoin Futures',
            'countries': ['SC'],
            'rateLimit': 75,
            'version': 'v1',
            'certified': False,
            'pro': True,
            'comment': 'Platform 2.0',
            'quoteJsonNumbers': False,
            'has': {
                'CORS': None,
                'spot': False,
                'margin': False,
                'swap': True,
                'future': True,
                'option': False,
                'addMargin': True,
                'cancelAllOrders': True,
                'cancelOrder': True,
                'createDepositAddress': True,
                'createOrder': True,
                'createReduceOnlyOrder': True,
                'createStopLimitOrder': True,
                'createStopMarketOrder': True,
                'createStopOrder': True,
                'fetchAccounts': True,
                'fetchBalance': True,
                'fetchBorrowRate': False,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchBorrowRates': False,
                'fetchBorrowRatesPerSymbol': False,
                'fetchClosedOrders': True,
                'fetchCurrencies': False,
                'fetchDepositAddress': True,
                'fetchDeposits': True,
                'fetchDepositWithdrawFee': False,
                'fetchDepositWithdrawFees': False,
                'fetchFundingHistory': True,
                'fetchFundingRate': True,
                'fetchFundingRateHistory': False,
                'fetchIndexOHLCV': False,
                'fetchL3OrderBook': True,
                'fetchLedger': True,
                'fetchLeverageTiers': False,
                'fetchMarginMode': False,
                'fetchMarketLeverageTiers': True,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenOrders': True,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchPositionMode': False,
                'fetchPositions': True,
                'fetchPremiumIndexOHLCV': False,
                'fetchStatus': True,
                'fetchTicker': True,
                'fetchTickers': False,
                'fetchTime': True,
                'fetchTrades': True,
                'fetchTransactionFee': False,
                'fetchWithdrawals': True,
                'setMarginMode': False,
                'transfer': True,
                'withdraw': None,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/147508995-9e35030a-d046-43a1-a006-6fabd981b554.jpg',
                'doc': [
                    'https://docs.kucoin.com/futures',
                    'https://docs.kucoin.com',
                ],
                'www': 'https://futures.kucoin.com/',
                'referral': 'https://futures.kucoin.com/?rcode=E5wkqe',
                'api': {
                    'public': 'https://openapi-v2.kucoin.com',
                    'private': 'https://openapi-v2.kucoin.com',
                    'futuresPrivate': 'https://api-futures.kucoin.com',
                    'futuresPublic': 'https://api-futures.kucoin.com',
                    'webFront': 'https://futures.kucoin.com/_api/web-front',
                },
                'test': {
                    'public': 'https://openapi-sandbox.kucoin.com',
                    'private': 'https://openapi-sandbox.kucoin.com',
                    'futuresPrivate': 'https://api-sandbox-futures.kucoin.com',
                    'futuresPublic': 'https://api-sandbox-futures.kucoin.com',
                },
            },
            'requiredCredentials': {
                'apiKey': True,
                'secret': True,
                'password': True,
            },
            'api': {
                'futuresPublic': {
                    'get': {
                        'contracts/active': 1,
                        'contracts/{symbol}': 1,
                        'contracts/risk-limit/{symbol}': 1,
                        'ticker': 1,
                        'level2/snapshot': 1.33,
                        'level2/depth{limit}': 1,
                        'level2/message/query': 1,
                        'level3/message/query': 1,  # deprecated，level3/snapshot is suggested
                        'level3/snapshot': 1,  # v2
                        'trade/history': 1,
                        'interest/query': 1,
                        'index/query': 1,
                        'mark-price/{symbol}/current': 1,
                        'premium/query': 1,
                        'funding-rate/{symbol}/current': 1,
                        'timestamp': 1,
                        'status': 1,
                        'kline/query': 1,
                    },
                    'post': {
                        'bullet-public': 1,
                    },
                },
                'futuresPrivate': {
                    'get': {
                        'account-overview': 1.33,
                        'transaction-history': 4.44,
                        'deposit-address': 1,
                        'deposit-list': 1,
                        'withdrawals/quotas': 1,
                        'withdrawal-list': 1,
                        'transfer-list': 1,
                        'orders': 1.33,
                        'stopOrders': 1,
                        'recentDoneOrders': 1,
                        'orders/{orderId}': 1,  # ?clientOid={client-order-id}  # get order by orderId
                        'orders/byClientOid': 1,  # ?clientOid=eresc138b21023a909e5ad59  # get order by clientOid
                        'fills': 4.44,
                        'recentFills': 4.44,
                        'openOrderStatistics': 1,
                        'position': 1,
                        'positions': 4.44,
                        'funding-history': 4.44,
                    },
                    'post': {
                        'withdrawals': 1,
                        'transfer-out': 1,  # v2
                        'orders': 1.33,
                        'position/margin/auto-deposit-status': 1,
                        'position/margin/deposit-margin': 1,
                        'bullet-private': 1,
                    },
                    'delete': {
                        'withdrawals/{withdrawalId}': 1,
                        'cancel/transfer-out': 1,
                        'orders/{orderId}': 1,
                        'orders': 4.44,
                        'stopOrders': 1,
                    },
                },
                'webFront': {
                    'get': {
                        'contract/{symbol}/funding-rates': 1,
                    },
                },
            },
            'precisionMode': TICK_SIZE,
            'exceptions': {
                'exact': {
                    '400': BadRequest,  # Bad Request -- Invalid request format
                    '401': AuthenticationError,  # Unauthorized -- Invalid API Key
                    '403': NotSupported,  # Forbidden -- The request is forbidden
                    '404': NotSupported,  # Not Found -- The specified resource could not be found
                    '405': NotSupported,  # Method Not Allowed -- You tried to access the resource with an invalid method.
                    '415': BadRequest,  # Content-Type -- application/json
                    '429': RateLimitExceeded,  # Too Many Requests -- Access limit breached
                    '500': ExchangeNotAvailable,  # Internal Server Error -- We had a problem with our server. Try again later.
                    '503': ExchangeNotAvailable,  # Service Unavailable -- We're temporarily offline for maintenance. Please try again later.
                    '100001': InvalidOrder,     # {"code":"100001","msg":"Unavailable to enable both \"postOnly\" and \"hidden\""}
                    '100004': BadRequest,       # {"code":"100004","msg":"Order is in not cancelable state"}
                    '101030': PermissionDenied,  # {"code":"101030","msg":"You haven't yet enabled the margin trading"}
                    '200004': InsufficientFunds,
                    '230003': InsufficientFunds,  # {"code":"230003","msg":"Balance insufficient!"}
                    '260100': InsufficientFunds,  # {"code":"260100","msg":"account.noBalance"}
                    '300003': InsufficientFunds,
                    '300012': InvalidOrder,
                    '400001': AuthenticationError,  # Any of KC-API-KEY, KC-API-SIGN, KC-API-TIMESTAMP, KC-API-PASSPHRASE is missing in your request header.
                    '400002': InvalidNonce,  # KC-API-TIMESTAMP Invalid -- Time differs from server time by more than 5 seconds
                    '400003': AuthenticationError,  # KC-API-KEY not exists
                    '400004': AuthenticationError,  # KC-API-PASSPHRASE error
                    '400005': AuthenticationError,  # Signature error -- Please check your signature
                    '400006': AuthenticationError,  # The IP address is not in the API whitelist
                    '400007': AuthenticationError,  # Access Denied -- Your API key does not have sufficient permissions to access the URI
                    '404000': NotSupported,  # URL Not Found -- The requested resource could not be found
                    '400100': BadRequest,  # Parameter Error -- You tried to access the resource with invalid parameters
                    '411100': AccountSuspended,  # User is frozen -- Please contact us via support center
                    '500000': ExchangeNotAvailable,  # Internal Server Error -- We had a problem with our server. Try again later.
                },
                'broad': {
                    'Position does not exist': OrderNotFound,  # {"code":"200000", "msg":"Position does not exist"}
                },
            },
            'fees': {
                'trading': {
                    'tierBased': True,
                    'percentage': True,
                    'taker': self.parse_number('0.0006'),
                    'maker': self.parse_number('0.0002'),
                    'tiers': {
                        'taker': [
                            [self.parse_number('0'), self.parse_number('0.0006')],
                            [self.parse_number('50'), self.parse_number('0.0006')],
                            [self.parse_number('200'), self.parse_number('0.0006')],
                            [self.parse_number('500'), self.parse_number('0.0005')],
                            [self.parse_number('1000'), self.parse_number('0.0004')],
                            [self.parse_number('2000'), self.parse_number('0.0004')],
                            [self.parse_number('4000'), self.parse_number('0.00038')],
                            [self.parse_number('8000'), self.parse_number('0.00035')],
                            [self.parse_number('15000'), self.parse_number('0.00032')],
                            [self.parse_number('25000'), self.parse_number('0.0003')],
                            [self.parse_number('40000'), self.parse_number('0.0003')],
                            [self.parse_number('60000'), self.parse_number('0.0003')],
                            [self.parse_number('80000'), self.parse_number('0.0003')],
                        ],
                        'maker': [
                            [self.parse_number('0'), self.parse_number('0.02')],
                            [self.parse_number('50'), self.parse_number('0.015')],
                            [self.parse_number('200'), self.parse_number('0.01')],
                            [self.parse_number('500'), self.parse_number('0.01')],
                            [self.parse_number('1000'), self.parse_number('0.01')],
                            [self.parse_number('2000'), self.parse_number('0')],
                            [self.parse_number('4000'), self.parse_number('0')],
                            [self.parse_number('8000'), self.parse_number('0')],
                            [self.parse_number('15000'), self.parse_number('-0.003')],
                            [self.parse_number('25000'), self.parse_number('-0.006')],
                            [self.parse_number('40000'), self.parse_number('-0.009')],
                            [self.parse_number('60000'), self.parse_number('-0.012')],
                            [self.parse_number('80000'), self.parse_number('-0.015')],
                        ],
                    },
                },
                'funding': {
                    'tierBased': False,
                    'percentage': False,
                    'withdraw': {},
                    'deposit': {},
                },
            },
            'commonCurrencies': {
                'HOT': 'HOTNOW',
                'EDGE': 'DADI',  # https://github.com/ccxt/ccxt/issues/5756
                'WAX': 'WAXP',
                'TRY': 'Trias',
                'VAI': 'VAIOT',
                'XBT': 'BTC',
            },
            'timeframes': {
                '1m': 1,
                '3m': None,
                '5m': 5,
                '15m': 15,
                '30m': 30,
                '1h': 60,
                '2h': 120,
                '4h': 240,
                '6h': None,
                '8h': 480,
                '12h': 720,
                '1d': 1440,
                '1w': 10080,
            },
            'options': {
                'version': 'v1',
                'symbolSeparator': '-',
                'defaultType': 'swap',
                'code': 'USDT',
                'marginModes': {},
                'marginTypes': {},
                # endpoint versions
                'versions': {
                    'futuresPrivate': {
                        'POST': {
                            'transfer-out': 'v2',
                        },
                    },
                    'futuresPublic': {
                        'GET': {
                            'level3/snapshot': 'v2',
                        },
                    },
                },
                'networks': {
                    'OMNI': 'omni',
                    'ERC20': 'eth',
                    'TRC20': 'trx',
                },
                # 'code': 'BTC',
                # 'fetchBalance': {
                #    'code': 'BTC',
                # },
            },
        })

    async def fetch_accounts(self, params={}):
        """
        fetch all the accounts associated with a profile
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: a dictionary of `account structures <https://docs.ccxt.com/en/latest/manual.html#account-structure>` indexed by the account type
        """
        raise BadRequest(self.id + ' fetchAccounts() is not supported yet')

    async def fetch_status(self, params={}):
        """
        the latest known information on the availability of the exchange API
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/en/latest/manual.html#exchange-status-structure>`
        """
        response = await self.futuresPublicGetStatus(params)
        #
        #     {
        #         "code":"200000",
        #         "data":{
        #             "status": "open",  # open, close, cancelonly
        #             "msg": "upgrade match engine"  # remark for operation when status not open
        #         }
        #     }
        #
        data = self.safe_value(response, 'data', {})
        status = self.safe_string(data, 'status')
        return {
            'status': 'ok' if (status == 'open') else 'maintenance',
            'updated': None,
            'eta': None,
            'url': None,
            'info': response,
        }

    async def fetch_markets(self, params={}):
        """
        retrieves data on all markets for kucoinfutures
        :param dict params: extra parameters specific to the exchange api endpoint
        :returns [dict]: an array of objects representing market data
        """
        response = await self.futuresPublicGetContractsActive(params)
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #            "symbol": "ETHUSDTM",
        #            "rootSymbol": "USDT",
        #            "type": "FFWCSX",
        #            "firstOpenDate": 1591086000000,
        #            "expireDate": null,
        #            "settleDate": null,
        #            "baseCurrency": "ETH",
        #            "quoteCurrency": "USDT",
        #            "settleCurrency": "USDT",
        #            "maxOrderQty": 1000000,
        #            "maxPrice": 1000000.0000000000,
        #            "lotSize": 1,
        #            "tickSize": 0.05,
        #            "indexPriceTickSize": 0.01,
        #            "multiplier": 0.01,
        #            "initialMargin": 0.01,
        #            "maintainMargin": 0.005,
        #            "maxRiskLimit": 1000000,
        #            "minRiskLimit": 1000000,
        #            "riskStep": 500000,
        #            "makerFeeRate": 0.00020,
        #            "takerFeeRate": 0.00060,
        #            "takerFixFee": 0.0000000000,
        #            "makerFixFee": 0.0000000000,
        #            "settlementFee": null,
        #            "isDeleverage": True,
        #            "isQuanto": True,
        #            "isInverse": False,
        #            "markMethod": "FairPrice",
        #            "fairMethod": "FundingRate",
        #            "fundingBaseSymbol": ".ETHINT8H",
        #            "fundingQuoteSymbol": ".USDTINT8H",
        #            "fundingRateSymbol": ".ETHUSDTMFPI8H",
        #            "indexSymbol": ".KETHUSDT",
        #            "settlementSymbol": "",
        #            "status": "Open",
        #            "fundingFeeRate": 0.000535,
        #            "predictedFundingFeeRate": 0.002197,
        #            "openInterest": "8724443",
        #            "turnoverOf24h": 341156641.03354263,
        #            "volumeOf24h": 74833.54000000,
        #            "markPrice": 4534.07,
        #            "indexPrice":4531.92,
        #            "lastTradePrice": 4545.4500000000,
        #            "nextFundingRateTime": 25481884,
        #            "maxLeverage": 100,
        #            "sourceExchanges":  ["huobi", "Okex", "Binance", "Kucoin", "Poloniex", "Hitbtc"],
        #            "premiumsSymbol1M": ".ETHUSDTMPI",
        #            "premiumsSymbol8H": ".ETHUSDTMPI8H",
        #            "fundingBaseSymbol1M": ".ETHINT",
        #            "fundingQuoteSymbol1M": ".USDTINT",
        #            "lowPrice": 4456.90,
        #            "highPrice":  4674.25,
        #            "priceChgPct": 0.0046,
        #            "priceChg": 21.15
        #        }
        #    }
        #
        result = []
        data = self.safe_value(response, 'data', [])
        for i in range(0, len(data)):
            market = data[i]
            id = self.safe_string(market, 'symbol')
            expiry = self.safe_integer(market, 'expireDate')
            future = True if expiry else False
            swap = not future
            baseId = self.safe_string(market, 'baseCurrency')
            quoteId = self.safe_string(market, 'quoteCurrency')
            settleId = self.safe_string(market, 'settleCurrency')
            base = self.safe_currency_code(baseId)
            quote = self.safe_currency_code(quoteId)
            settle = self.safe_currency_code(settleId)
            symbol = base + '/' + quote + ':' + settle
            type = 'swap'
            if future:
                symbol = symbol + '-' + self.yymmdd(expiry, '')
                type = 'future'
            inverse = self.safe_value(market, 'isInverse')
            status = self.safe_string(market, 'status')
            multiplier = self.safe_string(market, 'multiplier')
            tickSize = self.safe_number(market, 'tickSize')
            lotSize = self.safe_number(market, 'lotSize')
            limitAmountMin = lotSize
            if limitAmountMin is None:
                limitAmountMin = self.safe_number(market, 'baseMinSize')
            limitAmountMax = self.safe_number(market, 'maxOrderQty')
            if limitAmountMax is None:
                limitAmountMax = self.safe_number(market, 'baseMaxSize')
            limitPriceMax = self.safe_number(market, 'maxPrice')
            if limitPriceMax is None:
                baseMinSizeString = self.safe_string(market, 'baseMinSize')
                quoteMaxSizeString = self.safe_string(market, 'quoteMaxSize')
                limitPriceMax = self.parse_number(Precise.string_div(quoteMaxSizeString, baseMinSizeString))
            result.append({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'settle': settle,
                'baseId': baseId,
                'quoteId': quoteId,
                'settleId': settleId,
                'type': type,
                'spot': False,
                'margin': False,
                'swap': swap,
                'future': future,
                'option': False,
                'active': (status == 'Open'),
                'contract': True,
                'linear': not inverse,
                'inverse': inverse,
                'taker': self.safe_number(market, 'takerFeeRate'),
                'maker': self.safe_number(market, 'makerFeeRate'),
                'contractSize': self.parse_number(Precise.string_abs(multiplier)),
                'expiry': expiry,
                'expiryDatetime': self.iso8601(expiry),
                'strike': None,
                'optionType': None,
                'precision': {
                    'amount': lotSize,
                    'price': tickSize,
                },
                'limits': {
                    'leverage': {
                        'min': self.parse_number('1'),
                        'max': self.safe_number(market, 'maxLeverage'),
                    },
                    'amount': {
                        'min': limitAmountMin,
                        'max': limitAmountMax,
                    },
                    'price': {
                        'min': tickSize,
                        'max': limitPriceMax,
                    },
                    'cost': {
                        'min': self.safe_number(market, 'quoteMinSize'),
                        'max': self.safe_number(market, 'quoteMaxSize'),
                    },
                },
                'info': market,
            })
        return result

    async def fetch_time(self, params={}):
        """
        fetches the current integer timestamp in milliseconds from the exchange server
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        """
        response = await self.futuresPublicGetTimestamp(params)
        #
        #    {
        #        code: "200000",
        #        data: 1637385119302,
        #    }
        #
        return self.safe_number(response, 'data')

    async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
        """
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int|None since: timestamp in ms of the earliest candle to fetch
        :param int|None limit: the maximum amount of candles to fetch
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume
        """
        await self.load_markets()
        market = self.market(symbol)
        marketId = market['id']
        request = {
            'symbol': marketId,
            'granularity': self.safe_integer(self.timeframes, timeframe, timeframe),
        }
        duration = self.parse_timeframe(timeframe) * 1000
        endAt = self.milliseconds()
        if since is not None:
            request['from'] = since
            if limit is None:
                limit = self.safe_integer(self.options, 'fetchOHLCVLimit', 200)
            endAt = self.sum(since, limit * duration)
        elif limit is not None:
            since = endAt - limit * duration
            request['from'] = since
        request['to'] = endAt
        response = await self.futuresPublicGetKlineQuery(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": [
        #            [1636459200000, 4779.3, 4792.1, 4768.7, 4770.3, 78051],
        #            [1636460100000, 4770.25, 4778.55, 4757.55, 4777.25, 80164],
        #            [1636461000000, 4777.25, 4791.45, 4774.5, 4791.3, 51555]
        #        ]
        #    }
        #
        data = self.safe_value(response, 'data', [])
        return self.parse_ohlcvs(data, market, timeframe, since, limit)

    def parse_ohlcv(self, ohlcv, market=None):
        #
        #    [
        #        "1545904980000",          # Start time of the candle cycle
        #        "0.058",                  # opening price
        #        "0.049",                  # closing price
        #        "0.058",                  # highest price
        #        "0.049",                  # lowest price
        #        "0.018",                  # base volume
        #        "0.000945",               # quote volume
        #    ]
        #
        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 create_deposit_address(self, code, params={}):
        """
        create a currency deposit address
        :param str code: unified currency code of the currency for the deposit address
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>`
        """
        raise BadRequest(self.id + ' createDepositAddress() is not supported yet')

    async def fetch_deposit_address(self, code, params={}):
        """
        fetch the deposit address for a currency associated with self account
        :param str code: unified currency code
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>`
        """
        await self.load_markets()
        currency = self.currency(code)
        currencyId = currency['id']
        request = {
            'currency': currencyId,  # Currency,including XBT,USDT
        }
        response = await self.futuresPrivateGetDepositAddress(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #            "address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1",//Deposit address
        #            "memo": null//Address tag. If the returned value is null, it means that the requested token has no memo. If you are to transfer funds from another platform to KuCoin Futures and if the token to be  #transferred has memo(tag), you need to fill in the memo to ensure the transferred funds will be sent  #to the address you specified.
        #        }
        #    }
        #
        data = self.safe_value(response, 'data', {})
        address = self.safe_string(data, 'address')
        if currencyId != 'NIM':
            # contains spaces
            self.check_address(address)
        return {
            'info': response,
            'currency': currencyId,
            'address': address,
            'tag': self.safe_string(data, 'memo'),
            'network': self.safe_string(data, 'chain'),
        }

    async def fetch_order_book(self, symbol, limit=None, params={}):
        """
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str symbol: unified symbol of the market to fetch the order book for
        :param int|None limit: the maximum amount of order book entries to return
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbols
        """
        await self.load_markets()
        level = self.safe_number(params, 'level')
        if level != 2 and level is not None:
            raise BadRequest(self.id + ' fetchOrderBook() can only return level 2')
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            if (limit == 20) or (limit == 100):
                request['limit'] = limit
            else:
                raise BadRequest(self.id + ' fetchOrderBook() limit argument must be 20 or 100')
        else:
            request['limit'] = 20
        response = await self.futuresPublicGetLevel2DepthLimit(self.extend(request, params))
        #
        #     {
        #         "code": "200000",
        #         "data": {
        #           "symbol": "XBTUSDM",      #Symbol
        #           "sequence": 100,          #Ticker sequence number
        #           "asks": [
        #                 ["5000.0", 1000],   #Price, quantity
        #                 ["6000.0", 1983]    #Price, quantity
        #           ],
        #           "bids": [
        #                 ["3200.0", 800],    #Price, quantity
        #                 ["3100.0", 100]     #Price, quantity
        #           ],
        #           "ts": 1604643655040584408  # timestamp
        #         }
        #     }
        #
        data = self.safe_value(response, 'data', {})
        timestamp = int(self.safe_integer(data, 'ts') / 1000000)
        orderbook = self.parse_order_book(data, market['symbol'], timestamp, 'bids', 'asks', 0, 1)
        orderbook['nonce'] = self.safe_integer(data, 'sequence')
        return orderbook

    async def fetch_l3_order_book(self, symbol, limit=None, params={}):
        raise BadRequest(self.id + ' fetchL3OrderBook() is not supported yet')

    async def fetch_ticker(self, symbol, params={}):
        """
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.futuresPublicGetTicker(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #            "sequence": 1638444978558,
        #            "symbol": "ETHUSDTM",
        #            "side": "sell",
        #            "size": 4,
        #            "price": "4229.35",
        #            "bestBidSize": 2160,
        #            "bestBidPrice": "4229.0",
        #            "bestAskPrice": "4229.05",
        #            "tradeId": "61aaa8b777a0c43055fe4851",
        #            "ts": 1638574296209786785,
        #            "bestAskSize": 36,
        #        }
        #    }
        #
        return self.parse_ticker(response['data'], market)

    def parse_ticker(self, ticker, market=None):
        #
        #     {
        #         "code": "200000",
        #         "data": {
        #             "sequence":  1629930362547,
        #             "symbol": "ETHUSDTM",
        #             "side": "buy",
        #             "size":  130,
        #             "price": "4724.7",
        #             "bestBidSize":  5,
        #             "bestBidPrice": "4724.6",
        #             "bestAskPrice": "4724.65",
        #             "tradeId": "618d2a5a77a0c4431d2335f4",
        #             "ts":  1636641371963227600,
        #             "bestAskSize":  1789
        #          }
        #     }
        #
        last = self.safe_string(ticker, 'price')
        marketId = self.safe_string(ticker, 'symbol')
        market = self.safe_market(marketId, market, '-')
        timestamp = self.safe_integer_product(ticker, 'ts', 0.000001)
        return self.safe_ticker({
            'symbol': market['symbol'],
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': None,
            'low': None,
            'bid': self.safe_string(ticker, 'bestBidPrice'),
            'bidVolume': self.safe_string(ticker, 'bestBidSize'),
            'ask': self.safe_string(ticker, 'bestAskPrice'),
            'askVolume': self.safe_string(ticker, 'bestAskSize'),
            'vwap': None,
            'open': None,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': None,
            'percentage': None,
            'average': None,
            'baseVolume': None,
            'quoteVolume': None,
            'info': ticker,
        }, market)

    async def fetch_funding_history(self, symbol=None, since=None, limit=None, params={}):
        """
        fetch the history of funding payments paid and received on self account
        :param str symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch funding history for
        :param int|None limit: the maximum number of funding history structures to retrieve
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: a `funding history structure <https://docs.ccxt.com/en/latest/manual.html#funding-history-structure>`
        """
        #
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchFundingHistory() requires a symbol argument')
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if since is not None:
            request['startAt'] = since
        if limit is not None:
            # * Since is ignored if limit is defined
            request['maxCount'] = limit
        response = await self.futuresPrivateGetFundingHistory(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #            "dataList": [
        #                {
        #                    "id": 239471298749817,
        #                    "symbol": "ETHUSDTM",
        #                    "timePoint": 1638532800000,
        #                    "fundingRate": 0.000100,
        #                    "markPrice": 4612.8300000000,
        #                    "positionQty": 12,
        #                    "positionCost": 553.5396000000,
        #                    "funding": -0.0553539600,
        #                    "settleCurrency": "USDT"
        #                },
        #                ...
        #            ],
        #            "hasMore": True
        #        }
        #    }
        #
        data = self.safe_value(response, 'data')
        dataList = self.safe_value(data, 'dataList', [])
        fees = []
        for i in range(0, len(dataList)):
            listItem = dataList[i]
            timestamp = self.safe_integer(listItem, 'timePoint')
            fees.append({
                'info': listItem,
                'symbol': symbol,
                'code': self.safe_currency_code(self.safe_string(listItem, 'settleCurrency')),
                'timestamp': timestamp,
                'datetime': self.iso8601(timestamp),
                'id': self.safe_number(listItem, 'id'),
                'amount': self.safe_number(listItem, 'funding'),
                'fundingRate': self.safe_number(listItem, 'fundingRate'),
                'markPrice': self.safe_number(listItem, 'markPrice'),
                'positionQty': self.safe_number(listItem, 'positionQty'),
                'positionCost': self.safe_number(listItem, 'positionCost'),
            })
        return fees

    async def fetch_positions(self, symbols=None, params={}):
        """
        fetch all open positions
        :param [str]|None symbols: list of unified market symbols
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns [dict]: a list of `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        """
        await self.load_markets()
        response = await self.futuresPrivateGetPositions(params)
        #
        #    {
        #        "code": "200000",
        #        "data": [
        #            {
        #                "id": "615ba79f83a3410001cde321",
        #                "symbol": "ETHUSDTM",
        #                "autoDeposit": False,
        #                "maintMarginReq": 0.005,
        #                "riskLimit": 1000000,
        #                "realLeverage": 18.61,
        #                "crossMode": False,
        #                "delevPercentage": 0.86,
        #                "openingTimestamp": 1638563515618,
        #                "currentTimestamp": 1638576872774,
        #                "currentQty": 2,
        #                "currentCost": 83.64200000,
        #                "currentComm": 0.05018520,
        #                "unrealisedCost": 83.64200000,
        #                "realisedGrossCost": 0.00000000,
        #                "realisedCost": 0.05018520,
        #                "isOpen": True,
        #                "markPrice": 4225.01,
        #                "markValue": 84.50020000,
        #                "posCost": 83.64200000,
        #                "posCross": 0.0000000000,
        #                "posInit": 3.63660870,
        #                "posComm": 0.05236717,
        #                "posLoss": 0.00000000,
        #                "posMargin": 3.68897586,
        #                "posMaint": 0.50637594,
        #                "maintMargin": 4.54717586,
        #                "realisedGrossPnl": 0.00000000,
        #                "realisedPnl": -0.05018520,
        #                "unrealisedPnl": 0.85820000,
        #                "unrealisedPnlPcnt": 0.0103,
        #                "unrealisedRoePcnt": 0.2360,
        #                "avgEntryPrice": 4182.10,
        #                "liquidationPrice": 4023.00,
        #                "bankruptPrice": 4000.25,
        #                "settleCurrency": "USDT",
        #                "isInverse": False
        #            }
        #        ]
        #    }
        #
        data = self.safe_value(response, 'data')
        return self.parse_positions(data, symbols)

    def parse_position(self, position, market=None):
        #
        #    {
        #        "code": "200000",
        #        "data": [
        #            {
        #                "id": "615ba79f83a3410001cde321",         # Position ID
        #                "symbol": "ETHUSDTM",                     # Symbol
        #                "autoDeposit": False,                     # Auto deposit margin or not
        #                "maintMarginReq": 0.005,                  # Maintenance margin requirement
        #                "riskLimit": 1000000,                     # Risk limit
        #                "realLeverage": 25.92,                    # Leverage of the order
        #                "crossMode": False,                       # Cross mode or not
        #                "delevPercentage": 0.76,                  # ADL ranking percentile
        #                "openingTimestamp": 1638578546031,        # Open time
        #                "currentTimestamp": 1638578563580,        # Current timestamp
        #                "currentQty": 2,                          # Current postion quantity
        #                "currentCost": 83.787,                    # Current postion value
        #                "currentComm": 0.0167574,                 # Current commission
        #                "unrealisedCost": 83.787,                 # Unrealised value
        #                "realisedGrossCost": 0.0,                 # Accumulated realised gross profit value
        #                "realisedCost": 0.0167574,                # Current realised position value
        #                "isOpen": True,                           # Opened position or not
        #                "markPrice": 4183.38,                     # Mark price
        #                "markValue": 83.6676,                     # Mark value
        #                "posCost": 83.787,                        # Position value
        #                "posCross": 0.0,                          # added margin
        #                "posInit": 3.35148,                       # Leverage margin
        #                "posComm": 0.05228309,                    # Bankruptcy cost
        #                "posLoss": 0.0,                           # Funding fees paid out
        #                "posMargin": 3.40376309,                  # Position margin
        #                "posMaint": 0.50707892,                   # Maintenance margin
        #                "maintMargin": 3.28436309,                # Position margin
        #                "realisedGrossPnl": 0.0,                  # Accumulated realised gross profit value
        #                "realisedPnl": -0.0167574,                # Realised profit and loss
        #                "unrealisedPnl": -0.1194,                 # Unrealised profit and loss
        #                "unrealisedPnlPcnt": -0.0014,             # Profit-loss ratio of the position
        #                "unrealisedRoePcnt": -0.0356,             # Rate of return on investment
        #                "avgEntryPrice": 4189.35,                 # Average entry price
        #                "liquidationPrice": 4044.55,              # Liquidation price
        #                "bankruptPrice": 4021.75,                 # Bankruptcy price
        #                "settleCurrency": "USDT",                 # Currency used to clear and settle the trades
        #                "isInverse": False
        #            }
        #        ]
        #    }
        #
        symbol = self.safe_string(position, 'symbol')
        market = self.safe_market(symbol, market)
        timestamp = self.safe_number(position, 'currentTimestamp')
        size = self.safe_string(position, 'currentQty')
        side = None
        if Precise.string_gt(size, '0'):
            side = 'long'
        elif Precise.string_lt(size, '0'):
            side = 'short'
        notional = Precise.string_abs(self.safe_string(position, 'posCost'))
        initialMargin = self.safe_string(position, 'posInit')
        initialMarginPercentage = Precise.string_div(initialMargin, notional)
        # marginRatio = Precise.string_div(maintenanceRate, collateral)
        unrealisedPnl = self.safe_string(position, 'unrealisedPnl')
        crossMode = self.safe_value(position, 'crossMode')
        # currently crossMode is always set to False and only isolated positions are supported
        marginMode = 'cross' if crossMode else 'isolated'
        return {
            'info': position,
            'id': None,
            'symbol': self.safe_string(market, 'symbol'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'initialMargin': self.parse_number(initialMargin),
            'initialMarginPercentage': self.parse_number(initialMarginPercentage),
            'maintenanceMargin': self.safe_number(position, 'posMaint'),
            'maintenanceMarginPercentage': self.safe_number(position, 'maintMarginReq'),
            'entryPrice': self.safe_number(position, 'avgEntryPrice'),
            'notional': self.parse_number(notional),
            'leverage': self.safe_number(position, 'realLeverage'),
            'unrealizedPnl': self.parse_number(unrealisedPnl),
            'contracts': self.parse_number(Precise.string_abs(size)),
            'contractSize': self.safe_value(market, 'contractSize'),
            #     realisedPnl: position['realised_pnl'],
            'marginRatio': None,
            'liquidationPrice': self.safe_number(position, 'liquidationPrice'),
            'markPrice': self.safe_number(position, 'markPrice'),
            'collateral': self.safe_number(position, 'maintMargin'),
            'marginMode': marginMode,
            'side': side,
            'percentage': self.parse_number(Precise.string_div(unrealisedPnl, initialMargin)),
        }

    async def create_order(self, symbol, type, side, amount, price=None, params={}):
        """
        Create an order on the exchange
        see https://docs.kucoin.com/futures/#place-an-order
        :param str symbol: Unified CCXT market symbol
        :param str type: 'limit' or 'market'
        :param str side: 'buy' or 'sell'
        :param float amount: the amount of currency to trade
        :param float price: *ignored in "market" orders* the price at which the order is to be fullfilled at in units of the quote currency
        :param dict params:  Extra parameters specific to the exchange API endpoint
        :param float params['triggerPrice']: The price a trigger order is triggered at
        :param float params['stopLossPrice']: price to trigger stop-loss orders
        :param float params['takeProfitPrice']: price to trigger take-profit orders
        :param bool params['reduceOnly']: A mark to reduce the position size only. Set to False by default. Need to set the position size when reduceOnly is True.
        :param str params['timeInForce']: GTC, GTT, IOC, or FOK, default is GTC, limit orders only
        :param str params['postOnly']: Post only flag, invalid when timeInForce is IOC or FOK
         * ----------------- Exchange Specific Parameters -----------------
        :param float params['leverage']: Leverage size of the order
        :param str params['clientOid']: client order id, defaults to uuid if not passed
        :param str params['remark']: remark for the order, length cannot exceed 100 utf8 characters
        :param str params['stop']: 'up' or 'down', the direction the stopPrice is triggered from, requires stopPrice. down: Triggers when the price reaches or goes below the stopPrice. up: Triggers when the price reaches or goes above the stopPrice.
        :param str params['stopPriceType']:  TP, IP or MP, defaults to MP: Mark Price
        :param bool params['closeOrder']: set to True to close position
        :param bool params['forceHold']: A mark to forcely hold the funds for an order, even though it's an order to reduce the position size. This helps the order stay on the order book and not get canceled when the position size changes. Set to False by default.
        :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        # required param, cannot be used twice
        clientOrderId = self.safe_string_2(params, 'clientOid', 'clientOrderId', self.uuid())
        params = self.omit(params, ['clientOid', 'clientOrderId'])
        if amount < 1:
            raise InvalidOrder(self.id + ' createOrder() minimum contract order amount is 1')
        preciseAmount = int(self.amount_to_precision(symbol, amount))
        request = {
            'clientOid': clientOrderId,
            'side': side,
            'symbol': market['id'],
            'type': type,  # limit or market
            'size': preciseAmount,
            'leverage': 1,
        }
        stopPrice = self.safe_value_2(params, 'triggerPrice', 'stopPrice')
        stopLossPrice = self.safe_value(params, 'stopLossPrice')
        takeProfitPrice = self.safe_value(params, 'takeProfitPrice')
        isStopLoss = stopLossPrice is not None
        isTakeProfit = takeProfitPrice is not None
        if stopPrice:
            request['stop'] = 'up' if (side == 'buy') else 'down'
            request['stopPrice'] = self.price_to_precision(symbol, stopPrice)
            request['stopPriceType'] = 'MP'
        elif isStopLoss or isTakeProfit:
            if isStopLoss:
                request['stop'] = 'up' if (side == 'buy') else 'down'
                request['stopPrice'] = self.price_to_precision(symbol, stopLossPrice)
            else:
                request['stop'] = 'down' if (side == 'buy') else 'up'
                request['stopPrice'] = self.price_to_precision(symbol, takeProfitPrice)
            request['reduceOnly'] = True
            request['stopPriceType'] = 'MP'
        uppercaseType = type.upper()
        timeInForce = self.safe_string_upper(params, 'timeInForce')
        if uppercaseType == 'LIMIT':
            if price is None:
                raise ArgumentsRequired(self.id + ' createOrder() requires a price argument for limit orders')
            else:
                request['price'] = self.price_to_precision(symbol, price)
            if timeInForce is not None:
                request['timeInForce'] = timeInForce
        postOnly = self.safe_value(params, 'postOnly', False)
        hidden = self.safe_value(params, 'hidden')
        if postOnly and (hidden is not None):
            raise BadRequest(self.id + ' createOrder() does not support the postOnly parameter together with a hidden parameter')
        iceberg = self.safe_value(params, 'iceberg')
        if iceberg:
            visibleSize = self.safe_value(params, 'visibleSize')
            if visibleSize is None:
                raise ArgumentsRequired(self.id + ' createOrder() requires a visibleSize parameter for iceberg orders')
        params = self.omit(params, ['timeInForce', 'stopPrice', 'triggerPrice', 'stopLossPrice', 'takeProfitPrice'])  # Time in force only valid for limit orders, exchange error when gtc for market orders
        response = await self.futuresPrivatePostOrders(self.extend(request, params))
        #
        #    {
        #        code: "200000",
        #        data: {
        #            orderId: "619717484f1d010001510cde",
        #        },
        #    }
        #
        data = self.safe_value(response, 'data', {})
        return {
            'id': self.safe_string(data, 'orderId'),
            'clientOrderId': None,
            'timestamp': None,
            'datetime': None,
            'lastTradeTimestamp': None,
            'symbol': None,
            'type': None,
            'side': None,
            'price': None,
            'amount': None,
            'cost': None,
            'average': None,
            'filled': None,
            'remaining': None,
            'status': None,
            'fee': None,
            'trades': None,
            'timeInForce': None,
            'postOnly': None,
            'stopPrice': None,
            'triggerPrice': None,
            'info': response,
        }

    async def cancel_order(self, id, symbol=None, params={}):
        """
        cancels an open order
        :param str id: order id
        :param str|None symbol: unified symbol of the market the order was made in
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        request = {
            'orderId': id,
        }
        response = await self.futuresPrivateDeleteOrdersOrderId(self.extend(request, params))
        #
        #   {
        #       code: "200000",
        #       data: {
        #           cancelledOrderIds: [
        #                "619714b8b6353000014c505a",
        #           ],
        #       },
        #   }
        #
        return self.safe_value(response, 'data')

    async def cancel_all_orders(self, symbol=None, params={}):
        """
        cancel all open orders
        :param str|None symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :param dict params['stop']: When True, all the trigger orders will be cancelled
        :returns: Response from the exchange
        """
        await self.load_markets()
        request = {}
        if symbol is not None:
            request['symbol'] = self.market_id(symbol)
        stop = self.safe_value(params, 'stop')
        method = 'futuresPrivateDeleteStopOrders' if stop else 'futuresPrivateDeleteOrders'
        response = await getattr(self, method)(self.extend(request, params))
        #
        #   {
        #       code: "200000",
        #       data: {
        #           cancelledOrderIds: [
        #                "619714b8b6353000014c505a",
        #           ],
        #       },
        #   }
        #
        return self.safe_value(response, 'data')

    async def add_margin(self, symbol, amount, params={}):
        """
        add margin
        :param str symbol: unified market symbol
        :param float amount: amount of margin to add
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/en/latest/manual.html#add-margin-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        uuid = self.uuid()
        request = {
            'symbol': market['id'],
            'margin': self.amount_to_precision(symbol, amount),
            'bizNo': uuid,
        }
        response = await self.futuresPrivatePostPositionMarginDepositMargin(self.extend(request, params))
        #
        #    {
        #        code: '200000',
        #        data: {
        #            id: '62311d26064e8f00013f2c6d',
        #            symbol: 'XRPUSDTM',
        #            autoDeposit: False,
        #            maintMarginReq: 0.01,
        #            riskLimit: 200000,
        #            realLeverage: 0.88,
        #            crossMode: False,
        #            delevPercentage: 0.4,
        #            openingTimestamp: 1647385894798,
        #            currentTimestamp: 1647414510672,
        #            currentQty: -1,
        #            currentCost: -7.658,
        #            currentComm: 0.0053561,
        #            unrealisedCost: -7.658,
        #            realisedGrossCost: 0,
        #            realisedCost: 0.0053561,
        #            isOpen: True,
        #            markPrice: 0.7635,
        #            markValue: -7.635,
        #            posCost: -7.658,
        #            posCross: 1.00016084,
        #            posInit: 7.658,
        #            posComm: 0.00979006,
        #            posLoss: 0,
        #            posMargin: 8.6679509,
        #            posMaint: 0.08637006,
        #            maintMargin: 8.6909509,
        #            realisedGrossPnl: 0,
        #            realisedPnl: -0.0038335,
        #            unrealisedPnl: 0.023,
        #            unrealisedPnlPcnt: 0.003,
        #            unrealisedRoePcnt: 0.003,
        #            avgEntryPrice: 0.7658,
        #            liquidationPrice: 1.6239,
        #            bankruptPrice: 1.6317,
        #            settleCurrency: 'USDT'
        #        }
        #    }
        #
        #
        #    {
        #        "code":"200000",
        #        "msg":"Position does not exist"
        #    }
        #
        data = self.safe_value(response, 'data')
        return self.extend(self.parse_margin_modification(data, market), {
            'amount': self.amount_to_precision(symbol, amount),
            'direction': 'in',
        })

    def parse_margin_modification(self, info, market=None):
        #
        #    {
        #        id: '62311d26064e8f00013f2c6d',
        #        symbol: 'XRPUSDTM',
        #        autoDeposit: False,
        #        maintMarginReq: 0.01,
        #        riskLimit: 200000,
        #        realLeverage: 0.88,
        #        crossMode: False,
        #        delevPercentage: 0.4,
        #        openingTimestamp: 1647385894798,
        #        currentTimestamp: 1647414510672,
        #        currentQty: -1,
        #        currentCost: -7.658,
        #        currentComm: 0.0053561,
        #        unrealisedCost: -7.658,
        #        realisedGrossCost: 0,
        #        realisedCost: 0.0053561,
        #        isOpen: True,
        #        markPrice: 0.7635,
        #        markValue: -7.635,
        #        posCost: -7.658,
        #        posCross: 1.00016084,
        #        posInit: 7.658,
        #        posComm: 0.00979006,
        #        posLoss: 0,
        #        posMargin: 8.6679509,
        #        posMaint: 0.08637006,
        #        maintMargin: 8.6909509,
        #        realisedGrossPnl: 0,
        #        realisedPnl: -0.0038335,
        #        unrealisedPnl: 0.023,
        #        unrealisedPnlPcnt: 0.003,
        #        unrealisedRoePcnt: 0.003,
        #        avgEntryPrice: 0.7658,
        #        liquidationPrice: 1.6239,
        #        bankruptPrice: 1.6317,
        #        settleCurrency: 'USDT'
        #    }
        #
        #    {
        #        "code":"200000",
        #        "msg":"Position does not exist"
        #    }
        #
        id = self.safe_string(info, 'id')
        market = self.safe_market(id, market)
        currencyId = self.safe_string(info, 'settleCurrency')
        crossMode = self.safe_value(info, 'crossMode')
        mode = 'cross' if crossMode else 'isolated'
        marketId = self.safe_string(market, 'symbol')
        return {
            'info': info,
            'direction': None,
            'mode': mode,
            'amount': None,
            'code': self.safe_currency_code(currencyId),
            'symbol': self.safe_symbol(marketId, market),
            'status': None,
        }

    async def fetch_orders_by_status(self, status, symbol=None, since=None, limit=None, params={}):
        """
        fetches a list of orders placed on the exchange
        :param str status: 'active' or 'closed', only 'active' is valid for stop orders
        :param str|None symbol: unified symbol for the market to retrieve orders from
        :param int|None since: timestamp in ms of the earliest order to retrieve
        :param int|None limit: The maximum number of orders to retrieve
        :param dict params: exchange specific parameters
        :param bool|None params['stop']: set to True to retrieve untriggered stop orders
        :param int|None params['until']: End time in ms
        :param str|None params['side']: buy or sell
        :param str|None params['type']: limit or market
        :returns: An `array of order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        stop = self.safe_value(params, 'stop')
        until = self.safe_integer_2(params, 'until', 'till')
        params = self.omit(params, ['stop', 'until', 'till'])
        if status == 'closed':
            status = 'done'
        elif status == 'open':
            status = 'active'
        request = {}
        if not stop:
            request['status'] = status
        elif status != 'active':
            raise BadRequest(self.id + ' fetchOrdersByStatus() can only fetch untriggered stop orders')
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            request['startAt'] = since
        if until is not None:
            request['endAt'] = until
        method = 'futuresPrivateGetStopOrders' if stop else 'futuresPrivateGetOrders'
        response = await getattr(self, method)(self.extend(request, params))
        responseData = self.safe_value(response, 'data', {})
        orders = self.safe_value(responseData, 'items', [])
        return self.parse_orders(orders, market, since, limit)

    async def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches information on multiple closed orders made by the user
        :param str|None symbol: unified market symbol of the market orders were made in
        :param int|None since: the earliest time in ms to fetch orders for
        :param int|None limit: the maximum number of  orde structures to retrieve
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :param int|None params['till']: end time in ms
        :param str|None params['side']: buy or sell
        :param str|None params['type']: limit, or market
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        return await self.fetch_orders_by_status('done', symbol, since, limit, params)

    async def fetch_order(self, id=None, symbol=None, params={}):
        """
        fetches information on an order made by the user
        :param str|None symbol: unified symbol of the market the order was made in
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        request = {}
        method = 'futuresPrivateGetOrdersOrderId'
        if id is None:
            clientOrderId = self.safe_string_2(params, 'clientOid', 'clientOrderId')
            if clientOrderId is None:
                raise InvalidOrder(self.id + ' fetchOrder() requires parameter id or params.clientOid')
            request['clientOid'] = clientOrderId
            method = 'futuresPrivateGetOrdersByClientOid'
            params = self.omit(params, ['clientOid', 'clientOrderId'])
        else:
            request['orderId'] = id
        response = await getattr(self, method)(self.extend(request, params))
        market = self.market(symbol) if (symbol is not None) else None
        responseData = self.safe_value(response, 'data')
        return self.parse_order(responseData, market)

    def parse_order(self, order, market=None):
        marketId = self.safe_string(order, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        orderId = self.safe_string(order, 'id')
        type = self.safe_string(order, 'type')
        timestamp = self.safe_integer(order, 'createdAt')
        datetime = self.iso8601(timestamp)
        price = self.safe_string(order, 'price')
        # price is zero for market order
        # omitZero is called in safeOrder2
        side = self.safe_string(order, 'side')
        feeCurrencyId = self.safe_string(order, 'feeCurrency')
        feeCurrency = self.safe_currency_code(feeCurrencyId)
        feeCost = self.safe_number(order, 'fee')
        amount = self.safe_string(order, 'size')
        filled = self.safe_string(order, 'dealSize')
        rawCost = self.safe_string_2(order, 'dealFunds', 'filledValue')
        leverage = self.safe_string(order, 'leverage')
        cost = Precise.string_div(rawCost, leverage)
        average = None
        if Precise.string_gt(filled, '0'):
            contractSize = self.safe_string(market, 'contractSize')
            if market['linear']:
                average = Precise.string_div(rawCost, Precise.string_mul(contractSize, filled))
            else:
                average = Precise.string_div(Precise.string_mul(contractSize, filled), rawCost)
        # precision reported by their api is 8 d.p.
        # average = Precise.string_div(rawCost, Precise.string_mul(filled, market['contractSize']))
        # bool
        isActive = self.safe_value(order, 'isActive', False)
        cancelExist = self.safe_value(order, 'cancelExist', False)
        status = 'open' if isActive else 'closed'
        status = 'canceled' if cancelExist else status
        fee = {
            'currency': feeCurrency,
            'cost': feeCost,
        }
        clientOrderId = self.safe_string(order, 'clientOid')
        timeInForce = self.safe_string(order, 'timeInForce')
        stopPrice = self.safe_number(order, 'stopPrice')
        postOnly = self.safe_value(order, 'postOnly')
        return self.safe_order({
            'id': orderId,
            'clientOrderId': clientOrderId,
            'symbol': symbol,
            'type': type,
            'timeInForce': timeInForce,
            'postOnly': postOnly,
            'side': side,
            'amount': amount,
            'price': price,
            'stopPrice': stopPrice,
            'triggerPrice': stopPrice,
            'cost': cost,
            'filled': filled,
            'remaining': None,
            'timestamp': timestamp,
            'datetime': datetime,
            'fee': fee,
            'status': status,
            'info': order,
            'lastTradeTimestamp': None,
            'average': average,
            'trades': None,
        }, market)

    async def fetch_funding_rate(self, symbol, params={}):
        """
        fetch the current funding rate
        :param str symbol: unified market symbol
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/en/latest/manual.html#funding-rate-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.futuresPublicGetFundingRateSymbolCurrent(self.extend(request, params))
        #
        #    {
        #        code: "200000",
        #        data: {
        #            symbol: ".ETHUSDTMFPI8H",
        #            granularity: 28800000,
        #            timePoint: 1637380800000,
        #            value: 0.0001,
        #            predictedValue: 0.0001,
        #        },
        #    }
        #
        data = self.safe_value(response, 'data')
        fundingTimestamp = self.safe_number(data, 'timePoint')
        # the website displayes the previous funding rate as "funding rate"
        return {
            'info': data,
            'symbol': market['symbol'],
            'markPrice': None,
            'indexPrice': None,
            'interestRate': None,
            'estimatedSettlePrice': None,
            'timestamp': None,
            'datetime': None,
            'fundingRate': self.safe_number(data, 'predictedValue'),
            'fundingTimestamp': None,
            'fundingDatetime': None,
            'nextFundingRate': None,
            'nextFundingTimestamp': None,
            'nextFundingDatetime': None,
            'previousFundingRate': self.safe_number(data, 'value'),
            'previousFundingTimestamp': fundingTimestamp,
            'previousFundingDatetime': self.iso8601(fundingTimestamp),
        }

    def parse_balance(self, response):
        result = {
            'info': response,
            'timestamp': None,
            'datetime': None,
        }
        data = self.safe_value(response, 'data')
        currencyId = self.safe_string(data, 'currency')
        code = self.safe_currency_code(currencyId)
        account = self.account()
        account['free'] = self.safe_string(data, 'availableBalance')
        account['total'] = self.safe_string(data, 'accountEquity')
        result[code] = account
        return self.safe_balance(result)

    async def fetch_balance(self, params={}):
        """
        query for balance and get the amount of funds available for trading or funds locked in orders
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>`
        """
        await self.load_markets()
        # only fetches one balance at a time
        defaultCode = self.safe_string(self.options, 'code')
        fetchBalanceOptions = self.safe_value(self.options, 'fetchBalance', {})
        defaultCode = self.safe_string(fetchBalanceOptions, 'code', defaultCode)
        code = self.safe_string(params, 'code', defaultCode)
        currency = self.currency(code)
        request = {
            'currency': currency['id'],
        }
        response = await self.futuresPrivateGetAccountOverview(self.extend(request, params))
        #
        #     {
        #         code: '200000',
        #         data: {
        #             accountEquity: 0.00005,
        #             unrealisedPNL: 0,
        #             marginBalance: 0.00005,
        #             positionMargin: 0,
        #             orderMargin: 0,
        #             frozenFunds: 0,
        #             availableBalance: 0.00005,
        #             currency: 'XBT'
        #         }
        #     }
        #
        return self.parse_balance(response)

    async def transfer(self, code, amount, fromAccount, toAccount, params={}):
        """
        transfer currency internally between wallets on the same account
        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account to transfer from
        :param str toAccount: account to transfer to
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: a `transfer structure <https://docs.ccxt.com/en/latest/manual.html#transfer-structure>`
        """
        if (toAccount != 'main' and toAccount != 'funding') or (fromAccount != 'futures' and fromAccount != 'future' and fromAccount != 'contract'):
            raise BadRequest(self.id + ' transfer() only supports transfers from contract(future) account to main(funding) account')
        await self.load_markets()
        currency = self.currency(code)
        amountToPrecision = self.currency_to_precision(code, amount)
        request = {
            'currency': self.safe_string(currency, 'id'),  # Currency,including XBT,USDT
            'amount': amountToPrecision,
        }
        # transfer from usdm futures wallet to spot wallet
        response = await self.futuresPrivatePostTransferOut(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #            "applyId": "5bffb63303aa675e8bbe18f9"  # Transfer-out request ID
        #        }
        #    }
        #
        data = self.safe_value(response, 'data')
        return self.extend(self.parse_transfer(data, currency), {
            'amount': self.parse_number(amountToPrecision),
            'fromAccount': 'future',
            'toAccount': 'spot',
        })

    def parse_transfer(self, transfer, currency=None):
        #
        # transfer
        #
        #     {
        #            "applyId": "5bffb63303aa675e8bbe18f9"  # Transfer-out request ID
        #     }
        #
        timestamp = self.safe_integer(transfer, 'updatedAt')
        return {
            'id': self.safe_string(transfer, 'applyId'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'currency': self.safe_currency_code(None, currency),
            'amount': None,
            'fromAccount': None,
            'toAccount': None,
            'status': self.safe_string(transfer, 'status'),
            'info': transfer,
        }

    def parse_transfer_status(self, status):
        statuses = {
            'PROCESSING': 'pending',
        }
        return self.safe_string(statuses, status, status)

    async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
        """
        fetch all trades made by the user
        :param str|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch trades for
        :param int|None limit: the maximum number of trades structures to retrieve
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
        """
        await self.load_markets()
        request = {
            # orderId(str) [optional] Fills for a specific order(other parameters can be ignored if specified)
            # symbol(str) [optional] Symbol of the contract
            # side(str) [optional] buy or sell
            # type(str) [optional] limit, market, limit_stop or market_stop
            # startAt(long) [optional] Start time(milisecond)
            # endAt(long) [optional] End time(milisecond)
        }
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            request['startAt'] = since
        response = await self.futuresPrivateGetFills(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #          "currentPage": 1,
        #          "pageSize": 1,
        #          "totalNum": 251915,
        #          "totalPage": 251915,
        #          "items": [
        #              {
        #                  "symbol": "XBTUSDM",  # Ticker symbol of the contract
        #                  "tradeId": "5ce24c1f0c19fc3c58edc47c",  # Trade ID
        #                  "orderId": "5ce24c16b210233c36ee321d",  # Order ID
        #                  "side": "sell",  # Transaction side
        #                  "liquidity": "taker",  # Liquidity- taker or maker
        #                  "price": "8302",  # Filled price
        #                  "size": 10,  # Filled amount
        #                  "value": "0.001204529",  # Order value
        #                  "feeRate": "0.0005",  # Floating fees
        #                  "fixFee": "0.00000006",  # Fixed fees
        #                  "feeCurrency": "XBT",  # Charging currency
        #                  "stop": "",  # A mark to the stop order type
        #                  "fee": "0.0000012022",  # Transaction fee
        #                  "orderType": "limit",  # Order type
        #                  "tradeType": "trade",  # Trade type(trade, liquidation, ADL or settlement)
        #                  "createdAt": 1558334496000,  # Time the order created
        #                  "settleCurrency": "XBT",  # settlement currency
        #                  "tradeTime": 1558334496000000000  # trade time in nanosecond
        #              }
        #            ]
        #        }
        #    }
        #
        data = self.safe_value(response, 'data', {})
        trades = self.safe_value(data, 'items', {})
        return self.parse_trades(trades, market, since, limit)

    async def fetch_trades(self, symbol, since=None, limit=None, params={}):
        """
        get the list of most recent trades for a particular symbol
        :param str symbol: unified symbol of the market to fetch trades for
        :param int|None since: timestamp in ms of the earliest trade to fetch
        :param int|None limit: the maximum amount of trades to fetch
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html?#public-trades>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.futuresPublicGetTradeHistory(self.extend(request, params))
        #
        #      {
        #          "code": "200000",
        #          "data": [
        #              {
        #                  "sequence": 32114961,
        #                  "side": "buy",
        #                  "size": 39,
        #                  "price": "4001.6500000000",
        #                  "takerOrderId": "61c20742f172110001e0ebe4",
        #                  "makerOrderId": "61c2073fcfc88100010fcb5d",
        #                  "tradeId": "61c2074277a0c473e69029b8",
        #                  "ts": 1640105794099993896   # filled time
        #              }
        #          ]
        #      }
        #
        trades = self.safe_value(response, 'data', [])
        return self.parse_trades(trades, market, since, limit)

    def parse_trade(self, trade, market=None):
        #
        # fetchTrades(public)
        #
        #     {
        #         "sequence": 32114961,
        #         "side": "buy",
        #         "size": 39,
        #         "price": "4001.6500000000",
        #         "takerOrderId": "61c20742f172110001e0ebe4",
        #         "makerOrderId": "61c2073fcfc88100010fcb5d",
        #         "tradeId": "61c2074277a0c473e69029b8",
        #         "ts": 1640105794099993896   # filled time
        #     }
        #
        # fetchMyTrades(private) v2
        #
        #     {
        #         "symbol":"BTC-USDT",
        #         "tradeId":"5c35c02709e4f67d5266954e",
        #         "orderId":"5c35c02703aa673ceec2a168",
        #         "counterOrderId":"5c1ab46003aa676e487fa8e3",
        #         "side":"buy",
        #         "liquidity":"taker",
        #         "forceTaker":true,
        #         "price":"0.083",
        #         "size":"0.8424304",
        #         "funds":"0.0699217232",
        #         "fee":"0",
        #         "feeRate":"0",
        #         "feeCurrency":"USDT",
        #         "stop":"",
        #         "type":"limit",
        #         "createdAt":1547026472000
        #     }
        #
        # fetchMyTrades(private) v1
        #
        #    {
        #        "symbol":"DOGEUSDTM",
        #        "tradeId":"620ec41a96bab27b5f4ced56",
        #        "orderId":"620ec41a0d1d8a0001560bd0",
        #        "side":"sell",
        #        "liquidity":"taker",
        #        "forceTaker":true,
        #        "price":"0.13969",
        #        "size":1,
        #        "value":"13.969",
        #        "feeRate":"0.0006",
        #        "fixFee":"0",
        #        "feeCurrency":"USDT",
        #        "stop":"",
        #        "tradeTime":1645134874858018058,
        #        "fee":"0.0083814",
        #        "settleCurrency":"USDT",
        #        "orderType":"market",
        #        "tradeType":"trade",
        #        "createdAt":1645134874858
        #    }
        #
        # watchTrades
        #
        #    {
        #        makerUserId: '62286a4d720edf0001e81961',
        #        symbol: 'ADAUSDTM',
        #        sequence: 41320766,
        #        side: 'sell',
        #        size: 2,
        #        price: 0.35904,
        #        takerOrderId: '636dd9da9857ba00010cfa44',
        #        makerOrderId: '636dd9c8df149d0001e62bc8',
        #        takerUserId: '6180be22b6ab210001fa3371',
        #        tradeId: '636dd9da0000d400d477eca7',
        #        ts: 1668143578987357700
        #    }
        #
        marketId = self.safe_string(trade, 'symbol')
        market = self.safe_market(marketId, market, '-')
        id = self.safe_string_2(trade, 'tradeId', 'id')
        orderId = self.safe_string(trade, 'orderId')
        takerOrMaker = self.safe_string(trade, 'liquidity')
        timestamp = self.safe_integer(trade, 'ts')
        if timestamp is not None:
            timestamp = int(timestamp / 1000000)
        else:
            timestamp = self.safe_integer(trade, 'createdAt')
            # if it's a historical v1 trade, the exchange returns timestamp in seconds
            if ('dealValue' in trade) and (timestamp is not None):
                timestamp = timestamp * 1000
        priceString = self.safe_string_2(trade, 'price', 'dealPrice')
        amountString = self.safe_string_2(trade, 'size', 'amount')
        side = self.safe_string(trade, 'side')
        fee = None
        feeCostString = self.safe_string(trade, 'fee')
        if feeCostString is not None:
            feeCurrencyId = self.safe_string(trade, 'feeCurrency')
            feeCurrency = self.safe_currency_code(feeCurrencyId)
            if feeCurrency is None:
                feeCurrency = market['quote'] if (side == 'sell') else market['base']
            fee = {
                'cost': feeCostString,
                'currency': feeCurrency,
                'rate': self.safe_string(trade, 'feeRate'),
            }
        type = self.safe_string_2(trade, 'type', 'orderType')
        if type == 'match':
            type = None
        costString = self.safe_string_2(trade, 'funds', 'value')
        if costString is None:
            contractSize = self.safe_string(market, 'contractSize')
            contractCost = Precise.string_mul(priceString, amountString)
            costString = Precise.string_mul(contractCost, contractSize)
        return self.safe_trade({
            'info': trade,
            'id': id,
            'order': orderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': market['symbol'],
            'type': type,
            'takerOrMaker': takerOrMaker,
            'side': side,
            'price': priceString,
            'amount': amountString,
            'cost': costString,
            'fee': fee,
        }, market)

    async def fetch_deposits(self, code=None, since=None, limit=None, params={}):
        """
        fetch all deposits made to an account
        :param str|None code: unified currency code
        :param int|None since: the earliest time in ms to fetch deposits for
        :param int|None limit: the maximum number of deposits structures to retrieve
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        await self.load_markets()
        request = {}
        currency = None
        if code is not None:
            currency = self.currency(code)
            request['currency'] = currency['id']
        if limit is not None:
            request['pageSize'] = limit
        if since is not None:
            request['startAt'] = since
        response = await self.futuresPrivateGetDepositList(self.extend(request, params))
        #
        #     {
        #         code: '200000',
        #         data: {
        #             "currentPage": 1,
        #             "pageSize": 5,
        #             "totalNum": 2,
        #             "totalPage": 1,
        #             "items": [
        #                 {
        #                     "address": "0x5f047b29041bcfdbf0e4478cdfa753a336ba6989",
        #                     "memo": "5c247c8a03aa677cea2a251d",
        #                     "amount": 1,
        #                     "fee": 0.0001,
        #                     "currency": "KCS",
        #                     "isInner": False,
        #                     "walletTxId": "5bbb57386d99522d9f954c5a@test004",
        #                     "status": "SUCCESS",
        #                     "createdAt": 1544178843000,
        #                     "updatedAt": 1544178891000
        #                     "remark":"foobar"
        #                 },
        #                 ...
        #             ]
        #         }
        #     }
        #
        responseData = response['data']['items']
        return self.parse_transactions(responseData, currency, since, limit, {'type': 'deposit'})

    async def fetch_withdrawals(self, code=None, since=None, limit=None, params={}):
        """
        fetch all withdrawals made from an account
        :param str|None code: unified currency code
        :param int|None since: the earliest time in ms to fetch withdrawals for
        :param int|None limit: the maximum number of withdrawals structures to retrieve
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        await self.load_markets()
        request = {}
        currency = None
        if code is not None:
            currency = self.currency(code)
            request['currency'] = currency['id']
        if limit is not None:
            request['pageSize'] = limit
        if since is not None:
            request['startAt'] = since
        response = await self.futuresPrivateGetWithdrawalList(self.extend(request, params))
        #
        #     {
        #         code: '200000',
        #         data: {
        #             "currentPage": 1,
        #             "pageSize": 5,
        #             "totalNum": 2,
        #             "totalPage": 1,
        #             "items": [
        #                 {
        #                     "id": "5c2dc64e03aa675aa263f1ac",
        #                     "address": "0x5bedb060b8eb8d823e2414d82acce78d38be7fe9",
        #                     "memo": "",
        #                     "currency": "ETH",
        #                     "amount": 1.0000000,
        #                     "fee": 0.0100000,
        #                     "walletTxId": "3e2414d82acce78d38be7fe9",
        #                     "isInner": False,
        #                     "status": "FAILURE",
        #                     "createdAt": 1546503758000,
        #                     "updatedAt": 1546504603000
        #                 },
        #                 ...
        #             ]
        #         }
        #     }
        #
        responseData = response['data']['items']
        return self.parse_transactions(responseData, currency, since, limit, {'type': 'withdrawal'})

    async def fetch_transaction_fee(self, code, params={}):
        """
        *DEPRECATED* please use fetchDepositWithdrawFee instead
        :param str code: unified currency code
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/en/latest/manual.html#fee-structure>`
        """
        raise BadRequest(self.id + ' fetchTransactionFee() is not supported')

    async def fetch_deposit_withdraw_fee(self, code, params={}):
        """
        Not supported
        :param str code: unified currency code
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/en/latest/manual.html#fee-structure>`
        """
        raise BadRequest(self.id + ' fetchDepositWithdrawFee() is not supported')

    async def fetch_ledger(self, code=None, since=None, limit=None, params={}):
        raise BadRequest(self.id + ' fetchLedger() is not supported yet')

    async def fetch_market_leverage_tiers(self, symbol, params={}):
        """
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes for a single market
        :param str symbol: unified market symbol
        :param dict params: extra parameters specific to the kucoinfutures api endpoint
        :returns dict: a `leverage tiers structure <https://docs.ccxt.com/en/latest/manual.html#leverage-tiers-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        if not market['contract']:
            raise BadRequest(self.id + ' fetchMarketLeverageTiers() supports contract markets only')
        request = {
            'symbol': market['id'],
        }
        response = await self.futuresPublicGetContractsRiskLimitSymbol(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": [
        #            {
        #                "symbol": "ETHUSDTM",
        #                "level": 1,
        #                "maxRiskLimit": 300000,
        #                "minRiskLimit": 0,
        #                "maxLeverage": 100,
        #                "initialMargin": 0.0100000000,
        #                "maintainMargin": 0.0050000000
        #            },
        #            ...
        #        ]
        #    }
        #
        data = self.safe_value(response, 'data')
        return self.parse_market_leverage_tiers(data, market)

    def parse_market_leverage_tiers(self, info, market):
        """
         * @ignore
        :param dict info: Exchange market response for 1 market
        :param dict market: CCXT market
        """
        #
        #    {
        #        "symbol": "ETHUSDTM",
        #        "level": 1,
        #        "maxRiskLimit": 300000,
        #        "minRiskLimit": 0,
        #        "maxLeverage": 100,
        #        "initialMargin": 0.0100000000,
        #        "maintainMargin": 0.0050000000
        #    }
        #
        tiers = []
        for i in range(0, len(info)):
            tier = info[i]
            tiers.append({
                'tier': self.safe_number(tier, 'level'),
                'currency': market['base'],
                'minNotional': self.safe_number(tier, 'minRiskLimit'),
                'maxNotional': self.safe_number(tier, 'maxRiskLimit'),
                'maintenanceMarginRate': self.safe_number(tier, 'maintainMargin'),
                'maxLeverage': self.safe_number(tier, 'maxLeverage'),
                'info': tier,
            })
        return tiers

    async def fetch_funding_rate_history(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches historical funding rate prices
        :param str|None symbol: unified symbol of the market to fetch the funding rate history for
        :param int|None since: not used by kucuoinfutures
        :param int|None limit: the maximum amount of `funding rate structures <https://docs.ccxt.com/en/latest/manual.html?#funding-rate-history-structure>` to fetch
        :param dict params: extra parameters specific to the okx api endpoint
        :returns [dict]: a list of `funding rate structures <https://docs.ccxt.com/en/latest/manual.html?#funding-rate-history-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchFundingRateHistory() requires a symbol argument')
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['maxCount'] = limit
        response = await self.webFrontGetContractSymbolFundingRates(self.extend(request, params))
        #
        #    {
        #        success: True,
        #        code: '200',
        #        msg: 'success',
        #        retry: False,
        #        data: {
        #            dataList: [
        #                {
        #                    symbol: 'XBTUSDTM',
        #                    granularity: 28800000,
        #                    timePoint: 1675108800000,
        #                    value: 0.0001
        #                },
        #                ...
        #            ],
        #            hasMore: True
        #        }
        #    }
        #
        data = self.safe_value(response, 'data')
        dataList = self.safe_value(data, 'dataList')
        return self.parse_funding_rate_histories(dataList, market, since, limit)

    def parse_funding_rate_history(self, info, market=None):
        timestamp = self.safe_number(info, 'timePoint')
        marketId = self.safe_string(info, 'symbol')
        return {
            'info': info,
            'symbol': self.safe_symbol(marketId, market),
            'fundingRate': self.safe_number(info, 'value'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
        }
