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

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

from ccxt.async_support.base.exchange import Exchange
import hashlib
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):

    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': False,
            'version': 'v1',
            'has': {
                'CORS': None,
                'spot': False,
                'margin': True,
                'swap': True,
                'future': False,
                'option': None,
                'createOrder': True,
                'fetchBalance': True,
                'fetchClosedOrders': True,
                'fetchCurrencies': False,
                'fetchFundingRate': True,
                '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,
                        'orders': 1,
                        'stopOrders': 1,
                        'recentDoneOrders': 1,
                        'orders/{order-id}': 1,
                        'fills': 1,
                        'openOrderStatistics': 1,
                        'position': 1.5,
                        'positions': 1.5,
                        'funding-history': 1,
                        'marginType/query': 1,
                    },
                    'post': {
                        'orders': 1.5,
                        'batchOrders': 1.5,
                        'position/margin/auto-deposit-status': 1.5,
                        'position/margin/deposit-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"}
                },
            },
        })

    async def fetch_markets(self, params={}):
        """
        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 = await 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'
        #     },
        #   ]
        # }
        #
        result = []
        data = self.safe_value(response, 'data', [])
        dataLength = len(data)
        for i in range(0, dataLength):
            market = data[i]
            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')
            result.append({
                '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,
                    },
                },
                'info': market,
            })
        return result

    def parse_ticker(self, ticker, market=None):
        marketId = self.safe_string(ticker, 'symbol')
        symbol = self.safe_symbol(marketId, market)
        timestamp = self.safe_integer_product(ticker, 'ts', 0.000001)
        last = self.safe_string(ticker, 'price')
        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': None,
            'average': None,
            'baseVolume': self.safe_string(ticker, 'size'),
            'quoteVolume': None,
            'info': ticker,
        }, market)

    async def fetch_ticker(self, symbol, params={}):
        """
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        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 poloniexfutures api endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.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)

    async def fetch_tickers(self, symbols=None, params={}):
        """
        fetches price tickers for multiple markets, statistical calculations with the information calculated over the past 24 hours each market
        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 poloniexfutures api endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        await self.load_markets()
        response = await self.publicGetTickers(params)
        return self.parse_tickers(self.safe_value(response, 'data', []), symbols)

    async def fetch_order_book(self, symbol, limit=None, params={}):
        """
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        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|None limit: the maximum amount of order book entries to return
        :param dict params: extra parameters specific to the poloniexfuturesfutures api endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbols
        """
        await self.load_markets()
        level = self.safe_number(params, 'level')
        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 = {
            'symbol': market['id'],
        }
        response = None
        if level == 3:
            response = await self.publicGetLevel3Snapshot(self.extend(request, params))
        else:
            response = await 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

    async def fetch_l3_order_book(self, symbol, limit=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|None limit: max number of orders to return, default is None
        :param dict params: extra parameters specific to the blockchaincom api endpoint
        :returns dict: an `order book structure <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        return self.fetch_order_book(market['id'], None, {'level': 3})

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

    async def fetch_trades(self, symbol, since=None, limit=None, params={}):
        """
        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|None since: timestamp in ms of the earliest trade to fetch
        :param int|None limit: the maximum amount of trades to fetch
        :param dict params: extra parameters specific to the poloniexfutures api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html?#public-trades>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.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_value(response, 'data', [])
        return self.parse_trades(trades, market, since, limit)

    async 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 poloniexfutures api endpoint
        :returns int: the current integer timestamp in milliseconds from the poloniexfutures server
        """
        response = await self.publicGetTimestamp(params)
        #
        # {
        #     "code":"200000",
        #     "msg":"success",
        #     "data":1546837113087
        # }
        #
        return self.safe_integer(response, 'data')

    async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
        """
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        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|None since: timestamp in ms of the earliest candle to fetch
        :param int|None limit: the maximum amount of candles to fetch
        :param dict params: extra parameters specific to the poloniexfutures api endpoint
        :returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume
        """
        await self.load_markets()
        market = self.market(symbol)
        marketId = market['id']
        request = {
            'symbol': marketId,
            'granularity': self.safe_integer(self.timeframes, timeframe, timeframe),
        }
        duration = self.parse_timeframe(timeframe) * 1000
        endAt = self.milliseconds()
        if since is not None:
            request['from'] = since
            if limit is None:
                limit = self.safe_integer(self.options, 'fetchOHLCVLimit', 200)
            endAt = self.sum(since, limit * duration)
            request['to'] = endAt
        elif limit is not None:
            since = endAt - limit * duration
            request['from'] = since
        response = await 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_value(response, 'data', [])
        return self.parse_ohlcvs(data, market, timeframe, since, limit)

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

    async def fetch_balance(self, params={}):
        """
        query for balance and get the amount of funds available for trading or funds locked in orders
        see https://futures-docs.poloniex.com/#get-account-overview
        :param dict params: extra parameters specific to the poloniexfutures api endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>`
        """
        await self.load_markets()
        currencyId = self.safe_string(params, 'currency')
        request = {}
        if currencyId is not None:
            currency = self.currency(currencyId)
            request = {
                'currency': currency['id'],
            }
        response = await 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)

    async def create_order(self, symbol, type, side, amount, price=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/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        # required param, cannot be used twice
        clientOrderId = self.safe_string_2(params, 'clientOid', 'clientOrderId', self.uuid())
        params = self.omit(params, ['clientOid', 'clientOrderId'])
        if amount < 1:
            raise InvalidOrder(self.id + ' createOrder() minimum contract order amount is 1')
        preciseAmount = int(self.amount_to_precision(symbol, amount))
        request = {
            'clientOid': clientOrderId,
            'side': side,
            'symbol': market['id'],
            'type': type,  # limit or market
            'size': preciseAmount,
            'leverage': 1,
        }
        stopPrice = self.safe_value_2(params, 'triggerPrice', 'stopPrice')
        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_value(params, 'postOnly', False)
        hidden = self.safe_value(params, 'hidden')
        if postOnly and (hidden is not None):
            raise BadRequest(self.id + ' createOrder() does not support the postOnly parameter together with a hidden parameter')
        iceberg = self.safe_value(params, 'iceberg')
        if iceberg:
            visibleSize = self.safe_value(params, 'visibleSize')
            if visibleSize is None:
                raise ArgumentsRequired(self.id + ' createOrder() requires a visibleSize parameter for iceberg orders')
        params = self.omit(params, ['timeInForce', 'stopPrice', 'triggerPrice'])  # Time in force only valid for limit orders, exchange error when gtc for market orders
        response = await self.privatePostOrders(self.extend(request, params))
        #
        #    {
        #        code: "200000",
        #        data: {
        #            orderId: "619717484f1d010001510cde",
        #        },
        #    }
        #
        data = self.safe_value(response, 'data', {})
        return {
            'id': self.safe_string(data, 'orderId'),
            'clientOrderId': None,
            'timestamp': None,
            'datetime': None,
            'lastTradeTimestamp': None,
            'symbol': None,
            'type': None,
            'side': None,
            'price': None,
            'amount': None,
            'cost': None,
            'average': None,
            'filled': None,
            'remaining': None,
            'status': None,
            'fee': None,
            'trades': None,
            'timeInForce': None,
            'postOnly': None,
            'stopPrice': None,
            'info': response,
        }

    async def cancel_order(self, id, symbol=None, params={}):
        """
        cancels an open order
        see https://futures-docs.poloniex.com/#cancel-an-order
        :param str id: order id
        :param str|None symbol: unified symbol of the market the order was made in
        :param dict params: extra parameters specific to the poloniexfutures api endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        request = {
            'order-id': id,
        }
        response = await 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 {
            'id': self.safe_string(cancelledOrderIds, 0),
            '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,
        }

    async def fetch_positions(self, symbols=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 poloniexfutures api endpoint
        :returns [dict]: a list of `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        """
        await self.load_markets()
        response = await self.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_value(response, 'data')
        return self.parse_positions(data, symbols)

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

    async def fetch_funding_history(self, symbol=None, since=None, limit=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|None since: the earliest time in ms to fetch funding history for
        :param int|None limit: the maximum number of funding history structures to retrieve
        :param dict params: extra parameters specific to the poloniexfutures api endpoint
        :returns dict: a `funding history structure <https://docs.ccxt.com/en/latest/manual.html#funding-history-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchFundingHistory() requires a symbol argument')
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if since is not None:
            request['startAt'] = since
        if limit is not None:
            # * Since is ignored if limit is defined
            request['maxCount'] = limit
        response = await self.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

    async def cancel_all_orders(self, symbol=None, params={}):
        """
        cancel all open orders
        :param str|None symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict params: extra parameters specific to the poloniexfutures 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/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        request = {}
        if symbol is not None:
            request['symbol'] = self.market_id(symbol)
        stop = self.safe_value(params, 'stop')
        method = 'privateDeleteStopOrders' if stop else 'privateDeleteOrders'
        response = await getattr(self, method)(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({
                '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

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

    async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        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|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch open orders for
        :param int|None limit: the maximum number of  open orders structures to retrieve
        :param dict params: extra parameters specific to the poloniexfutures api endpoint
        :param int|None params['till']: end time in ms
        :param str|None params['side']: buy or sell
        :param str|None params['type']: limit, or market
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        return await self.fetch_orders_by_status('active', symbol, since, limit, params)

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

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

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

    async def fetch_funding_rate(self, symbol, params={}):
        """
        fetch the current funding rate
        see https://futures-docs.poloniex.com/#get-premium-index
        :param str symbol: unified market symbol
        :param dict params: extra parameters specific to the poloniexfutures api endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/en/latest/manual.html#funding-rate-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.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),
        }

    async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
        """
        fetch all trades made by the user
        see https://futures-docs.poloniex.com/#get-fills
        :param str|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch trades for
        :param int|None limit: the maximum number of trades structures to retrieve
        :param dict params: extra parameters specific to the poloniexfutures api endpoint
        :param str|None orderIdFills: filles for a specific order(other parameters can be ignored if specified)
        :param str|None side: buy or sell
        :param str|None type:  limit, market, limit_stop or market_stop
        :param int|None endAt: end time(milisecond)
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
        """
        await self.load_markets()
        request = {
        }
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            request['startAt'] = since
        response = await self.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_value(data, 'items', {})
        return self.parse_trades(trades, market, since, limit)

    async def set_margin_mode(self, marginMode, symbol, params={}):
        """
        set margin mode to 'cross' or 'isolated'
        see https://futures-docs.poloniex.com/#change-margin-mode
        :param int marginMode: 0(isolated) or 1(cross)
        :param str symbol: unified market symbol
        :param dict params: extra parameters specific to the poloniexfutures 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):
            raise ArgumentsRequired(self.id + ' setMarginMode() marginMode must be 0(isolated) or 1(cross)')
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            'marginType': marginMode,
        }
        return await 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, 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, reason, url, method, headers, body, response, requestHeaders, requestBody):
        if not response:
            self.throw_broadly_matched_exception(self.exceptions['broad'], body, body)
            return
        #
        # 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)
