# -*- 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.kucoin import kucoin
from ccxt.abstract.kucoinfutures import ImplicitAPI
from ccxt.base.types import Balances, Currency, Int, LeverageTier, MarginModification, Market, Num, Order, OrderBook, OrderRequest, OrderSide, OrderType, Str, Strings, Ticker, Tickers, Trade, TradingFeeInterface, Transaction, TransferEntry
from typing import List
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, ImplicitAPI):

    def describe(self):
        return self.deep_extend(super(kucoinfutures, self).describe(), {
            'id': 'kucoinfutures',
            'name': 'KuCoin Futures',
            'countries': ['SC'],
            'rateLimit': 75,
            'version': 'v1',
            'certified': True,
            '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,
                'closeAllPositions': False,
                'closePosition': True,
                'closePositions': False,
                'createDepositAddress': True,
                'createOrder': True,
                'createOrders': True,
                'createReduceOnlyOrder': True,
                'createStopLimitOrder': True,
                'createStopLossOrder': True,
                'createStopMarketOrder': True,
                'createStopOrder': True,
                'createTakeProfitOrder': True,
                'createTriggerOrder': True,
                'fetchAccounts': True,
                'fetchBalance': True,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchClosedOrders': True,
                'fetchCrossBorrowRate': False,
                'fetchCrossBorrowRates': False,
                'fetchCurrencies': False,
                'fetchDepositAddress': True,
                'fetchDeposits': True,
                'fetchDepositWithdrawFee': False,
                'fetchDepositWithdrawFees': False,
                'fetchFundingHistory': True,
                'fetchFundingRate': True,
                'fetchFundingRateHistory': True,
                'fetchIndexOHLCV': False,
                'fetchIsolatedBorrowRate': False,
                'fetchIsolatedBorrowRates': False,
                'fetchL3OrderBook': True,
                'fetchLedger': True,
                'fetchLeverageTiers': False,
                'fetchMarginAdjustmentHistory': False,
                'fetchMarginMode': False,
                'fetchMarketLeverageTiers': True,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenOrders': True,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchPosition': True,
                'fetchPositionHistory': False,
                'fetchPositionMode': False,
                'fetchPositions': True,
                'fetchPositionsHistory': True,
                'fetchPremiumIndexOHLCV': False,
                'fetchStatus': True,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTime': True,
                'fetchTrades': True,
                'fetchTradingFee': True,
                'fetchTransactionFee': False,
                'fetchWithdrawals': True,
                'setLeverage': False,
                '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',
                    'webExchange': 'https://futures.kucoin.com/_api/web-front',
                },
            },
            '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,
                        'sub/api-key': 1,
                        'trade-statistics': 1,
                        'trade-fees': 1,
                        'history-positions': 1,
                    },
                    'post': {
                        'withdrawals': 1,
                        'transfer-out': 1,  # v2
                        'transfer-in': 1,
                        'orders': 1.33,
                        'orders/test': 1.33,
                        'position/margin/auto-deposit-status': 1,
                        'position/margin/deposit-margin': 1,
                        'position/risk-limit-level/change': 1,
                        'bullet-private': 1,
                        'sub/api-key': 1,
                        'sub/api-key/update': 1,
                    },
                    'delete': {
                        'withdrawals/{withdrawalId}': 1,
                        'cancel/transfer-out': 1,
                        'orders/{orderId}': 1,
                        'orders': 4.44,
                        'stopOrders': 1,
                        'sub/api-key': 1,
                        'orders/client-order/{clientOid}': 1,
                    },
                },
                'webExchange': {
                    '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',
                # },
            },
        })

    def fetch_status(self, params={}):
        """
        the latest known information on the availability of the exchange API
        :see: https://www.kucoin.com/docs/rest/futures-trading/market-data/get-service-status
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
        """
        response = 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,
        }

    def fetch_markets(self, params={}) -> List[Market]:
        """
        retrieves data on all markets for kucoinfutures
        :see: https://www.kucoin.com/docs/rest/futures-trading/market-data/get-symbols-list
        :param dict [params]: extra parameters specific to the exchange api endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = 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'),
                    },
                },
                'created': self.safe_integer(market, 'firstOpenDate'),
                'info': market,
            })
        return result

    def fetch_time(self, params={}):
        """
        fetches the current integer timestamp in milliseconds from the exchange server
        :see: https://www.kucoin.com/docs/rest/futures-trading/market-data/get-server-time
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        """
        response = self.futuresPublicGetTimestamp(params)
        #
        #    {
        #        "code": "200000",
        #        "data": 1637385119302,
        #    }
        #
        return self.safe_integer(response, 'data')

    def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
        """
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :see: https://www.kucoin.com/docs/rest/futures-trading/market-data/get-klines
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        self.load_markets()
        paginate = False
        paginate, params = self.handle_option_and_params(params, 'fetchOHLCV', 'paginate')
        if paginate:
            return self.fetch_paginated_call_deterministic('fetchOHLCV', symbol, since, limit, timeframe, params, 200)
        market = self.market(symbol)
        marketId = market['id']
        parsedTimeframe = self.safe_integer(self.timeframes, timeframe)
        request: dict = {
            'symbol': marketId,
        }
        if parsedTimeframe is not None:
            request['granularity'] = parsedTimeframe
        else:
            request['granularity'] = 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 = 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_list(response, 'data', [])
        return self.parse_ohlcvs(data, market, timeframe, since, limit)

    def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
        #
        #    [
        #        "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),
        ]

    def fetch_deposit_address(self, code: str, params={}):
        """
        fetch the deposit address for a currency associated with self account
        :see: https://www.kucoin.com/docs/rest/funding/deposit/get-deposit-address
        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        """
        self.load_markets()
        currency = self.currency(code)
        currencyId = currency['id']
        request: dict = {
            'currency': currencyId,  # Currency,including XBT,USDT
        }
        response = 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'),
        }

    def fetch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
        """
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: https://www.kucoin.com/docs/rest/futures-trading/market-data/get-part-order-book-level-2
        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        """
        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: dict = {
            '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 = 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 = self.parse_to_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

    def fetch_ticker(self, symbol: str, params={}) -> Ticker:
        """
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :see: https://www.kucoin.com/docs/rest/futures-trading/market-data/get-ticker
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = 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 fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
        """
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        :see: https://www.kucoin.com/docs/rest/futures-trading/market-data/get-symbols-list
        :param str[] [symbols]: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        self.load_markets()
        symbols = self.market_symbols(symbols)
        response = 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
        #        }
        #    }
        #
        data = self.safe_list(response, 'data', [])
        tickers = self.parse_tickers(data, symbols)
        return self.filter_by_array_tickers(tickers, 'symbol', symbols)

    def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
        #
        #     {
        #         "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
        #          }
        #     }
        #
        # from fetchTickers
        #
        # {
        #     symbol: "XBTUSDTM",
        #     rootSymbol: "USDT",
        #     type: "FFWCSX",
        #     firstOpenDate: 1585555200000,
        #     expireDate: null,
        #     settleDate: null,
        #     baseCurrency: "XBT",
        #     quoteCurrency: "USDT",
        #     settleCurrency: "USDT",
        #     maxOrderQty: 1000000,
        #     maxPrice: 1000000,
        #     lotSize: 1,
        #     tickSize: 0.1,
        #     indexPriceTickSize: 0.01,
        #     multiplier: 0.001,
        #     initialMargin: 0.008,
        #     maintainMargin: 0.004,
        #     maxRiskLimit: 100000,
        #     minRiskLimit: 100000,
        #     riskStep: 50000,
        #     makerFeeRate: 0.0002,
        #     takerFeeRate: 0.0006,
        #     takerFixFee: 0,
        #     makerFixFee: 0,
        #     settlementFee: null,
        #     isDeleverage: True,
        #     isQuanto: True,
        #     isInverse: False,
        #     markMethod: "FairPrice",
        #     fairMethod: "FundingRate",
        #     fundingBaseSymbol: ".XBTINT8H",
        #     fundingQuoteSymbol: ".USDTINT8H",
        #     fundingRateSymbol: ".XBTUSDTMFPI8H",
        #     indexSymbol: ".KXBTUSDT",
        #     settlementSymbol: "",
        #     status: "Open",
        #     fundingFeeRate: 0.000297,
        #     predictedFundingFeeRate: 0.000327,
        #     fundingRateGranularity: 28800000,
        #     openInterest: "8033200",
        #     turnoverOf24h: 659795309.2524643,
        #     volumeOf24h: 9998.54,
        #     markPrice: 67193.51,
        #     indexPrice: 67184.81,
        #     lastTradePrice: 67191.8,
        #     nextFundingRateTime: 20022985,
        #     maxLeverage: 125,
        #     premiumsSymbol1M: ".XBTUSDTMPI",
        #     premiumsSymbol8H: ".XBTUSDTMPI8H",
        #     fundingBaseSymbol1M: ".XBTINT",
        #     fundingQuoteSymbol1M: ".USDTINT",
        #     lowPrice: 64041.6,
        #     highPrice: 67737.3,
        #     priceChgPct: 0.0447,
        #     priceChg: 2878.7
        # }
        #
        marketId = self.safe_string(ticker, 'symbol')
        market = self.safe_market(marketId, market, '-')
        last = self.safe_string_2(ticker, 'price', 'lastTradePrice')
        timestamp = self.safe_integer_product(ticker, 'ts', 0.000001)
        return self.safe_ticker({
            'symbol': market['symbol'],
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': self.safe_string(ticker, 'highPrice'),
            'low': self.safe_string(ticker, 'lowPrice'),
            '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': self.safe_string(ticker, 'priceChg'),
            'percentage': self.safe_string(ticker, 'priceChgPct'),
            'average': None,
            'baseVolume': self.safe_string(ticker, 'volumeOf24h'),
            'quoteVolume': self.safe_string(ticker, 'turnoverOf24h'),
            'info': ticker,
        }, market)

    def fetch_funding_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        fetch the history of funding payments paid and received on self account
        :see: https://www.kucoin.com/docs/rest/futures-trading/funding-fees/get-funding-history
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch funding history for
        :param int [limit]: the maximum number of funding history structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding history structure <https://docs.ccxt.com/#/?id=funding-history-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchFundingHistory() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            '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 = 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

    def fetch_position(self, symbol: str, params={}):
        """
        :see: https://docs.kucoin.com/futures/#get-position-details
        fetch data on an open position
        :param str symbol: unified market symbol of the market the position is held in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = self.futuresPrivateGetPosition(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #            "id": "6505ee6eaff4070001f651c4",
        #            "symbol": "XBTUSDTM",
        #            "autoDeposit": False,
        #            "maintMarginReq": 0,
        #            "riskLimit": 200,
        #            "realLeverage": 0.0,
        #            "crossMode": False,
        #            "delevPercentage": 0.0,
        #            "currentTimestamp": 1694887534594,
        #            "currentQty": 0,
        #            "currentCost": 0.0,
        #            "currentComm": 0.0,
        #            "unrealisedCost": 0.0,
        #            "realisedGrossCost": 0.0,
        #            "realisedCost": 0.0,
        #            "isOpen": False,
        #            "markPrice": 26611.71,
        #            "markValue": 0.0,
        #            "posCost": 0.0,
        #            "posCross": 0,
        #            "posInit": 0.0,
        #            "posComm": 0.0,
        #            "posLoss": 0.0,
        #            "posMargin": 0.0,
        #            "posMaint": 0.0,
        #            "maintMargin": 0.0,
        #            "realisedGrossPnl": 0.0,
        #            "realisedPnl": 0.0,
        #            "unrealisedPnl": 0.0,
        #            "unrealisedPnlPcnt": 0,
        #            "unrealisedRoePcnt": 0,
        #            "avgEntryPrice": 0.0,
        #            "liquidationPrice": 0.0,
        #            "bankruptPrice": 0.0,
        #            "settleCurrency": "USDT",
        #            "maintainMargin": 0,
        #            "riskLimitLevel": 1
        #        }
        #    }
        #
        data = self.safe_dict(response, 'data', {})
        return self.parse_position(data, market)

    def fetch_positions(self, symbols: Strings = None, params={}):
        """
        fetch all open positions
        :see: https://docs.kucoin.com/futures/#get-position-list
        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        """
        self.load_markets()
        response = 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_list(response, 'data')
        return self.parse_positions(data, symbols)

    def fetch_positions_history(self, symbols: Strings = None, since: Int = None, limit: Int = None, params={}):
        """
        fetches historical positions
        :see: https://www.kucoin.com/docs/rest/futures-trading/positions/get-positions-history
        :param str[] [symbols]: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: closing end time
        :param int [params.pageId]: page id
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        """
        self.load_markets()
        if limit is None:
            limit = 200
        request: dict = {
            'limit': limit,
        }
        if since is not None:
            request['from'] = since
        until = self.safe_integer(params, 'until')
        if until is not None:
            params = self.omit(params, 'until')
            request['to'] = until
        response = self.futuresPrivateGetHistoryPositions(self.extend(request, params))
        #
        # {
        #     "success": True,
        #     "code": "200",
        #     "msg": "success",
        #     "retry": False,
        #     "data": {
        #         "currentPage": 1,
        #         "pageSize": 10,
        #         "totalNum": 25,
        #         "totalPage": 3,
        #         "items": [
        #             {
        #                 "closeId": "300000000000000030",
        #                 "positionId": "300000000000000009",
        #                 "uid": 99996908309485,
        #                 "userId": "6527d4fc8c7f3d0001f40f5f",
        #                 "symbol": "XBTUSDM",
        #                 "settleCurrency": "XBT",
        #                 "leverage": "0.0",
        #                 "type": "LIQUID_LONG",
        #                 "side": null,
        #                 "closeSize": null,
        #                 "pnl": "-1.0000003793999999",
        #                 "realisedGrossCost": "0.9993849748999999",
        #                 "withdrawPnl": "0.0",
        #                 "roe": null,
        #                 "tradeFee": "0.0006154045",
        #                 "fundingFee": "0.0",
        #                 "openTime": 1713785751181,
        #                 "closeTime": 1713785752784,
        #                 "openPrice": null,
        #                 "closePrice": null
        #             }
        #         ]
        #     }
        # }
        #
        data = self.safe_dict(response, 'data')
        items = self.safe_list(data, 'items', [])
        return self.parse_positions(items, symbols)

    def parse_position(self, position: dict, market: 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
        #            }
        #        ]
        #    }
        # position history
        #             {
        #                 "closeId": "300000000000000030",
        #                 "positionId": "300000000000000009",
        #                 "uid": 99996908309485,
        #                 "userId": "6527d4fc8c7f3d0001f40f5f",
        #                 "symbol": "XBTUSDM",
        #                 "settleCurrency": "XBT",
        #                 "leverage": "0.0",
        #                 "type": "LIQUID_LONG",
        #                 "side": null,
        #                 "closeSize": null,
        #                 "pnl": "-1.0000003793999999",
        #                 "realisedGrossCost": "0.9993849748999999",
        #                 "withdrawPnl": "0.0",
        #                 "roe": null,
        #                 "tradeFee": "0.0006154045",
        #                 "fundingFee": "0.0",
        #                 "openTime": 1713785751181,
        #                 "closeTime": 1713785752784,
        #                 "openPrice": null,
        #                 "closePrice": null
        #             }
        #
        symbol = self.safe_string(position, 'symbol')
        market = self.safe_market(symbol, market)
        timestamp = self.safe_integer(position, 'currentTimestamp')
        size = self.safe_string(position, 'currentQty')
        side = None
        type = self.safe_string_lower(position, 'type')
        if size is not None:
            if Precise.string_gt(size, '0'):
                side = 'long'
            elif Precise.string_lt(size, '0'):
                side = 'short'
        elif type is not None:
            if type.find('long') > -1:
                side = 'long'
            else:
                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 = None
        if crossMode is not None:
            marginMode = 'cross' if crossMode else 'isolated'
        return self.safe_position({
            'info': position,
            'id': self.safe_string_2(position, 'id', 'positionId'),
            'symbol': self.safe_string(market, 'symbol'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastUpdateTimestamp': self.safe_integer(position, 'closeTime'),
            '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_2(position, 'avgEntryPrice', 'openPrice'),
            'notional': self.parse_number(notional),
            'leverage': self.safe_number_2(position, 'realLeverage', 'leverage'),
            'unrealizedPnl': self.parse_number(unrealisedPnl),
            'contracts': self.parse_number(Precise.string_abs(size)),
            'contractSize': self.safe_value(market, 'contractSize'),
            'realizedPnl': self.safe_number_2(position, 'realisedPnl', 'pnl'),
            'marginRatio': None,
            'liquidationPrice': self.safe_number(position, 'liquidationPrice'),
            'markPrice': self.safe_number(position, 'markPrice'),
            'lastPrice': None,
            'collateral': self.safe_number(position, 'maintMargin'),
            'marginMode': marginMode,
            'side': side,
            'percentage': None,
            'stopLossPrice': None,
            'takeProfitPrice': None,
        })

    def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = 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.test]: set to True to use the test order endpoint(does not submit order, use to validate params)
        :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/#/?id=order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        testOrder = self.safe_bool(params, 'test', False)
        params = self.omit(params, 'test')
        orderRequest = self.create_contract_order_request(symbol, type, side, amount, price, params)
        response = None
        if testOrder:
            response = self.futuresPrivatePostOrdersTest(orderRequest)
        else:
            response = self.futuresPrivatePostOrders(orderRequest)
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #            "orderId": "619717484f1d010001510cde",
        #        },
        #    }
        #
        data = self.safe_dict(response, 'data', {})
        return self.parse_order(data, market)

    def create_orders(self, orders: List[OrderRequest], params={}):
        """
        create a list of trade orders
        :see: https://www.kucoin.com/docs/rest/futures-trading/orders/place-multiple-orders
        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :param dict [params]:  extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        ordersRequests = []
        for i in range(0, len(orders)):
            rawOrder = orders[i]
            symbol = self.safe_string(rawOrder, 'symbol')
            market = self.market(symbol)
            type = self.safe_string(rawOrder, 'type')
            side = self.safe_string(rawOrder, 'side')
            amount = self.safe_value(rawOrder, 'amount')
            price = self.safe_value(rawOrder, 'price')
            orderParams = self.safe_value(rawOrder, 'params', {})
            orderRequest = self.create_contract_order_request(market['id'], type, side, amount, price, orderParams)
            ordersRequests.append(orderRequest)
        response = self.futuresPrivatePostOrdersMulti(ordersRequests)
        #
        #     {
        #         "code": "200000",
        #         "data": [
        #             {
        #                 "orderId": "135241412609331200",
        #                 "clientOid": "3d8fcc13-0b13-447f-ad30-4b3441e05213",
        #                 "symbol": "LTCUSDTM",
        #                 "code": "200000",
        #                 "msg": "success"
        #             },
        #             {
        #                 "orderId": "135241412747743234",
        #                 "clientOid": "b878c7ee-ae3e-4d63-a20b-038acbb7306f",
        #                 "symbol": "LTCUSDTM",
        #                 "code": "200000",
        #                 "msg": "success"
        #             }
        #         ]
        #     }
        #
        data = self.safe_list(response, 'data', [])
        return self.parse_orders(data)

    def create_contract_order_request(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
        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: dict = {
            'clientOid': clientOrderId,
            'side': side,
            'symbol': market['id'],
            'type': type,  # limit or market
            'size': preciseAmount,
            'leverage': 1,
        }
        triggerPrice, stopLossPrice, takeProfitPrice = self.handle_trigger_prices(params)
        triggerPriceTypes: dict = {
            'mark': 'MP',
            'last': 'TP',
            'index': 'IP',
        }
        triggerPriceType = self.safe_string(params, 'triggerPriceType', 'mark')
        triggerPriceTypeValue = self.safe_string(triggerPriceTypes, triggerPriceType, triggerPriceType)
        params = self.omit(params, ['stopLossPrice', 'takeProfitPrice', 'triggerPrice', 'stopPrice'])
        if triggerPrice:
            request['stop'] = 'up' if (side == 'buy') else 'down'
            request['stopPrice'] = self.price_to_precision(symbol, triggerPrice)
            request['stopPriceType'] = triggerPriceTypeValue
        elif stopLossPrice or takeProfitPrice:
            if stopLossPrice:
                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'] = triggerPriceTypeValue
        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 = None
        postOnly, params = self.handle_post_only(type == 'market', False, params)
        if postOnly:
            request['postOnly'] = True
        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
        return self.extend(request, params)

    def cancel_order(self, id: str, symbol: Str = None, params={}):
        """
        cancels an open order
        :see: https://www.kucoin.com/docs/rest/futures-trading/orders/cancel-futures-order-by-orderid
        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.clientOrderId]: cancel order by client order id
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        clientOrderId = self.safe_string_2(params, 'clientOid', 'clientOrderId')
        params = self.omit(params, ['clientOrderId'])
        request: dict = {}
        response = None
        if clientOrderId is not None:
            if symbol is None:
                raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument when cancelling by clientOrderId')
            market = self.market(symbol)
            request['symbol'] = market['id']
            request['clientOid'] = clientOrderId
            response = self.futuresPrivateDeleteOrdersClientOrderClientOid(self.extend(request, params))
        else:
            request['orderId'] = id
            response = self.futuresPrivateDeleteOrdersOrderId(self.extend(request, params))
        #
        #   {
        #       "code": "200000",
        #       "data": {
        #           "cancelledOrderIds": [
        #                "619714b8b6353000014c505a",
        #           ],
        #       },
        #   }
        #
        return self.safe_value(response, 'data')

    def cancel_all_orders(self, symbol: Str = None, params={}):
        """
        cancel all open orders
        :see: https://www.kucoin.com/docs/rest/futures-trading/orders/cancel-multiple-futures-limit-orders
        :see: https://www.kucoin.com/docs/rest/futures-trading/orders/cancel-multiple-futures-stop-orders
        :param str symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param dict [params.trigger]: When True, all the trigger orders will be cancelled
        :returns: Response from the exchange
        """
        self.load_markets()
        request: dict = {}
        if symbol is not None:
            request['symbol'] = self.market_id(symbol)
        stop = self.safe_value_2(params, 'stop', 'trigger')
        params = self.omit(params, ['stop', 'trigger'])
        response = None
        if stop:
            response = self.futuresPrivateDeleteStopOrders(self.extend(request, params))
        else:
            response = self.futuresPrivateDeleteOrders(self.extend(request, params))
        #
        #   {
        #       "code": "200000",
        #       "data": {
        #           "cancelledOrderIds": [
        #                "619714b8b6353000014c505a",
        #           ],
        #       },
        #   }
        #
        return self.safe_value(response, 'data')

    def add_margin(self, symbol: str, amount: float, params={}) -> MarginModification:
        """
        add margin
        :see: https://www.kucoin.com/docs/rest/futures-trading/positions/add-margin-manually
        :param str symbol: unified market symbol
        :param float amount: amount of margin to add
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=add-margin-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        uuid = self.uuid()
        request: dict = {
            'symbol': market['id'],
            'margin': self.amount_to_precision(symbol, amount),
            'bizNo': uuid,
        }
        response = 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: Market = None) -> MarginModification:
        #
        #    {
        #        "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')
        timestamp = self.safe_integer(info, 'currentTimestamp')
        return {
            'info': info,
            'symbol': self.safe_symbol(marketId, market),
            'type': None,
            'marginMode': mode,
            'amount': None,
            'total': None,
            'code': self.safe_currency_code(currencyId),
            'status': None,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
        }

    def fetch_orders_by_status(self, status, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        fetches a list of orders placed on the exchange
        :see: https://docs.kucoin.com/futures/#get-order-list
        :see: https://docs.kucoin.com/futures/#get-untriggered-stop-order-list
        :param str status: 'active' or 'closed', only 'active' is valid for stop orders
        :param str symbol: unified symbol for the market to retrieve orders from
        :param int [since]: timestamp in ms of the earliest order to retrieve
        :param int [limit]: The maximum number of orders to retrieve
        :param dict [params]: exchange specific parameters
        :param bool [params.trigger]: set to True to retrieve untriggered stop orders
        :param int [params.until]: End time in ms
        :param str [params.side]: buy or sell
        :param str [params.type]: limit or market
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns: An `array of order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        paginate = False
        paginate, params = self.handle_option_and_params(params, 'fetchOrdersByStatus', 'paginate')
        if paginate:
            return self.fetch_paginated_call_dynamic('fetchOrdersByStatus', symbol, since, limit, params)
        stop = self.safe_value_2(params, 'stop', 'trigger')
        until = self.safe_integer(params, 'until')
        params = self.omit(params, ['stop', 'until', 'trigger'])
        if status == 'closed':
            status = 'done'
        elif status == 'open':
            status = 'active'
        request: dict = {}
        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
        response = None
        if stop:
            response = self.futuresPrivateGetStopOrders(self.extend(request, params))
        else:
            response = self.futuresPrivateGetOrders(self.extend(request, params))
        #
        #     {
        #         "code": "200000",
        #         "data": {
        #             "currentPage": 1,
        #             "pageSize": 50,
        #             "totalNum": 4,
        #             "totalPage": 1,
        #             "items": [
        #                 {
        #                     "id": "64507d02921f1c0001ff6892",
        #                     "symbol": "XBTUSDTM",
        #                     "type": "market",
        #                     "side": "buy",
        #                     "price": null,
        #                     "size": 1,
        #                     "value": "27.992",
        #                     "dealValue": "27.992",
        #                     "dealSize": 1,
        #                     "stp": "",
        #                     "stop": "",
        #                     "stopPriceType": "",
        #                     "stopTriggered": False,
        #                     "stopPrice": null,
        #                     "timeInForce": "GTC",
        #                     "postOnly": False,
        #                     "hidden": False,
        #                     "iceberg": False,
        #                     "leverage": "17",
        #                     "forceHold": False,
        #                     "closeOrder": False,
        #                     "visibleSize": null,
        #                     "clientOid": null,
        #                     "remark": null,
        #                     "tags": null,
        #                     "isActive": False,
        #                     "cancelExist": False,
        #                     "createdAt": 1682996482000,
        #                     "updatedAt": 1682996483062,
        #                     "endAt": 1682996483062,
        #                     "orderTime": 1682996482953900677,
        #                     "settleCurrency": "USDT",
        #                     "status": "done",
        #                     "filledValue": "27.992",
        #                     "filledSize": 1,
        #                     "reduceOnly": False
        #                 }
        #             ]
        #         }
        #     }
        #
        responseData = self.safe_value(response, 'data', {})
        orders = self.safe_list(responseData, 'items', [])
        return self.parse_orders(orders, market, since, limit)

    def fetch_closed_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
        fetches information on multiple closed orders made by the user
        :see: https://docs.kucoin.com/futures/#get-order-list
        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: end time in ms
        :param str [params.side]: buy or sell
        :param str [params.type]: limit, or market
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        paginate = False
        paginate, params = self.handle_option_and_params(params, 'fetchClosedOrders', 'paginate')
        if paginate:
            return self.fetch_paginated_call_dynamic('fetchClosedOrders', symbol, since, limit, params)
        return self.fetch_orders_by_status('done', symbol, since, limit, params)

    def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
        fetches information on multiple open orders made by the user
        :see: https://docs.kucoin.com/futures/#get-order-list
        :see: https://docs.kucoin.com/futures/#get-untriggered-stop-order-list
        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: end time in ms
        :param str [params.side]: buy or sell
        :param str [params.type]: limit, or market
        :param boolean [params.trigger]: set to True to retrieve untriggered stop orders
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        paginate = False
        paginate, params = self.handle_option_and_params(params, 'fetchOpenOrders', 'paginate')
        if paginate:
            return self.fetch_paginated_call_dynamic('fetchOpenOrders', symbol, since, limit, params)
        return self.fetch_orders_by_status('open', symbol, since, limit, params)

    def fetch_order(self, id: Str = None, symbol: Str = None, params={}):
        """
        fetches information on an order made by the user
        :see: https://docs.kucoin.com/futures/#get-details-of-a-single-order
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        request: dict = {}
        response = None
        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
            params = self.omit(params, ['clientOid', 'clientOrderId'])
            response = self.futuresPrivateGetOrdersByClientOid(self.extend(request, params))
        else:
            request['orderId'] = id
            response = self.futuresPrivateGetOrdersOrderId(self.extend(request, params))
        #
        #     {
        #         "code": "200000",
        #         "data": {
        #             "id": "64507d02921f1c0001ff6892",
        #             "symbol": "XBTUSDTM",
        #             "type": "market",
        #             "side": "buy",
        #             "price": null,
        #             "size": 1,
        #             "value": "27.992",
        #             "dealValue": "27.992",
        #             "dealSize": 1,
        #             "stp": "",
        #             "stop": "",
        #             "stopPriceType": "",
        #             "stopTriggered": False,
        #             "stopPrice": null,
        #             "timeInForce": "GTC",
        #             "postOnly": False,
        #             "hidden": False,
        #             "iceberg": False,
        #             "leverage": "17",
        #             "forceHold": False,
        #             "closeOrder": False,
        #             "visibleSize": null,
        #             "clientOid": null,
        #             "remark": null,
        #             "tags": null,
        #             "isActive": False,
        #             "cancelExist": False,
        #             "createdAt": 1682996482000,
        #             "updatedAt": 1682996483000,
        #             "endAt": 1682996483000,
        #             "orderTime": 1682996482953900677,
        #             "settleCurrency": "USDT",
        #             "status": "done",
        #             "filledSize": 1,
        #             "filledValue": "27.992",
        #             "reduceOnly": False
        #         }
        #     }
        #
        market = self.market(symbol) if (symbol is not None) else None
        responseData = self.safe_dict(response, 'data')
        return self.parse_order(responseData, market)

    def parse_order(self, order: dict, market: Market = None) -> Order:
        #
        # fetchOrder, fetchOrdersByStatus
        #
        #     {
        #         "id": "64507d02921f1c0001ff6892",
        #         "symbol": "XBTUSDTM",
        #         "type": "market",
        #         "side": "buy",
        #         "price": null,
        #         "size": 1,
        #         "value": "27.992",
        #         "dealValue": "27.992",
        #         "dealSize": 1,
        #         "stp": "",
        #         "stop": "",
        #         "stopPriceType": "",
        #         "stopTriggered": False,
        #         "stopPrice": null,
        #         "timeInForce": "GTC",
        #         "postOnly": False,
        #         "hidden": False,
        #         "iceberg": False,
        #         "leverage": "17",
        #         "forceHold": False,
        #         "closeOrder": False,
        #         "visibleSize": null,
        #         "clientOid": null,
        #         "remark": null,
        #         "tags": null,
        #         "isActive": False,
        #         "cancelExist": False,
        #         "createdAt": 1682996482000,
        #         "updatedAt": 1682996483062,
        #         "endAt": 1682996483062,
        #         "orderTime": 1682996482953900677,
        #         "settleCurrency": "USDT",
        #         "status": "done",
        #         "filledValue": "27.992",
        #         "filledSize": 1,
        #         "reduceOnly": False
        #     }
        #
        # createOrder
        #
        #     {
        #         "orderId": "619717484f1d010001510cde"
        #     }
        #
        # createOrders
        #
        #     {
        #         "orderId": "80465574458560512",
        #         "clientOid": "5c52e11203aa677f33e491",
        #         "symbol": "ETHUSDTM",
        #         "code": "200000",
        #         "msg": "success"
        #     }
        #
        marketId = self.safe_string(order, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        orderId = self.safe_string_2(order, 'id', 'orderId')
        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, 'filledSize')
        cost = self.safe_string(order, 'filledValue')
        average = None
        if Precise.string_gt(filled, '0'):
            contractSize = self.safe_string(market, 'contractSize')
            if market['linear']:
                average = Precise.string_div(cost, Precise.string_mul(contractSize, filled))
            else:
                average = Precise.string_div(Precise.string_mul(contractSize, filled), cost)
        # precision reported by their api is 8 d.p.
        # average = Precise.string_div(cost, Precise.string_mul(filled, market['contractSize']))
        # bool
        isActive = self.safe_value(order, 'isActive')
        cancelExist = self.safe_bool(order, 'cancelExist', False)
        status = None
        if isActive is not None:
            status = 'open' if isActive else 'closed'
        status = 'canceled' if cancelExist else status
        fee = None
        if feeCost is not None:
            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')
        reduceOnly = self.safe_value(order, 'reduceOnly')
        lastUpdateTimestamp = self.safe_integer(order, 'updatedAt')
        return self.safe_order({
            'id': orderId,
            'clientOrderId': clientOrderId,
            'symbol': symbol,
            'type': type,
            'timeInForce': timeInForce,
            'postOnly': postOnly,
            'reduceOnly': reduceOnly,
            '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,
            'lastUpdateTimestamp': lastUpdateTimestamp,
            'average': average,
            'trades': None,
        }, market)

    def fetch_funding_rate(self, symbol: str, params={}):
        """
        fetch the current funding rate
        :see: https://www.kucoin.com/docs/rest/futures-trading/funding-fees/get-current-funding-rate
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = 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_integer(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, 'value'),
            'fundingTimestamp': fundingTimestamp,
            'fundingDatetime': self.iso8601(fundingTimestamp),
            'nextFundingRate': self.safe_number(data, 'predictedValue'),
            'nextFundingTimestamp': None,
            'nextFundingDatetime': None,
            'previousFundingRate': None,
            'previousFundingTimestamp': None,
            'previousFundingDatetime': None,
        }

    def parse_balance(self, response) -> Balances:
        result: dict = {
            '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)

    def fetch_balance(self, params={}) -> Balances:
        """
        query for balance and get the amount of funds available for trading or funds locked in orders
        :see: https://www.kucoin.com/docs/rest/funding/funding-overview/get-account-detail-futures
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        """
        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: dict = {
            'currency': currency['id'],
        }
        response = 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)

    def transfer(self, code: str, amount: float, fromAccount: str, toAccount: str, params={}) -> TransferEntry:
        """
        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 exchange API endpoint
        :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=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')
        self.load_markets()
        currency = self.currency(code)
        amountToPrecision = self.currency_to_precision(code, amount)
        request: dict = {
            'currency': self.safe_string(currency, 'id'),  # Currency,including XBT,USDT
            'amount': amountToPrecision,
        }
        # transfer from usdm futures wallet to spot wallet
        response = 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: dict, currency: Currency = None) -> TransferEntry:
        #
        # 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: Str) -> Str:
        statuses: dict = {
            'PROCESSING': 'pending',
        }
        return self.safe_string(statuses, status, status)

    def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        :see: https://docs.kucoin.com/futures/#get-fills
        fetch all trades made by the user
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: End time in ms
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        """
        self.load_markets()
        paginate = False
        paginate, params = self.handle_option_and_params(params, 'fetchMyTrades', 'paginate')
        if paginate:
            return self.fetch_paginated_call_dynamic('fetchMyTrades', symbol, since, limit, params)
        request: dict = {
            # 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(millisecond)
            # endAt(long) [optional] End time(millisecond)
        }
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            request['startAt'] = since
        request, params = self.handle_until_option('endAt', request, params)
        response = 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_dict(response, 'data', {})
        trades = self.safe_list(data, 'items', [])
        return self.parse_trades(trades, market, since, limit)

    def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
        """
        get the list of most recent trades for a particular symbol
        :see: https://www.kucoin.com/docs/rest/futures-trading/market-data/get-transaction-history
        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = 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_list(response, 'data', [])
        return self.parse_trades(trades, market, since, limit)

    def parse_trade(self, trade: dict, market: Market = None) -> Trade:
        #
        # 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 = self.parse_to_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)

    def fetch_deposits(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
        """
        fetch all deposits made to an account
        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        self.load_markets()
        request: dict = {}
        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 = 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'})

    def fetch_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
        """
        fetch all withdrawals made from an account
        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        self.load_markets()
        request: dict = {}
        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 = 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'})

    def fetch_market_leverage_tiers(self, symbol: str, params={}) -> List[LeverageTier]:
        """
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes for a single market
        :see: https://www.kucoin.com/docs/rest/futures-trading/risk-limit/get-futures-risk-limit-level
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `leverage tiers structure <https://docs.ccxt.com/#/?id=leverage-tiers-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        if not market['contract']:
            raise BadRequest(self.id + ' fetchMarketLeverageTiers() supports contract markets only')
        request: dict = {
            'symbol': market['id'],
        }
        response = 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: Market = None) -> List[LeverageTier]:
        """
         * @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

    def fetch_funding_rate_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        :see: https://www.kucoin.com/docs/rest/futures-trading/funding-fees/get-public-funding-history#request-url
        fetches historical funding rate prices
        :param str symbol: unified symbol of the market to fetch the funding rate history for
        :param int [since]: not used by kucuoinfutures
        :param int [limit]: the maximum amount of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>` to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: end time in ms
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchFundingRateHistory() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
            'from': 0,
            'to': self.milliseconds(),
        }
        until = self.safe_integer(params, 'until')
        params = self.omit(params, ['until'])
        if since is not None:
            request['from'] = since
            if until is None:
                request['to'] = since + 1000 * 8 * 60 * 60 * 100
        if until is not None:
            request['to'] = until
            if since is None:
                request['to'] = until - 1000 * 8 * 60 * 60 * 100
        response = self.futuresPublicGetContractFundingRates(self.extend(request, params))
        #
        #     {
        #         "code": "200000",
        #         "data": [
        #             {
        #                 "symbol": "IDUSDTM",
        #                 "fundingRate": 2.26E-4,
        #                 "timepoint": 1702296000000
        #             }
        #         ]
        #     }
        #
        data = self.safe_value(response, 'data')
        return self.parse_funding_rate_histories(data, market, since, limit)

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

    def close_position(self, symbol: str, side: OrderSide = None, params={}) -> Order:
        """
        closes open positions for a market
        :see: https://www.kucoin.com/docs/rest/futures-trading/orders/place-order
        :param str symbol: Unified CCXT market symbol
        :param str side: not used by kucoinfutures closePositions
        :param dict [params]: extra parameters specific to the okx api endpoint
        :param str [params.clientOrderId]: client order id of the order
        :returns dict[]: `A list of position structures <https://docs.ccxt.com/#/?id=position-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        clientOrderId = self.safe_string(params, 'clientOrderId')
        testOrder = self.safe_bool(params, 'test', False)
        params = self.omit(params, ['test', 'clientOrderId'])
        if clientOrderId is None:
            clientOrderId = self.number_to_string(self.nonce())
        request: dict = {
            'symbol': market['id'],
            'closeOrder': True,
            'clientOid': clientOrderId,
            'type': 'market',
        }
        response = None
        if testOrder:
            response = self.futuresPrivatePostOrdersTest(self.extend(request, params))
        else:
            response = self.futuresPrivatePostOrders(self.extend(request, params))
        return self.parse_order(response, market)

    def fetch_trading_fee(self, symbol: str, params={}) -> TradingFeeInterface:
        """
        fetch the trading fees for a market
        :see: https://www.kucoin.com/docs/rest/funding/trade-fee/trading-pair-actual-fee-futures
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/#/?id=fee-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbols': market['id'],
        }
        response = self.privateGetTradeFees(self.extend(request, params))
        #
        #  {
        #      "code": "200000",
        #      "data": {
        #        "symbol": "XBTUSDTM",
        #        "takerFeeRate": "0.0006",
        #        "makerFeeRate": "0.0002"
        #      }
        #  }
        #
        data = self.safe_list(response, 'data', [])
        first = self.safe_dict(data, 0)
        marketId = self.safe_string(first, 'symbol')
        return {
            'info': response,
            'symbol': self.safe_symbol(marketId, market),
            'maker': self.safe_number(first, 'makerFeeRate'),
            'taker': self.safe_number(first, 'takerFeeRate'),
            'percentage': True,
            'tierBased': True,
        }
