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

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

from ccxt.base.exchange import Exchange
from ccxt.abstract.poloniexfutures import ImplicitAPI
import hashlib
from ccxt.base.types import Balances, Int, Market, Num, Order, OrderBook, OrderSide, OrderType, Str, Strings, Ticker, Tickers, Trade
from typing import List
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import AccountSuspended
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
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 poloniexfutures(Exchange, ImplicitAPI):

    def describe(self):
        return self.deep_extend(super(poloniexfutures, self).describe(), {
            'id': 'poloniexfutures',
            'name': 'Poloniex Futures',
            'countries': ['US'],
            # 30 requests per second
            'rateLimit': 33.3,
            'certified': False,
            'pro': True,
            'version': 'v1',
            'has': {
                'CORS': None,
                'spot': False,
                'margin': True,
                'swap': True,
                'future': False,
                'option': None,
                'createOrder': True,
                'fetchBalance': True,
                'fetchClosedOrders': True,
                'fetchCurrencies': False,
                'fetchDepositAddress': False,
                'fetchDepositAddresses': False,
                'fetchDepositAddressesByNetwork': False,
                'fetchFundingRate': True,
                'fetchFundingRateHistory': False,
                'fetchL3OrderBook': True,
                'fetchMarkets': True,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenOrders': True,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrdersByStatus': True,
                'fetchPositions': True,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTime': True,
                'fetchTrades': True,
                'setMarginMode': True,
            },
            'timeframes': {
                '1m': 1,
                '5m': 5,
                '15m': 15,
                '30m': 30,
                '1h': 60,
                '2h': 120,
                '4h': 480,
                '12h': 720,
                '1d': 1440,
                '1w': 10080,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766817-e9456312-5ee6-11e7-9b3c-b628ca5626a5.jpg',
                'api': {
                    'public': 'https://futures-api.poloniex.com',
                    'private': 'https://futures-api.poloniex.com',
                },
                'www': 'https://www.poloniex.com',
                'doc': 'https://futures-docs.poloniex.com',
                'fees': 'https://poloniex.com/fee-schedule',
                'referral': 'https://poloniex.com/signup?c=UBFZJRPJ',
            },
            'api': {
                'public': {
                    'get': {
                        'contracts/active': 10,
                        'contracts/{symbol}': 10,
                        'ticker': 10,
                        'tickers': 10,  # v2
                        'level2/snapshot': 180.002,
                        'level2/depth': 180.002,
                        'level2/message/query': 180.002,
                        'level3/snapshot': 180.002,  # v2
                        'trade/history': 10,
                        'interest/query': 10,
                        'index/query': 10,
                        'mark-price/{symbol}/current': 10,
                        'premium/query': 10,
                        'funding-rate/{symbol}/current': 10,
                        'timestamp': 10,
                        'status': 10,
                        'kline/query': 10,
                    },
                    'post': {
                        'bullet-public': 10,
                    },
                },
                'private': {
                    'get': {
                        'account-overview': 1,
                        'transaction-history': 1,
                        'maxActiveOrders': 1,
                        'maxRiskLimit': 1,
                        'userFeeRate': 1,
                        'marginType/query': 1,
                        'orders': 1,
                        'stopOrders': 1,
                        'recentDoneOrders': 1,
                        'orders/{order-id}': 1,
                        'clientOrderId/{clientOid}': 1,
                        'fills': 1,
                        'openOrderStatistics': 1,
                        'position': 1.5,
                        'positions': 1.5,
                        'funding-history': 1,
                    },
                    'post': {
                        'orders': 1.5,
                        'batchOrders': 1.5,
                        'position/margin/auto-deposit-status': 1.5,
                        'position/margin/deposit-margin': 1.5,
                        'position/margin/withdraw-margin': 1.5,
                        'bullet-private': 1,
                        'marginType/change': 1,
                    },
                    'delete': {
                        'orders/{order-id}': 1.5,
                        'orders': 150.016,
                        'stopOrders': 150.016,
                    },
                },
            },
            'precisionMode': TICK_SIZE,
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'taker': self.parse_number('0.00075'),
                    'maker': self.parse_number('0.0001'),
                },
                'funding': {
                    'tierBased': False,
                    'percentage': False,
                    'withdraw': {},
                    'deposit': {},
                },
            },
            'commonCurrencies': {
            },
            'requiredCredentials': {
                'apiKey': True,
                'secret': True,
                'password': True,
            },
            'options': {
                'networks': {
                    'OMNI': 'omni',
                    'ERC20': 'eth',
                    'TRC20': 'trx',
                },
                'versions': {
                    'public': {
                        'GET': {
                            'ticker': 'v2',
                            'tickers': 'v2',
                            'level3/snapshot': 'v2',
                        },
                    },
                },
            },
            '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.
                    '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"}
                },
            },
        })

    def fetch_markets(self, params={}) -> List[Market]:
        """
        retrieves data on all markets for poloniexfutures
        :see: https://futures-docs.poloniex.com/#symbol-2
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = self.publicGetContractsActive(params)
        #
        # {
        #  "code": "200000",
        #  "data": [
        #     {
        #       "symbol": "APTUSDTPERP",
        #       "takerFixFee": "0E-10",
        #       "nextFundingRateTime": "20145603",
        #       "makerFixFee": "0E-10",
        #       "type": "FFWCSX",
        #       "predictedFundingFeeRate": "0.000000",
        #       "turnoverOf24h": "386037.46704292",
        #       "initialMargin": "0.05",
        #       "isDeleverage": True,
        #       "createdAt": "1666681959000",
        #       "fundingBaseSymbol": ".APTINT8H",
        #       "lowPriceOf24h": "4.34499979019165",
        #       "lastTradePrice": "4.4090000000",
        #       "indexPriceTickSize": "0.001",
        #       "fairMethod": "FundingRate",
        #       "takerFeeRate": "0.00040",
        #       "order": "102",
        #       "updatedAt": "1671076377000",
        #       "displaySettleCurrency": "USDT",
        #       "indexPrice": "4.418",
        #       "multiplier": "1.0",
        #       "maxLeverage": "20",
        #       "fundingQuoteSymbol": ".USDTINT8H",
        #       "quoteCurrency": "USDT",
        #       "maxOrderQty": "1000000",
        #       "maxPrice": "1000000.0000000000",
        #       "maintainMargin": "0.025",
        #       "status": "Open",
        #       "displayNameMap": [Object],
        #       "openInterest": "2367",
        #       "highPriceOf24h": "4.763999938964844",
        #       "fundingFeeRate": "0.000000",
        #       "volumeOf24h": "83540.00000000",
        #       "riskStep": "500000",
        #       "isQuanto": True,
        #       "maxRiskLimit": "20000",
        #       "rootSymbol": "USDT",
        #       "baseCurrency": "APT",
        #       "firstOpenDate": "1666701000000",
        #       "tickSize": "0.001",
        #       "markMethod": "FairPrice",
        #       "indexSymbol": ".PAPTUSDT",
        #       "markPrice": "4.418",
        #       "minRiskLimit": "1000000",
        #       "settlementFixFee": "0E-10",
        #       "settlementSymbol": '',
        #       "priceChgPctOf24h": "-0.0704",
        #       "fundingRateSymbol": ".APTUSDTPERPFPI8H",
        #       "makerFeeRate": "0.00010",
        #       "isInverse": False,
        #       "lotSize": "1",
        #       "settleCurrency": "USDT",
        #       "settlementFeeRate": "0.0"
        #     },
        #   ]
        # }
        #
        data = self.safe_value(response, 'data', [])
        return self.parse_markets(data)

    def parse_market(self, market: dict) -> Market:
        id = self.safe_string(market, 'symbol')
        baseId = self.safe_string(market, 'baseCurrency')
        quoteId = self.safe_string(market, 'quoteCurrency')
        settleId = self.safe_string(market, 'rootSymbol')
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        settle = self.safe_currency_code(settleId)
        symbol = base + '/' + quote + ':' + settle
        inverse = self.safe_value(market, 'isInverse')
        status = self.safe_string(market, 'status')
        multiplier = self.safe_string(market, 'multiplier')
        tickSize = self.safe_number(market, 'indexPriceTickSize')
        lotSize = self.safe_number(market, 'lotSize')
        limitAmountMax = self.safe_number(market, 'maxOrderQty')
        limitPriceMax = self.safe_number(market, 'maxPrice')
        return {
            'id': id,
            'symbol': symbol,
            'base': base,
            'quote': quote,
            'settle': settle,
            'baseId': baseId,
            'quoteId': quoteId,
            'settleId': settleId,
            'type': 'swap',
            'spot': False,
            'margin': False,
            'swap': True,
            'future': False,
            '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': None,
            'expiryDatetime': None,
            'strike': None,
            'optionType': None,
            'precision': {
                'amount': lotSize,
                'price': tickSize,
            },
            'limits': {
                'leverage': {
                    'min': self.parse_number('1'),
                    'max': self.safe_number(market, 'maxLeverage'),
                },
                'amount': {
                    'min': lotSize,
                    'max': limitAmountMax,
                },
                'price': {
                    'min': tickSize,
                    'max': limitPriceMax,
                },
                'cost': {
                    'min': None,
                    'max': None,
                },
            },
            'created': self.safe_integer(market, 'firstOpenDate'),
            'info': market,
        }

    def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
        #
        #    {
        #        "symbol": "BTCUSDTPERP",                   # Market of the symbol
        #        "sequence": 45,                            # Sequence number which is used to judge the continuity of the pushed messages
        #        "side": "sell",                            # Transaction side of the last traded taker order
        #        "price": 3600.00,                          # Filled price
        #        "size": 16,                                # Filled quantity
        #        "tradeId": "5c9dcf4170744d6f5a3d32fb",     # Order ID
        #        "bestBidSize": 795,                        # Best bid size
        #        "bestBidPrice": 3200.00,                   # Best bid
        #        "bestAskPrice": 3600.00,                   # Best ask size
        #        "bestAskSize": 284,                        # Best ask
        #        "ts": 1553846081210004941                  # Filled time - nanosecond
        #    }
        #
        #    {
        #        "volume": 30449670,            #24h Volume
        #        "turnover": 845169919063,      #24h Turnover
        #        "lastPrice": 3551,           #Last price
        #        "priceChgPct": 0.0043,         #24h Change
        #        "ts": 1547697294838004923      #Snapshot time(nanosecond)
        #    }
        #
        marketId = self.safe_string(ticker, 'symbol')
        symbol = self.safe_symbol(marketId, market)
        timestampString = self.safe_string(ticker, 'ts')
        multiplier = None
        if len(timestampString) == 16:
            # 16 digits: https://app.travis-ci.com/github/ccxt/ccxt/builds/270587157#L5454
            multiplier = 0.001
        elif len(timestampString) == 17:
            # 17 digits: https://app.travis-ci.com/github/ccxt/ccxt/builds/269959181#L4011
            multiplier = 0.0001
        elif len(timestampString) == 18:
            multiplier = 0.00001
        else:
            # 19 length default
            multiplier = 0.000001
        timestamp = self.safe_integer_product(ticker, 'ts', multiplier)
        last = self.safe_string_2(ticker, 'price', 'lastPrice')
        percentage = Precise.string_mul(self.safe_string(ticker, 'priceChgPct'), '100')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': None,
            'low': None,
            'bid': self.safe_string(ticker, 'bestBidPrice'),
            'bidVolume': self.safe_string(ticker, 'bestBidSize'),
            'ask': self.safe_string(ticker, 'bestAskPrice'),
            'askVolume': self.safe_string(ticker, 'bestAskSize'),
            'vwap': None,
            'open': None,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': None,
            'percentage': percentage,
            'average': None,
            'baseVolume': self.safe_string_2(ticker, 'size', 'volume'),
            'quoteVolume': self.safe_string(ticker, 'turnover'),
            'info': ticker,
        }, market)

    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://futures-docs.poloniex.com/#get-real-time-ticker-2-0
        :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.publicGetTicker(self.extend(request, params))
        #
        # {
        #     "code": "200000",
        #     "data": {
        #       "sequence": "11574719",
        #       "symbol": "BTCUSDTPERP",
        #       "side": "sell",
        #       "size": "1",
        #       "price": "16990.1",
        #       "bestBidSize": "3",
        #       "bestBidPrice": "16990.1",
        #       "bestAskPrice": "16991.0",
        #       "tradeId": "639c8a529fd7cf0001af4157",
        #       "bestAskSize": "505",
        #       "ts": "1671203410721232337"
        #     }
        # }
        #
        return self.parse_ticker(self.safe_value(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://futures-docs.poloniex.com/#get-real-time-ticker-of-all-symbols
        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        self.load_markets()
        response = self.publicGetTickers(params)
        data = self.safe_list(response, 'data', [])
        return self.parse_tickers(data, symbols)

    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://futures-docs.poloniex.com/#get-full-order-book-level-2
        :see: https://futures-docs.poloniex.com/#get-full-order-book-level-3
        :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')
        params = self.omit(params, 'level')
        if level is not None and level != 2 and level != 3:
            raise BadRequest(self.id + ' fetchOrderBook() can only return level 2 & 3')
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = None
        if level == 3:
            response = self.publicGetLevel3Snapshot(self.extend(request, params))
        else:
            response = self.publicGetLevel2Snapshot(self.extend(request, params))
        # L2
        #
        # {
        #     "code": "200000",
        #     "data": {
        #     "symbol": "BTCUSDTPERP",
        #     "sequence": 1669149851334,
        #     "asks": [
        #         [
        #             16952,
        #             12
        #         ],
        #     ],
        #     "bids": [
        #         [
        #             16951.9,
        #             13
        #         ],
        #     ],
        # }
        #
        # L3
        #
        # {
        #     "code": "200000",
        #     "data": {
        #     "symbol": "BTCUSDTPERP",
        #     "sequence": 1669149851334,
        #     "asks": [
        #         [
        #             "639c95388cba5100084eabce",
        #             "16952.0",
        #             "1",
        #             1671206200542484700
        #         ],
        #     ],
        #     "bids": [
        #         [
        #             "626659d83385c200072e690b",
        #             "17.0",
        #             "1000",
        #             1650874840161291000
        #         ],
        #     ],
        # }
        #
        data = self.safe_value(response, 'data', {})
        timestamp = self.safe_integer_product(data, 'ts', 0.000001)
        orderbook = None
        if level == 3:
            orderbook = self.parse_order_book(data, market['symbol'], timestamp, 'bids', 'asks', 1, 2)
        else:
            orderbook = self.parse_order_book(data, market['symbol'], timestamp, 'bids', 'asks', 0, 1)
        orderbook['nonce'] = self.safe_integer(data, 'sequence')
        return orderbook

    def fetch_l3_order_book(self, symbol: str, limit: Int = None, params={}):
        """
        fetches level 3 information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: https://futures-docs.poloniex.com/#get-full-order-book-level-3
        :param str symbol: unified market symbol
        :param int [limit]: max number of orders to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order book structure <https://docs.ccxt.com/#/?id=order-book-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        return self.fetch_order_book(market['id'], None, {'level': 3})

    def parse_trade(self, trade: dict, market: Market = None) -> Trade:
        #
        # fetchTrades(public)
        #
        #     {
        #         "sequence": 11827985,
        #         "side": "buy",
        #         "size": 101,
        #         "price": "16864.0000000000",
        #         "takerOrderId": "639c986f0ac2470007be75ee",
        #         "makerOrderId": "639c986fa69d280007b76111",
        #         "tradeId": "639c986f9fd7cf0001afd7ee",
        #         "ts": 1671207023485924400
        #     }
        #
        # fetchMyTrades
        #
        #   {
        #       "symbol": "BTCUSDTPERP",  #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
        #   }
        #
        marketId = self.safe_string(trade, 'symbol')
        market = self.safe_market(marketId, market, '-')
        id = self.safe_string(trade, 'tradeId')
        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(trade, 'price')
        amountString = self.safe_string(trade, 'size')
        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(trade, 'orderType')
        if type == 'match':
            type = None
        costString = self.safe_string(trade, 'value')
        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_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://futures-docs.poloniex.com/#historical-data
        :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.publicGetTradeHistory(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": [
        #        {
        #          "sequence": 11827985,
        #          "side": "buy",
        #          "size": 101,
        #          "price": "16864.0000000000",
        #          "takerOrderId": "639c986f0ac2470007be75ee",
        #          "makerOrderId": "639c986fa69d280007b76111",
        #          "tradeId": "639c986f9fd7cf0001afd7ee",
        #          "ts": 1671207023485924400
        #        },
        #    }
        #
        trades = self.safe_list(response, 'data', [])
        return self.parse_trades(trades, market, since, limit)

    def fetch_time(self, params={}):
        """
        fetches the current integer timestamp in milliseconds from the poloniexfutures server
        :see: https://futures-docs.poloniex.com/#time
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the poloniexfutures server
        """
        response = self.publicGetTimestamp(params)
        #
        # {
        #     "code":"200000",
        #     "msg":"success",
        #     "data":1546837113087
        # }
        #
        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://futures-docs.poloniex.com/#k-chart
        :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
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        self.load_markets()
        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)
            request['to'] = endAt
        elif limit is not None:
            since = endAt - limit * duration
            request['from'] = since
        response = self.publicGetKlineQuery(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_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://futures-docs.poloniex.com/#get-account-overview
        :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()
        currencyId = self.safe_string(params, 'currency')
        request: dict = {}
        if currencyId is not None:
            currency = self.currency(currencyId)
            request = {
                'currency': currency['id'],
            }
        response = self.privateGetAccountOverview(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 create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
        """
        Create an order on the exchange
        :see: https://futures-docs.poloniex.com/#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.leverage]: Leverage size of the order
        :param float [params.stopPrice]: The price at which a trigger order is triggered at
        :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
        :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', defaults to 'up' if side is sell and 'down' if side is buy, requires stopPrice
        :param str [params.stopPriceType]:  TP, IP or MP, defaults to TP
        :param bool [params.closeOrder]: set to True to close position
        :param bool [params.forceHold]: A mark to forcely hold the funds for an order, even though it's an order to reduce the position size. This helps the order stay on the order book and not get canceled when the position size changes. Set to False by default.
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        # required param, cannot be used twice
        clientOrderId = self.safe_string_2(params, 'clientOid', 'clientOrderId', self.uuid())
        params = self.omit(params, ['clientOid', 'clientOrderId'])
        if amount < 1:
            raise InvalidOrder(self.id + ' createOrder() minimum contract order amount is 1')
        preciseAmount = int(self.amount_to_precision(symbol, amount))
        request: dict = {
            'clientOid': clientOrderId,
            'side': side,
            'symbol': market['id'],
            'type': type,  # limit or market
            'size': preciseAmount,
            'leverage': 1,
        }
        stopPrice = self.safe_value_2(params, 'triggerPrice', 'stopPrice')
        if stopPrice:
            request['stop'] = 'up' if (side == 'buy') else 'down'
            stopPriceType = self.safe_string(params, 'stopPriceType', 'TP')
            request['stopPriceType'] = stopPriceType
            request['stopPrice'] = self.price_to_precision(symbol, stopPrice)
        timeInForce = self.safe_string_upper(params, 'timeInForce')
        if type == 'limit':
            if price is None:
                raise ArgumentsRequired(self.id + ' createOrder() requires a price argument for limit orders')
            else:
                request['price'] = self.price_to_precision(symbol, price)
            if timeInForce is not None:
                request['timeInForce'] = timeInForce
        postOnly = self.safe_bool(params, 'postOnly', False)
        hidden = self.safe_value(params, 'hidden')
        if postOnly and (hidden is not None):
            raise BadRequest(self.id + ' createOrder() does not support the postOnly parameter together with a hidden parameter')
        iceberg = self.safe_value(params, 'iceberg')
        if iceberg:
            visibleSize = self.safe_value(params, 'visibleSize')
            if visibleSize is None:
                raise ArgumentsRequired(self.id + ' createOrder() requires a visibleSize parameter for iceberg orders')
        params = self.omit(params, ['timeInForce', 'stopPrice', 'triggerPrice'])  # Time in force only valid for limit orders, exchange error when gtc for market orders
        response = self.privatePostOrders(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #            "orderId": "619717484f1d010001510cde",
        #        },
        #    }
        #
        data = self.safe_value(response, 'data', {})
        return self.safe_order({
            'id': self.safe_string(data, 'orderId'),
            'clientOrderId': None,
            'timestamp': None,
            'datetime': None,
            'lastTradeTimestamp': None,
            'symbol': None,
            'type': None,
            'side': None,
            'price': None,
            'amount': None,
            'cost': None,
            'average': None,
            'filled': None,
            'remaining': None,
            'status': None,
            'fee': None,
            'trades': None,
            'timeInForce': None,
            'postOnly': None,
            'stopPrice': None,
            'info': response,
        }, market)

    def cancel_order(self, id: str, symbol: Str = None, params={}):
        """
        cancels an open order
        :see: https://futures-docs.poloniex.com/#cancel-an-order
        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        request: dict = {
            'order-id': id,
        }
        response = self.privateDeleteOrdersOrderId(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #            "cancelledOrderIds": [
        #                "619714b8b6353000014c505a",
        #            ],
        #            "cancelFailedOrders": [
        #                {
        #                    "orderId": "63a9c5c2b9e7d70007eb0cd5",
        #                    "orderState": "2"
        #                }
        #            ],
        #        },
        #    }
        #
        data = self.safe_value(response, 'data')
        cancelledOrderIds = self.safe_value(data, 'cancelledOrderIds')
        cancelledOrderIdsLength = len(cancelledOrderIds)
        if cancelledOrderIdsLength == 0:
            raise InvalidOrder(self.id + ' cancelOrder() order already cancelled')
        return self.parse_order(data)

    def fetch_positions(self, symbols: Strings = None, params={}):
        """
        fetch all open positions
        :see: https://futures-docs.poloniex.com/#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.privateGetPositions(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 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
        #            }
        #        ]
        #    }
        #
        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: Str
        if Precise.string_gt(size, '0'):
            side = 'long'
        elif Precise.string_lt(size, '0'):
            side = 'short'
        notional = Precise.string_abs(self.safe_string(position, 'posCost'))
        initialMargin = self.safe_string(position, 'posInit')
        initialMarginPercentage = Precise.string_div(initialMargin, notional)
        # marginRatio = Precise.string_div(maintenanceRate, collateral)
        unrealisedPnl = self.safe_string(position, 'unrealisedPnl')
        crossMode = self.safe_value(position, 'crossMode')
        # currently crossMode is always set to False and only isolated positions are supported
        marginMode = 'cross' if crossMode else 'isolated'
        return {
            'info': position,
            'id': None,
            'symbol': self.safe_string(market, 'symbol'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'initialMargin': self.parse_number(initialMargin),
            'initialMarginPercentage': self.parse_number(initialMarginPercentage),
            'maintenanceMargin': self.safe_number(position, 'posMaint'),
            'maintenanceMarginPercentage': self.safe_number(position, 'maintMarginReq'),
            'entryPrice': self.safe_number(position, 'avgEntryPrice'),
            'notional': self.parse_number(notional),
            'leverage': self.safe_number(position, 'realLeverage'),
            'unrealizedPnl': self.parse_number(unrealisedPnl),
            'contracts': self.parse_number(Precise.string_abs(size)),
            'contractSize': self.safe_value(market, 'contractSize'),
            'marginRatio': None,
            'liquidationPrice': self.safe_number(position, 'liquidationPrice'),
            'markPrice': self.safe_number(position, 'markPrice'),
            'collateral': self.safe_number(position, 'maintMargin'),
            'marginMode': marginMode,
            'side': side,
            'percentage': self.parse_number(Precise.string_div(unrealisedPnl, initialMargin)),
            'stopLossPrice': None,
            'takeProfitPrice': None,
        }

    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://futures-docs.poloniex.com/#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.privateGetFundingHistory(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', [])
        dataListLength = len(dataList)
        fees = []
        for i in range(0, dataListLength):
            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 cancel_all_orders(self, symbol: Str = None, params={}):
        """
        cancel all open 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.stop]: When True, all the trigger orders will be cancelled
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        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.privateDeleteStopOrders(self.extend(request, params))
        else:
            response = self.privateDeleteOrders(self.extend(request, params))
        #
        #   {
        #       "code": "200000",
        #       "data": {
        #           "cancelledOrderIds": [
        #                "619714b8b6353000014c505a",
        #           ],
        #       },
        #   }
        #
        data = self.safe_value(response, 'data')
        result = []
        cancelledOrderIds = self.safe_value(data, 'cancelledOrderIds')
        cancelledOrderIdsLength = len(cancelledOrderIds)
        for i in range(0, cancelledOrderIdsLength):
            cancelledOrderId = self.safe_string(cancelledOrderIds, i)
            result.append(self.safe_order({
                'id': cancelledOrderId,
                'clientOrderId': None,
                'timestamp': None,
                'datetime': None,
                'lastTradeTimestamp': None,
                'symbol': None,
                'type': None,
                'side': None,
                'price': None,
                'amount': None,
                'cost': None,
                'average': None,
                'filled': None,
                'remaining': None,
                'status': None,
                'fee': None,
                'trades': None,
                'timeInForce': None,
                'postOnly': None,
                'stopPrice': None,
                'info': response,
            }))
        return result

    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://futures-docs.poloniex.com/#get-order-list
        :see: https://futures-docs.poloniex.com/#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.stop]: 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
        :returns: An `array of order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        stop = self.safe_value_2(params, 'stop', 'trigger')
        until = self.safe_integer(params, 'until')
        params = self.omit(params, ['trigger', 'stop', 'until'])
        if status == 'closed':
            status = 'done'
        request: dict = {}
        if not stop:
            request['status'] = 'active' if (status == 'open') else 'done'
        elif status != 'open':
            raise BadRequest(self.id + ' fetchOrdersByStatus() can only fetch untriggered stop orders')
        market: 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.privateGetStopOrders(self.extend(request, params))
        else:
            response = self.privateGetOrders(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #            "totalNum": 1,
        #            "totalPage": 1,
        #            "pageSize": 50,
        #            "currentPage": 1,
        #            "items": [
        #                {
        #                    "symbol": "ADAUSDTPERP",
        #                    "leverage": "1",
        #                    "hidden": False,
        #                    "forceHold": False,
        #                    "closeOrder": False,
        #                    "type": "limit",
        #                    "isActive": True,
        #                    "createdAt": 1678936920000,
        #                    "orderTime": 1678936920480905922,
        #                    "price": "0.3",
        #                    "iceberg": False,
        #                    "stopTriggered": False,
        #                    "id": "64128b582cc0710007a3c840",
        #                    "value": "3",
        #                    "timeInForce": "GTC",
        #                    "updatedAt": 1678936920000,
        #                    "side": "buy",
        #                    "stopPriceType": "",
        #                    "dealValue": "0",
        #                    "dealSize": 0,
        #                    "settleCurrency": "USDT",
        #                    "stp": "",
        #                    "filledValue": "0",
        #                    "postOnly": False,
        #                    "size": 1,
        #                    "stop": "",
        #                    "filledSize": 0,
        #                    "reduceOnly": False,
        #                    "marginType": 1,
        #                    "cancelExist": False,
        #                    "clientOid": "ba669f39-dfcc-4664-9801-a42d06e59c2e",
        #                    "status": "open"
        #                }
        #            ]
        #        }
        #    }
        #
        responseData = self.safe_value(response, 'data', {})
        orders = self.safe_value(responseData, 'items', [])
        ordersLength = len(orders)
        result = []
        for i in range(0, ordersLength):
            order = orders[i]
            orderStatus = self.safe_string(order, 'status')
            if status == orderStatus:
                result.append(orders[i])
        return self.parse_orders(result, market, since, limit)

    def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
        fetch all unfilled currently open orders
        :see: https://futures-docs.poloniex.com/#get-order-list
        :see: https://futures-docs.poloniex.com/#get-untriggered-stop-order-list
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of  open orders 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
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        return self.fetch_orders_by_status('open', symbol, since, limit, params)

    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://futures-docs.poloniex.com/#get-order-list
        :see: https://futures-docs.poloniex.com/#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
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        return self.fetch_orders_by_status('closed', 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://futures-docs.poloniex.com/#get-details-of-a-single-order
        :see: https://futures-docs.poloniex.com/#get-single-order-by-clientoid
        :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.privateGetClientOrderIdClientOid(self.extend(request, params))
        else:
            request['order-id'] = id
            response = self.privateGetOrdersOrderId(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #            "symbol": "ADAUSDTPERP",
        #            "leverage": "1",
        #            "hidden": False,
        #            "forceHold": False,
        #            "closeOrder": False,
        #            "type": "market",
        #            "isActive": False,
        #            "createdAt": 1678929587000,
        #            "orderTime": 1678929587248115582,
        #            "iceberg": False,
        #            "stopTriggered": False,
        #            "id": "64126eb38c6919000737dcdc",
        #            "value": "3.1783",
        #            "timeInForce": "GTC",
        #            "updatedAt": 1678929587000,
        #            "side": "buy",
        #            "stopPriceType": "",
        #            "dealValue": "3.1783",
        #            "dealSize": 1,
        #            "settleCurrency": "USDT",
        #            "trades": [
        #                {
        #                    "feePay": "0.00158915",
        #                    "tradeId": "64126eb36803eb0001ff99bc"
        #                }
        #            ],
        #            "endAt": 1678929587000,
        #            "stp": "",
        #            "filledValue": "3.1783",
        #            "postOnly": False,
        #            "size": 1,
        #            "stop": "",
        #            "filledSize": 1,
        #            "reduceOnly": False,
        #            "marginType": 1,
        #            "cancelExist": False,
        #            "clientOid": "d19e8fcb-2df4-44bc-afd4-67dd42048246",
        #            "status": "done"
        #        }
        #    }
        #
        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:
        #
        # createOrder
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #            "orderId": "619717484f1d010001510cde",
        #        },
        #    }
        #
        # fetchOrder
        #
        #    {
        #        "symbol": "ADAUSDTPERP",
        #        "leverage": "1",
        #        "hidden": False,
        #        "forceHold": False,
        #        "closeOrder": False,
        #        "type": "market",
        #        "isActive": False,
        #        "createdAt": 1678929587000,
        #        "orderTime": 1678929587248115582,
        #        "iceberg": False,
        #        "stopTriggered": False,
        #        "id": "64126eb38c6919000737dcdc",
        #        "value": "3.1783",
        #        "timeInForce": "GTC",
        #        "updatedAt": 1678929587000,
        #        "side": "buy",
        #        "stopPriceType": "",
        #        "dealValue": "3.1783",
        #        "dealSize": 1,
        #        "settleCurrency": "USDT",
        #        "trades": [
        #            {
        #                "feePay": "0.00158915",
        #                "tradeId": "64126eb36803eb0001ff99bc"
        #            }
        #        ],
        #        "endAt": 1678929587000,
        #        "stp": "",
        #        "filledValue": "3.1783",
        #        "postOnly": False,
        #        "size": 1,
        #        "stop": "",
        #        "filledSize": 1,
        #        "reduceOnly": False,
        #        "marginType": 1,
        #        "cancelExist": False,
        #        "clientOid": "d19e8fcb-2df4-44bc-afd4-67dd42048246",
        #        "status": "done"
        #    }
        #
        # cancelOrder
        #
        #    {
        #        "cancelledOrderIds": [
        #            "619714b8b6353000014c505a",
        #        ],
        #        "cancelFailedOrders": [
        #            {
        #                "orderId": "63a9c5c2b9e7d70007eb0cd5",
        #                "orderState": "2"
        #            }
        #        ],
        #    },
        #
        marketId = self.safe_string(order, 'symbol')
        market = self.safe_market(marketId, market)
        timestamp = self.safe_integer(order, 'createdAt')
        # price is zero for market order
        # omitZero is called in safeOrder2
        feeCurrencyId = self.safe_string(order, 'feeCurrency')
        filled = self.safe_string(order, 'dealSize')
        rawCost = self.safe_string_2(order, 'dealFunds', 'filledValue')
        average: Str = None
        if Precise.string_gt(filled, '0'):
            contractSize = self.safe_string(market, 'contractSize')
            if market['linear']:
                average = Precise.string_div(rawCost, Precise.string_mul(contractSize, filled))
            else:
                average = Precise.string_div(Precise.string_mul(contractSize, filled), rawCost)
        # precision reported by their api is 8 d.p.
        # average = Precise.string_div(rawCost, Precise.string_mul(filled, market['contractSize']))
        # bool
        isActive = self.safe_bool(order, 'isActive', False)
        cancelExist = self.safe_bool(order, 'cancelExist', False)
        status = 'open' if isActive else 'closed'
        id = self.safe_string(order, 'id')
        if 'cancelledOrderIds' in order:
            cancelledOrderIds = self.safe_value(order, 'cancelledOrderIds')
            id = self.safe_string(cancelledOrderIds, 0)
        return self.safe_order({
            'info': order,
            'id': id,
            'clientOrderId': self.safe_string(order, 'clientOid'),
            'symbol': self.safe_string(market, 'symbol'),
            'type': self.safe_string(order, 'type'),
            'timeInForce': self.safe_string(order, 'timeInForce'),
            'postOnly': self.safe_value(order, 'postOnly'),
            'side': self.safe_string(order, 'side'),
            'amount': self.safe_string(order, 'size'),
            'price': self.safe_string(order, 'price'),
            'stopPrice': self.safe_string(order, 'stopPrice'),
            'cost': self.safe_string(order, 'dealValue'),
            'filled': filled,
            'remaining': None,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'fee': {
                'currency': self.safe_currency_code(feeCurrencyId),
                'cost': self.safe_string(order, 'fee'),
            },
            'status': 'canceled' if cancelExist else status,
            'lastTradeTimestamp': None,
            'average': average,
            'trades': None,
        }, market)

    def fetch_funding_rate(self, symbol: str, params={}):
        """
        fetch the current funding rate
        :see: https://futures-docs.poloniex.com/#get-premium-index
        :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.publicGetFundingRateSymbolCurrent(self.extend(request, params))
        #
        #    {
        #        "symbol": ".BTCUSDTPERPFPI8H",
        #        "granularity": 28800000,
        #        "timePoint": 1558000800000,
        #        "value": 0.00375,
        #        "predictedValue": 0.00375
        #    }
        #
        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, 'predictedValue'),
            'fundingTimestamp': None,
            'fundingDatetime': None,
            'nextFundingRate': None,
            'nextFundingTimestamp': None,
            'nextFundingDatetime': None,
            'previousFundingRate': self.safe_number(data, 'value'),
            'previousFundingTimestamp': fundingTimestamp,
            'previousFundingDatetime': self.iso8601(fundingTimestamp),
        }

    def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        fetch all trades made by the user
        :see: https://futures-docs.poloniex.com/#get-fills
        :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 str orderIdFills: filles for a specific order(other parameters can be ignored if specified)
        :param str side: buy or sell
        :param str type:  limit, market, limit_stop or market_stop
        :param int endAt: end time(milisecond)
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        """
        self.load_markets()
        request: dict = {
        }
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            request['startAt'] = since
        response = self.privateGetFills(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #          "currentPage":1,
        #          "pageSize":1,
        #          "totalNum":251915,
        #          "totalPage":251915,
        #          "items":[
        #              {
        #                "symbol": "BTCUSDTPERP",  #Ticker symbol of the contract
        #                "tradeId": "5ce24c1f0c19fc3c58edc47c",  #Trade ID
        #                "orderId": "5ce24c16b210233c36ee321d",  # Order ID
        #                "side": "sell",  #Transaction side
        #                "liquidity": "taker",  #Liquidity- taker or maker
        #                "price": "8302",  #Filled price
        #                "size": 10,  #Filled amount
        #                "value": "0.001204529",  #Order value
        #                "feeRate": "0.0005",  #Floating fees
        #                "fixFee": "0.00000006",  #Fixed fees
        #                "feeCurrency": "XBT",  #Charging currency
        #                "stop": "",  #A mark to the stop order type
        #                "fee": "0.0000012022",  #Transaction fee
        #                "orderType": "limit",  #Order type
        #                "tradeType": "trade",  #Trade type(trade, liquidation, ADL or settlement)
        #                "createdAt": 1558334496000,  #Time the order created
        #                "settleCurrency": "XBT",  #settlement currency
        #                "tradeTime": 1558334496000000000  #trade time in nanosecond
        #              }
        #          ]
        #        }
        #    }
        #
        data = self.safe_value(response, 'data', {})
        trades = self.safe_list(data, 'items', [])
        return self.parse_trades(trades, market, since, limit)

    def set_margin_mode(self, marginMode: str, symbol: Str = None, params={}):
        """
        set margin mode to 'cross' or 'isolated'
        :see: https://futures-docs.poloniex.com/#change-margin-mode
        :param str marginMode: "0"(isolated) or "1"(cross)
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' setMarginMode() requires a symbol argument')
        if (marginMode != '0') and (marginMode != '1') and (marginMode != 'isolated') and (marginMode != 'cross'):
            raise ArgumentsRequired(self.id + ' setMarginMode() marginMode must be 0/isolated or 1/cross')
        self.load_markets()
        if marginMode == 'isolated':
            marginMode = '0'
        if marginMode == 'cross':
            marginMode = '1'
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
            'marginType': self.parse_to_int(marginMode),
        }
        return self.privatePostMarginTypeChange(request)

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = self.urls['api'][api]
        versions = self.safe_value(self.options, 'versions', {})
        apiVersions = self.safe_value(versions, api, {})
        methodVersions = self.safe_value(apiVersions, method, {})
        defaultVersion = self.safe_string(methodVersions, path, self.version)
        version = self.safe_string(params, 'version', defaultVersion)
        tail = '/api/' + version + '/' + self.implode_params(path, params)
        url += tail
        query = self.omit(params, self.extract_params(path))
        queryLength = query
        if api == 'public':
            if queryLength:
                url += '?' + self.urlencode(query)
        else:
            self.check_required_credentials()
            endpoint = '/api/v1/' + self.implode_params(path, params)
            bodyEncoded = self.urlencode(query)
            if method != 'GET' and method != 'HEAD':
                body = query
            else:
                if queryLength and bodyEncoded != '':
                    url += '?' + bodyEncoded
                    endpoint += '?' + bodyEncoded
            now = str(self.milliseconds())
            endpart = ''
            if body is not None:
                body = self.json(query)
                endpart = body
            payload = now + method + endpoint + endpart
            signature = self.hmac(self.encode(payload), self.encode(self.secret), hashlib.sha256, 'base64')
            headers = {
                'PF-API-SIGN': signature,
                'PF-API-TIMESTAMP': now,
                'PF-API-KEY': self.apiKey,
                'PF-API-PASSPHRASE': self.password,
            }
            headers['Content-Type'] = 'application/json'
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, code: int, reason: str, url: str, method: str, headers: dict, body: str, response, requestHeaders, requestBody):
        if not response:
            self.throw_broadly_matched_exception(self.exceptions['broad'], body, body)
            return None
        #
        # bad
        #     {"code": "400100", "msg": "validation.createOrder.clientOidIsRequired"}
        # good
        #     {code: "200000", data: {...}}
        #
        errorCode = self.safe_string(response, 'code')
        message = self.safe_string(response, 'msg', '')
        feedback = self.id + ' ' + message
        self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
        self.throw_exactly_matched_exception(self.exceptions['exact'], errorCode, feedback)
        self.throw_broadly_matched_exception(self.exceptions['broad'], body, feedback)
        return None
