# -*- 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.onetrading import ImplicitAPI
from ccxt.base.types import Any, Balances, Currencies, Int, Market, Num, Order, OrderBook, OrderSide, OrderType, Str, Strings, Ticker, Tickers, Trade, TradingFees
from typing import List
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidAddress
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import NotSupported
from ccxt.base.errors import DDoSProtection
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class onetrading(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(onetrading, self).describe(), {
            'id': 'onetrading',
            'name': 'One Trading',
            'countries': ['AT'],  # Austria
            'rateLimit': 300,
            'version': 'v1',
            'pro': True,
            # new metainfo interface
            'has': {
                'CORS': None,
                'spot': True,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'addMargin': False,
                'borrowCrossMargin': False,
                'borrowIsolatedMargin': False,
                'borrowMargin': False,
                'cancelAllOrders': True,
                'cancelOrder': True,
                'cancelOrders': True,
                'closeAllPositions': False,
                'closePosition': False,
                'createDepositAddress': False,
                'createOrder': True,
                'createReduceOnlyOrder': False,
                'createStopLimitOrder': True,
                'createStopMarketOrder': False,
                'createStopOrder': True,
                'fetchAccounts': False,
                'fetchAllGreeks': False,
                'fetchBalance': True,
                'fetchBorrowInterest': False,
                'fetchBorrowRate': False,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchBorrowRates': False,
                'fetchBorrowRatesPerSymbol': False,
                'fetchClosedOrders': True,
                'fetchCrossBorrowRate': False,
                'fetchCrossBorrowRates': False,
                'fetchCurrencies': True,
                'fetchDeposit': False,
                'fetchDepositAddress': False,
                'fetchDepositAddresses': False,
                'fetchDepositAddressesByNetwork': False,
                'fetchDeposits': False,
                'fetchDepositsWithdrawals': False,
                'fetchFundingHistory': False,
                'fetchFundingInterval': False,
                'fetchFundingIntervals': False,
                'fetchFundingRate': False,
                'fetchFundingRateHistory': False,
                'fetchFundingRates': False,
                'fetchGreeks': False,
                'fetchIndexOHLCV': False,
                'fetchIsolatedBorrowRate': False,
                'fetchIsolatedBorrowRates': False,
                'fetchIsolatedPositions': False,
                'fetchLedger': False,
                'fetchLeverage': False,
                'fetchLeverages': False,
                'fetchLeverageTiers': False,
                'fetchLiquidations': False,
                'fetchLongShortRatio': False,
                'fetchLongShortRatioHistory': False,
                'fetchMarginAdjustmentHistory': False,
                'fetchMarginMode': False,
                'fetchMarginModes': False,
                'fetchMarketLeverageTiers': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMarkPrice': False,
                'fetchMarkPrices': False,
                'fetchMyLiquidations': False,
                'fetchMySettlementHistory': False,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenInterest': False,
                'fetchOpenInterestHistory': False,
                'fetchOpenInterests': False,
                'fetchOpenOrders': True,
                'fetchOption': False,
                'fetchOptionChain': False,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrders': False,
                'fetchOrderTrades': True,
                'fetchPosition': False,
                'fetchPositionHistory': False,
                'fetchPositionMode': False,
                'fetchPositions': False,
                'fetchPositionsForSymbol': False,
                'fetchPositionsHistory': False,
                'fetchPositionsRisk': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchSettlementHistory': False,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTime': True,
                'fetchTrades': False,
                'fetchTradingFee': False,
                'fetchTradingFees': True,
                'fetchTransactionFee': False,
                'fetchTransactionFees': False,
                'fetchTransactions': False,
                'fetchTransfer': False,
                'fetchTransfers': False,
                'fetchUnderlyingAssets': False,
                'fetchVolatilityHistory': False,
                'fetchWithdrawal': False,
                'fetchWithdrawals': False,
                'reduceMargin': False,
                'repayCrossMargin': False,
                'repayIsolatedMargin': False,
                'setLeverage': False,
                'setMargin': False,
                'setMarginMode': False,
                'setPositionMode': False,
                'transfer': False,
                'withdraw': False,
            },
            'timeframes': {
                '1m': '1/MINUTES',
                '5m': '5/MINUTES',
                '15m': '15/MINUTES',
                '30m': '30/MINUTES',
                '1h': '1/HOURS',
                '4h': '4/HOURS',
                '1d': '1/DAYS',
                '1w': '1/WEEKS',
                '1M': '1/MONTHS',
            },
            'urls': {
                'logo': 'https://github.com/ccxt/ccxt/assets/43336371/bdbc26fd-02f2-4ca7-9f1e-17333690bb1c',
                'api': {
                    'public': 'https://api.onetrading.com/fast',
                    'private': 'https://api.onetrading.com/fast',
                },
                'www': 'https://onetrading.com/',
                'doc': [
                    'https://docs.onetrading.com',
                ],
                'fees': 'https://onetrading.com/fees',
            },
            'api': {
                'public': {
                    'get': [
                        'currencies',
                        'candlesticks/{instrument_code}',
                        'fees',
                        'instruments',
                        'order-book/{instrument_code}',
                        'market-ticker',
                        'market-ticker/{instrument_code}',
                        'time',
                    ],
                },
                'private': {
                    'get': [
                        'account/balances',
                        'account/fees',
                        'account/orders',
                        'account/orders/{order_id}',
                        'account/orders/{order_id}/trades',
                        'account/trades',
                        'account/trades/{trade_id}',
                    ],
                    'post': [
                        'account/orders',
                    ],
                    'delete': [
                        'account/orders',
                        'account/orders/{order_id}',
                        'account/orders/client/{client_id}',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'tierBased': True,
                    'percentage': True,
                    'taker': self.parse_number('0.0015'),
                    'maker': self.parse_number('0.001'),
                    'tiers': [
                        # volume in BTC
                        {
                            'taker': [
                                [self.parse_number('0'), self.parse_number('0.0015')],
                                [self.parse_number('100'), self.parse_number('0.0013')],
                                [self.parse_number('250'), self.parse_number('0.0013')],
                                [self.parse_number('1000'), self.parse_number('0.001')],
                                [self.parse_number('5000'), self.parse_number('0.0009')],
                                [self.parse_number('10000'), self.parse_number('0.00075')],
                                [self.parse_number('20000'), self.parse_number('0.00065')],
                            ],
                            'maker': [
                                [self.parse_number('0'), self.parse_number('0.001')],
                                [self.parse_number('100'), self.parse_number('0.001')],
                                [self.parse_number('250'), self.parse_number('0.0009')],
                                [self.parse_number('1000'), self.parse_number('0.00075')],
                                [self.parse_number('5000'), self.parse_number('0.0006')],
                                [self.parse_number('10000'), self.parse_number('0.0005')],
                                [self.parse_number('20000'), self.parse_number('0.0005')],
                            ],
                        },
                    ],
                },
            },
            'requiredCredentials': {
                'apiKey': True,
                'secret': False,
            },
            'precisionMode': TICK_SIZE,
            'exceptions': {
                'exact': {
                    'INVALID_CLIENT_UUID': InvalidOrder,
                    'ORDER_NOT_FOUND': OrderNotFound,
                    'ONLY_ONE_ERC20_ADDRESS_ALLOWED': InvalidAddress,
                    'DEPOSIT_ADDRESS_NOT_USED': InvalidAddress,
                    'INVALID_CREDENTIALS': AuthenticationError,
                    'MISSING_CREDENTIALS': AuthenticationError,
                    'INVALID_APIKEY': AuthenticationError,
                    'INVALID_SCOPES': AuthenticationError,
                    'INVALID_SUBJECT': AuthenticationError,
                    'INVALID_ISSUER': AuthenticationError,
                    'INVALID_AUDIENCE': AuthenticationError,
                    'INVALID_DEVICE_ID': AuthenticationError,
                    'INVALID_IP_RESTRICTION': AuthenticationError,
                    'APIKEY_REVOKED': AuthenticationError,
                    'APIKEY_EXPIRED': AuthenticationError,
                    'SYNCHRONIZER_TOKEN_MISMATCH': AuthenticationError,
                    'SESSION_EXPIRED': AuthenticationError,
                    'INTERNAL_ERROR': AuthenticationError,
                    'CLIENT_IP_BLOCKED': PermissionDenied,
                    'MISSING_PERMISSION': PermissionDenied,
                    'ILLEGAL_CHARS': BadRequest,
                    'UNSUPPORTED_MEDIA_TYPE': BadRequest,
                    'ACCOUNT_HISTORY_TIME_RANGE_TOO_BIG': BadRequest,
                    'CANDLESTICKS_TIME_RANGE_TOO_BIG': BadRequest,
                    'INVALID_INSTRUMENT_CODE': BadRequest,
                    'INVALID_ORDER_TYPE': BadRequest,
                    'INVALID_UNIT': BadRequest,
                    'INVALID_PERIOD': BadRequest,
                    'INVALID_TIME': BadRequest,
                    'INVALID_DATE': BadRequest,
                    'INVALID_CURRENCY': BadRequest,
                    'INVALID_AMOUNT': BadRequest,
                    'INVALID_PRICE': BadRequest,
                    'INVALID_LIMIT': BadRequest,
                    'INVALID_QUERY': BadRequest,
                    'INVALID_CURSOR': BadRequest,
                    'INVALID_ACCOUNT_ID': BadRequest,
                    'INVALID_SIDE': InvalidOrder,
                    'INVALID_ACCOUNT_HISTORY_FROM_TIME': BadRequest,
                    'INVALID_ACCOUNT_HISTORY_MAX_PAGE_SIZE': BadRequest,
                    'INVALID_ACCOUNT_HISTORY_TIME_PERIOD': BadRequest,
                    'INVALID_ACCOUNT_HISTORY_TO_TIME': BadRequest,
                    'INVALID_CANDLESTICKS_GRANULARITY': BadRequest,
                    'INVALID_CANDLESTICKS_UNIT': BadRequest,
                    'INVALID_ORDER_BOOK_DEPTH': BadRequest,
                    'INVALID_ORDER_BOOK_LEVEL': BadRequest,
                    'INVALID_PAGE_CURSOR': BadRequest,
                    'INVALID_TIME_RANGE': BadRequest,
                    'INVALID_TRADE_ID': BadRequest,
                    'INVALID_UI_ACCOUNT_SETTINGS': BadRequest,
                    'NEGATIVE_AMOUNT': InvalidOrder,
                    'NEGATIVE_PRICE': InvalidOrder,
                    'MIN_SIZE_NOT_SATISFIED': InvalidOrder,
                    'BAD_AMOUNT_PRECISION': InvalidOrder,
                    'BAD_PRICE_PRECISION': InvalidOrder,
                    'BAD_TRIGGER_PRICE_PRECISION': InvalidOrder,
                    'MAX_OPEN_ORDERS_EXCEEDED': BadRequest,
                    'MISSING_PRICE': InvalidOrder,
                    'MISSING_ORDER_TYPE': InvalidOrder,
                    'MISSING_SIDE': InvalidOrder,
                    'MISSING_CANDLESTICKS_PERIOD_PARAM': ArgumentsRequired,
                    'MISSING_CANDLESTICKS_UNIT_PARAM': ArgumentsRequired,
                    'MISSING_FROM_PARAM': ArgumentsRequired,
                    'MISSING_INSTRUMENT_CODE': ArgumentsRequired,
                    'MISSING_ORDER_ID': InvalidOrder,
                    'MISSING_TO_PARAM': ArgumentsRequired,
                    'MISSING_TRADE_ID': ArgumentsRequired,
                    'INVALID_ORDER_ID': OrderNotFound,
                    'NOT_FOUND': OrderNotFound,
                    'INSUFFICIENT_LIQUIDITY': InsufficientFunds,
                    'INSUFFICIENT_FUNDS': InsufficientFunds,
                    'NO_TRADING': ExchangeNotAvailable,
                    'SERVICE_UNAVAILABLE': ExchangeNotAvailable,
                    'GATEWAY_TIMEOUT': ExchangeNotAvailable,
                    'RATELIMIT': DDoSProtection,
                    'CF_RATELIMIT': DDoSProtection,
                    'INTERNAL_SERVER_ERROR': ExchangeError,
                },
                'broad': {
                    'Order not found.': OrderNotFound,
                },
            },
            'commonCurrencies': {
                'MIOTA': 'IOTA',  # https://github.com/ccxt/ccxt/issues/7487
            },
            # exchange-specific options
            'options': {
                'fetchTradingFees': {
                    'method': 'fetchPrivateTradingFees',  # or 'fetchPublicTradingFees'
                },
                'fiat': ['EUR', 'CHF'],
            },
            'features': {
                'spot': {
                    'sandbox': False,
                    'createOrder': {
                        'marginMode': False,
                        'triggerPrice': False,
                        'triggerDirection': False,
                        'triggerPriceType': None,
                        'stopLossPrice': False,
                        'takeProfitPrice': False,
                        'attachedStopLossTakeProfit': None,
                        'timeInForce': {
                            'IOC': True,
                            'FOK': True,
                            'PO': True,
                            'GTD': False,
                        },
                        'hedged': False,
                        'trailing': False,
                        'leverage': False,
                        'marketBuyByCost': False,
                        'marketBuyRequiresPrice': False,
                        'selfTradePrevention': False,
                        'iceberg': False,
                    },
                    'createOrders': None,
                    'fetchMyTrades': {
                        'marginMode': False,
                        'limit': 100,
                        'daysBack': 100000,  # todo
                        'untilDays': 100000,  # todo
                        'symbolRequired': False,
                    },
                    'fetchOrder': {
                        'marginMode': False,
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOpenOrders': {
                        'marginMode': False,
                        'limit': 100,
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOrders': None,  # todo
                    'fetchClosedOrders': {
                        'marginMode': False,
                        'limit': 100,
                        'daysBack': 100000,  # todo
                        'daysBackCanceled': 1 / 12,  # todo
                        'untilDays': 100000,  # todo
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOHLCV': {
                        'limit': 5000,
                    },
                },
                'swap': {
                    'linear': None,
                    'inverse': None,
                },
                'future': {
                    'linear': None,
                    'inverse': None,
                },
            },
        })

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

        https://docs.onetrading.com/#time

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        """
        response = self.publicGetTime(params)
        #
        #     {
        #         "iso": "2020-07-10T05:17:26.716Z",
        #         "epoch_millis": 1594358246716,
        #     }
        #
        return self.safe_integer(response, 'epoch_millis')

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

        https://docs.onetrading.com/#currencies

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        """
        response = self.publicGetCurrencies(params)
        #
        #     [
        #         {
        #             "code": "USDT",
        #             "precision": 6,
        #             "unified_cryptoasset_id": 825,
        #             "name": "Tether USDt",
        #             "collateral_percentage": 0
        #         },
        #     ]
        #
        result: dict = {}
        for i in range(0, len(response)):
            currency = response[i]
            id = self.safe_string(currency, 'code')
            code = self.safe_currency_code(id)
            result[code] = self.safe_currency_structure({
                'id': id,
                'code': code,
                'name': self.safe_string(currency, 'name'),
                'info': currency,
                'active': None,
                'fee': None,
                'precision': self.parse_number(self.parse_precision(self.safe_string(currency, 'precision'))),
                'withdraw': None,
                'deposit': None,
                'limits': {
                    'amount': {'min': None, 'max': None},
                    'withdraw': {'min': None, 'max': None},
                },
                'networks': {},
            })
        return result

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

        https://docs.onetrading.com/#instruments

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = self.publicGetInstruments(params)
        #
        #     [
        #         {
        #             "state": "ACTIVE",
        #             "base": {code: "ETH", precision: 8},
        #             "quote": {code: "CHF", precision: 2},
        #             "amount_precision": 4,
        #             "market_precision": 2,
        #             "min_size": "10.0"
        #         }
        #     ]
        #
        return self.parse_markets(response)

    def parse_market(self, market: dict) -> Market:
        #
        #   {
        #      "base":{
        #         "code":"BTC",
        #         "precision":"5"
        #      },
        #      "quote":{
        #         "code":"USDC",
        #         "precision":"2"
        #      },
        #      "amount_precision":"5",
        #      "market_precision":"2",
        #      "min_size":"10.0",
        #      "min_price":"1000",
        #      "max_price":"10000000",
        #      "id":"BTC_USDC",
        #      "type":"SPOT",
        #      "state":"ACTIVE"
        #   }
        #
        #
        #  {
        #      "base": {
        #          "code": "BTC",
        #          "precision": 5
        #      },
        #      "quote": {
        #          "code": "EUR",
        #          "precision": 2
        #      },
        #      "amount_precision": 5,
        #      "market_precision": 2,
        #      "min_size": "10.0",
        #      "min_price": "1000",
        #      "max_price": "10000000",
        #      "id": "BTC_EUR_P",
        #      "type": "PERP",
        #      "state": "ACTIVE"
        #  }
        #
        baseAsset = self.safe_dict(market, 'base', {})
        quoteAsset = self.safe_dict(market, 'quote', {})
        baseId = self.safe_string(baseAsset, 'code')
        quoteId = self.safe_string(quoteAsset, 'code')
        id = self.safe_string(market, 'id')
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        state = self.safe_string(market, 'state')
        type = self.safe_string(market, 'type')
        isPerp = type == 'PERP'
        symbol = base + '/' + quote
        if isPerp:
            symbol = symbol + ':' + quote
        return {
            'id': id,
            'symbol': symbol,
            'base': base,
            'quote': quote,
            'settle': quote if isPerp else None,
            'baseId': baseId,
            'quoteId': quoteId,
            'settleId': quoteId if isPerp else None,
            'type': 'swap' if isPerp else 'spot',
            'spot': not isPerp,
            'margin': False,
            'swap': isPerp,
            'future': False,
            'option': False,
            'active': (state == 'ACTIVE'),
            'contract': isPerp,
            'linear': True if isPerp else None,
            'inverse': False if isPerp else None,
            'contractSize': self.parse_number('1') if isPerp else None,
            'expiry': None,
            'expiryDatetime': None,
            'strike': None,
            'optionType': None,
            'precision': {
                'amount': self.parse_number(self.parse_precision(self.safe_string(market, 'amount_precision'))),
                'price': self.parse_number(self.parse_precision(self.safe_string(market, 'market_precision'))),
            },
            'limits': {
                'leverage': {
                    'min': None,
                    'max': None,
                },
                'amount': {
                    'min': None,
                    'max': None,
                },
                'price': {
                    'min': None,
                    'max': None,
                },
                'cost': {
                    'min': self.safe_number(market, 'min_size'),
                    'max': None,
                },
            },
            'created': None,
            'info': market,
        }

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

        https://docs.onetrading.com/#fee-groups
        https://docs.onetrading.com/#fees

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.method]: fetchPrivateTradingFees or fetchPublicTradingFees
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>` indexed by market symbols
        """
        method = self.safe_string(params, 'method')
        params = self.omit(params, 'method')
        if method is None:
            options = self.safe_value(self.options, 'fetchTradingFees', {})
            method = self.safe_string(options, 'method', 'fetchPrivateTradingFees')
        if method == 'fetchPrivateTradingFees':
            return self.fetch_private_trading_fees(params)
        elif method == 'fetchPublicTradingFees':
            return self.fetch_public_trading_fees(params)
        else:
            raise NotSupported(self.id + ' fetchTradingFees() does not support ' + method + ', fetchPrivateTradingFees and fetchPublicTradingFees are supported')

    def fetch_public_trading_fees(self, params={}):
        self.load_markets()
        response = self.publicGetFees(params)
        #
        # [
        #     {
        #         'fee_group_id': 'SPOT',
        #         'display_text': 'The fee plan for spot trading.',
        #         'volume_currency': 'EUR',
        #         'fee_tiers': [
        #             {
        #                 'volume': '0',
        #                 'fee_group_id': 'SPOT',
        #                 'maker_fee': '0.1000',
        #                 'taker_fee': '0.2000',
        #             },
        #             {
        #                 'volume': '10000',
        #                 'fee_group_id': 'SPOT',
        #                 'maker_fee': '0.0400',
        #                 'taker_fee': '0.0800',
        #             },
        #         ],
        #     },
        #     {
        #         'fee_group_id': 'FUTURES',
        #         'display_text': 'The fee plan for futures trading.',
        #         'volume_currency': 'EUR',
        #         'fee_tiers': [
        #             {
        #                 'volume': '0',
        #                 'fee_group_id': 'FUTURES',
        #                 'maker_fee': '0.1000',
        #                 'taker_fee': '0.2000',
        #             },
        #             {
        #                 'volume': '10000',
        #                 'fee_group_id': 'FUTURES',
        #                 'maker_fee': '0.0400',
        #                 'taker_fee': '0.0800',
        #             },
        #         ],
        #     },
        # ]
        #
        spotFees = self.safe_dict(response, 0, {})
        futuresFees = self.safe_dict(response, 1, {})
        spotFeeTiers = self.safe_list(spotFees, 'fee_tiers', [])
        futuresFeeTiers = self.safe_list(futuresFees, 'fee_tiers', [])
        spotTiers = self.parse_fee_tiers(spotFeeTiers)
        futuresTiers = self.parse_fee_tiers(futuresFeeTiers)
        firstSpotTier = self.safe_dict(spotTiers, 0, {})
        firstFuturesTier = self.safe_dict(futuresTiers, 0, {})
        result: dict = {}
        for i in range(0, len(self.symbols)):
            symbol = self.symbols[i]
            market = self.market(symbol)
            tierObject = firstSpotTier if (market['spot']) else firstFuturesTier
            result[symbol] = {
                'info': spotFees,
                'symbol': symbol,
                'maker': self.safe_number(tierObject, 'maker_fee'),
                'taker': self.safe_number(tierObject, 'taker_fee'),
                'percentage': True,
                'tierBased': True,
                'tiers': spotTiers,
            }
        return result

    def fetch_private_trading_fees(self, params={}):
        self.load_markets()
        response = self.privateGetAccountFees(params)
        #
        # {
        #    "account_id":"b7f4e27e-b34a-493a-b0d4-4bd341a3f2e0",
        #    "running_volumes":[
        #       {
        #          "fee_group_id":"SPOT",
        #          "volume":"0",
        #          "currency":"EUR"
        #       },
        #       {
        #          "fee_group_id":"FUTURES",
        #          "volume":"0",
        #          "currency":"EUR"
        #       }
        #    ],
        #    "active_fee_tiers":[
        #       {
        #          "fee_group_id":"SPOT",
        #          "volume":"0",
        #          "maker_fee":"0.1000",
        #          "taker_fee":"0.2000"
        #       },
        #       {
        #          "fee_group_id":"FUTURES",
        #          "volume":"0",
        #          "maker_fee":"0.1000",
        #          "taker_fee":"0.2000"
        #       }
        #    ]
        # }
        #
        activeFeeTier = self.safe_list(response, 'active_fee_tiers')
        spotFees = self.safe_dict(activeFeeTier, 0, {})
        futuresFees = self.safe_dict(activeFeeTier, 1, {})
        spotMakerFee = self.safe_string(spotFees, 'maker_fee')
        spotTakerFee = self.safe_string(spotFees, 'taker_fee')
        spotMakerFee = Precise.string_div(spotMakerFee, '100')
        spotTakerFee = Precise.string_div(spotTakerFee, '100')
        # feeTiers = self.safe_value(response, 'fee_tiers')
        futuresMakerFee = self.safe_string(futuresFees, 'maker_fee')
        futuresTakerFee = self.safe_string(futuresFees, 'taker_fee')
        futuresMakerFee = Precise.string_div(futuresMakerFee, '100')
        futuresTakerFee = Precise.string_div(futuresTakerFee, '100')
        result: dict = {}
        # tiers = self.parse_fee_tiers(feeTiers)
        for i in range(0, len(self.symbols)):
            symbol = self.symbols[i]
            market = self.market(symbol)
            makerFee = spotMakerFee if (market['spot']) else futuresMakerFee
            takerFee = spotTakerFee if (market['spot']) else futuresTakerFee
            result[symbol] = {
                'info': response,
                'symbol': symbol,
                'maker': self.parse_number(makerFee),
                'taker': self.parse_number(takerFee),
                'percentage': True,
                'tierBased': True,
                'tiers': None,
            }
        return result

    def parse_fee_tiers(self, feeTiers, market: Market = None):
        takerFees = []
        makerFees = []
        for i in range(0, len(feeTiers)):
            tier = feeTiers[i]
            volume = self.safe_number(tier, 'volume')
            taker = self.safe_string(tier, 'taker_fee')
            maker = self.safe_string(tier, 'maker_fee')
            maker = Precise.string_div(maker, '100')
            taker = Precise.string_div(taker, '100')
            makerFees.append([volume, self.parse_number(maker)])
            takerFees.append([volume, self.parse_number(taker)])
        return {
            'maker': makerFees,
            'taker': takerFees,
        }

    def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
        #
        # fetchTicker, fetchTickers
        #
        #     {
        #         "instrument_code":"BTC_EUR",
        #         "sequence":602562,
        #         "time":"2020-07-10T06:27:34.951Z",
        #         "state":"ACTIVE",
        #         "is_frozen":0,
        #         "quote_volume":"1695555.1783768",
        #         "base_volume":"205.67436",
        #         "last_price":"8143.91",
        #         "best_bid":"8143.71",
        #         "best_ask":"8156.9",
        #         "price_change":"-147.47",
        #         "price_change_percentage":"-1.78",
        #         "high":"8337.45",
        #         "low":"8110.0"
        #     }
        #
        timestamp = self.parse8601(self.safe_string(ticker, 'time'))
        marketId = self.safe_string(ticker, 'instrument_code')
        symbol = self.safe_symbol(marketId, market, '_')
        last = self.safe_string(ticker, 'last_price')
        percentage = self.safe_string(ticker, 'price_change_percentage')
        change = self.safe_string(ticker, 'price_change')
        baseVolume = self.safe_string(ticker, 'base_volume')
        quoteVolume = self.safe_string(ticker, 'quote_volume')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': self.safe_string(ticker, 'high'),
            'low': self.safe_string(ticker, 'low'),
            'bid': self.safe_string(ticker, 'best_bid'),
            'bidVolume': None,
            'ask': self.safe_string(ticker, 'best_ask'),
            'askVolume': None,
            'vwap': None,
            'open': None,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': change,
            'percentage': percentage,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            '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

        https://docs.onetrading.com/#market-ticker-for-instrument

        :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 = {
            'instrument_code': market['id'],
        }
        response = self.publicGetMarketTickerInstrumentCode(self.extend(request, params))
        #
        #     {
        #         "instrument_code":"BTC_EUR",
        #         "sequence":602562,
        #         "time":"2020-07-10T06:27:34.951Z",
        #         "state":"ACTIVE",
        #         "is_frozen":0,
        #         "quote_volume":"1695555.1783768",
        #         "base_volume":"205.67436",
        #         "last_price":"8143.91",
        #         "best_bid":"8143.71",
        #         "best_ask":"8156.9",
        #         "price_change":"-147.47",
        #         "price_change_percentage":"-1.78",
        #         "high":"8337.45",
        #         "low":"8110.0"
        #     }
        #
        return self.parse_ticker(response, 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

        https://docs.onetrading.com/#market-ticker

        :param str[] [symbols]: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        self.load_markets()
        symbols = self.market_symbols(symbols)
        response = self.publicGetMarketTicker(params)
        #
        #     [
        #         {
        #             "instrument_code":"BTC_EUR",
        #             "sequence":602562,
        #             "time":"2020-07-10T06:27:34.951Z",
        #             "state":"ACTIVE",
        #             "is_frozen":0,
        #             "quote_volume":"1695555.1783768",
        #             "base_volume":"205.67436",
        #             "last_price":"8143.91",
        #             "best_bid":"8143.71",
        #             "best_ask":"8156.9",
        #             "price_change":"-147.47",
        #             "price_change_percentage":"-1.78",
        #             "high":"8337.45",
        #             "low":"8110.0"
        #         }
        #     ]
        #
        result: dict = {}
        for i in range(0, len(response)):
            ticker = self.parse_ticker(response[i])
            symbol = ticker['symbol']
            result[symbol] = ticker
        return self.filter_by_array_tickers(result, 'symbol', 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

        https://docs.onetrading.com/#order-book

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :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()
        market = self.market(symbol)
        request: dict = {
            'instrument_code': market['id'],
            # level 1 means only the best bid and ask
            # level 2 is a compiled order book up to market precision
            # level 3 is a full orderbook
            # if you wish to get regular updates about orderbooks please use the Websocket channel
            # heavy usage of self endpoint may result in limited access according to rate limits rules
            # 'level': 3,  # default
        }
        if limit is not None:
            request['depth'] = limit
        response = self.publicGetOrderBookInstrumentCode(self.extend(request, params))
        #
        # level 1
        #
        #     {
        #         "instrument_code":"BTC_EUR",
        #         "time":"2020-07-10T07:39:06.343Z",
        #         "asks":{
        #             "value":{
        #                 "price":"8145.29",
        #                 "amount":"0.96538",
        #                 "number_of_orders":1
        #             }
        #         },
        #         "bids":{
        #             "value":{
        #                 "price":"8134.0",
        #                 "amount":"1.5978",
        #                 "number_of_orders":5
        #             }
        #         }
        #     }
        #
        # level 2
        #
        #     {
        #         "instrument_code":"BTC_EUR","time":"2020-07-10T07:36:43.538Z",
        #         "asks":[
        #             {"price":"8146.59","amount":"0.89691","number_of_orders":1},
        #             {"price":"8146.89","amount":"1.92062","number_of_orders":1},
        #             {"price":"8169.5","amount":"0.0663","number_of_orders":1},
        #         ],
        #         "bids":[
        #             {"price":"8143.49","amount":"0.01329","number_of_orders":1},
        #             {"price":"8137.01","amount":"5.34748","number_of_orders":1},
        #             {"price":"8137.0","amount":"2.0","number_of_orders":1},
        #         ]
        #     }
        #
        # level 3
        #
        #     {
        #         "instrument_code":"BTC_EUR",
        #         "time":"2020-07-10T07:32:31.525Z",
        #         "bids":[
        #             {"price":"8146.79","amount":"0.01537","order_id":"5d717da1-a8f4-422d-afcc-03cb6ab66825"},
        #             {"price":"8139.32","amount":"3.66009","order_id":"d0715c68-f28d-4cf1-a450-d56cf650e11c"},
        #             {"price":"8137.51","amount":"2.61049","order_id":"085fd6f4-e835-4ca5-9449-a8f165772e60"},
        #         ],
        #         "asks":[
        #             {"price":"8153.49","amount":"0.93384","order_id":"755d3aa3-42b5-46fa-903d-98f42e9ae6c4"},
        #             {"price":"8153.79","amount":"1.80456","order_id":"62034cf3-b70d-45ff-b285-ba6307941e7c"},
        #             {"price":"8167.9","amount":"0.0018","order_id":"036354e0-71cd-492f-94f2-01f7d4b66422"},
        #         ]
        #     }
        #
        timestamp = self.parse8601(self.safe_string(response, 'time'))
        return self.parse_order_book(response, market['symbol'], timestamp, 'bids', 'asks', 'price', 'amount')

    def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
        #
        #     {
        #         "instrument_code":"BTC_EUR",
        #         "granularity":{"unit":"HOURS","period":1},
        #         "high":"9252.65",
        #         "low":"9115.27",
        #         "open":"9250.0",
        #         "close":"9132.35",
        #         "total_amount":"33.85924",
        #         "volume":"311958.9635744",
        #         "time":"2020-05-08T22:59:59.999Z",
        #         "last_sequence":461123
        #     }
        #
        granularity = self.safe_value(ohlcv, 'granularity')
        unit = self.safe_string(granularity, 'unit')
        period = self.safe_string(granularity, 'period')
        units: dict = {
            'MINUTES': 'm',
            'HOURS': 'h',
            'DAYS': 'd',
            'WEEKS': 'w',
            'MONTHS': 'M',
        }
        lowercaseUnit = self.safe_string(units, unit)
        timeframe = period + lowercaseUnit
        durationInSeconds = self.parse_timeframe(timeframe)
        duration = durationInSeconds * 1000
        timestamp = self.parse8601(self.safe_string(ohlcv, 'time'))
        alignedTimestamp = duration * self.parse_to_int(timestamp / duration)
        options = self.safe_value(self.options, 'fetchOHLCV', {})
        volumeField = self.safe_string(options, 'volume', 'total_amount')
        return [
            alignedTimestamp,
            self.safe_number(ohlcv, 'open'),
            self.safe_number(ohlcv, 'high'),
            self.safe_number(ohlcv, 'low'),
            self.safe_number(ohlcv, 'close'),
            self.safe_number(ohlcv, volumeField),
        ]

    def fetch_ohlcv(self, symbol: str, timeframe: str = '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

        https://docs.onetrading.com/#candlesticks

        :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)
        periodUnit = self.safe_string(self.timeframes, timeframe)
        period, unit = periodUnit.split('/')
        durationInSeconds = self.parse_timeframe(timeframe)
        duration = durationInSeconds * 1000
        if limit is None:
            limit = 1500
        request: dict = {
            'instrument_code': market['id'],
            # 'from': self.iso8601(since),
            # 'to': self.iso8601(self.milliseconds()),
            'period': period,
            'unit': unit,
        }
        if since is None:
            now = self.milliseconds()
            request['to'] = self.iso8601(now)
            request['from'] = self.iso8601(now - limit * duration)
        else:
            request['from'] = self.iso8601(since)
            request['to'] = self.iso8601(self.sum(since, limit * duration))
        response = self.publicGetCandlesticksInstrumentCode(self.extend(request, params))
        #
        #     [
        #         {"instrument_code":"BTC_EUR","granularity":{"unit":"HOURS","period":1},"high":"9252.65","low":"9115.27","open":"9250.0","close":"9132.35","total_amount":"33.85924","volume":"311958.9635744","time":"2020-05-08T22:59:59.999Z","last_sequence":461123},
        #         {"instrument_code":"BTC_EUR","granularity":{"unit":"HOURS","period":1},"high":"9162.49","low":"9040.0","open":"9132.53","close":"9083.69","total_amount":"26.19685","volume":"238553.7812365","time":"2020-05-08T23:59:59.999Z","last_sequence":461376},
        #         {"instrument_code":"BTC_EUR","granularity":{"unit":"HOURS","period":1},"high":"9135.7","low":"9002.59","open":"9055.45","close":"9133.98","total_amount":"26.21919","volume":"238278.8724959","time":"2020-05-09T00:59:59.999Z","last_sequence":461521},
        #     ]
        #
        ohlcv = self.safe_list(response, 'candlesticks')
        return self.parse_ohlcvs(ohlcv, market, timeframe, since, limit)

    def parse_trade(self, trade: dict, market: Market = None) -> Trade:
        #
        # fetchTrades(public)
        #
        #     {
        #         "instrument_code":"BTC_EUR",
        #         "price":"8137.28",
        #         "amount":"0.22269",
        #         "taker_side":"BUY",
        #         "volume":"1812.0908832",
        #         "time":"2020-07-10T14:44:32.299Z",
        #         "trade_timestamp":1594392272299,
        #         "sequence":603047
        #     }
        #
        # fetchMyTrades, fetchOrder, fetchOpenOrders, fetchClosedOrders trades(private)
        #
        #     {
        #         "fee": {
        #             "fee_amount": "0.0014",
        #             "fee_currency": "BTC",
        #             "fee_percentage": "0.1",
        #             "fee_group_id": "default",
        #             "fee_type": "TAKER",
        #             "running_trading_volume": "0.0"
        #         },
        #         "trade": {
        #             "trade_id": "fdff2bcc-37d6-4a2d-92a5-46e09c868664",
        #             "order_id": "36bb2437-7402-4794-bf26-4bdf03526439",
        #             "account_id": "a4c699f6-338d-4a26-941f-8f9853bfc4b9",
        #             "amount": "1.4",
        #             "side": "BUY",
        #             "instrument_code": "BTC_EUR",
        #             "price": "7341.4",
        #             "time": "2019-09-27T15:05:32.564Z",
        #             "sequence": 48670
        #         }
        #     }
        #
        feeInfo = self.safe_value(trade, 'fee', {})
        trade = self.safe_value(trade, 'trade', trade)
        timestamp = self.safe_integer(trade, 'trade_timestamp')
        if timestamp is None:
            timestamp = self.parse8601(self.safe_string(trade, 'time'))
        side = self.safe_string_lower_2(trade, 'side', 'taker_side')
        priceString = self.safe_string(trade, 'price')
        amountString = self.safe_string(trade, 'amount')
        costString = self.safe_string(trade, 'volume')
        marketId = self.safe_string(trade, 'instrument_code')
        symbol = self.safe_symbol(marketId, market, '_')
        feeCostString = self.safe_string(feeInfo, 'fee_amount')
        takerOrMaker = None
        fee = None
        if feeCostString is not None:
            feeCurrencyId = self.safe_string(feeInfo, 'fee_currency')
            feeCurrencyCode = self.safe_currency_code(feeCurrencyId)
            feeRateString = self.safe_string(feeInfo, 'fee_percentage')
            fee = {
                'cost': feeCostString,
                'currency': feeCurrencyCode,
                'rate': feeRateString,
            }
            takerOrMaker = self.safe_string_lower(feeInfo, 'fee_type')
        return self.safe_trade({
            'id': self.safe_string_2(trade, 'trade_id', 'sequence'),
            'order': self.safe_string(trade, 'order_id'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': symbol,
            'type': None,
            'side': side,
            'price': priceString,
            'amount': amountString,
            'cost': costString,
            'takerOrMaker': takerOrMaker,
            'fee': fee,
            'info': trade,
        }, market)

    def parse_balance(self, response) -> Balances:
        balances = self.safe_value(response, 'balances', [])
        result: dict = {'info': response}
        for i in range(0, len(balances)):
            balance = balances[i]
            currencyId = self.safe_string(balance, 'currency_code')
            code = self.safe_currency_code(currencyId)
            account = self.account()
            account['free'] = self.safe_string(balance, 'available')
            account['used'] = self.safe_string(balance, 'locked')
            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

        https://docs.onetrading.com/#balances

        :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()
        response = self.privateGetAccountBalances(params)
        #
        #     {
        #         "account_id":"4b95934f-55f1-460c-a525-bd5afc0cf071",
        #         "balances":[
        #             {
        #                 "account_id":"4b95934f-55f1-460c-a525-bd5afc0cf071",
        #                 "currency_code":"BTC",
        #                 "change":"10.0",
        #                 "available":"10.0",
        #                 "locked":"0.0",
        #                 "sequence":142135994,
        #                 "time":"2020-07-01T10:57:32.959Z"
        #             }
        #         ]
        #     }
        #
        return self.parse_balance(response)

    def parse_order_status(self, status: Str):
        statuses: dict = {
            'FILLED': 'open',
            'FILLED_FULLY': 'closed',
            'FILLED_CLOSED': 'canceled',
            'FILLED_REJECTED': 'rejected',
            'OPEN': 'open',
            'REJECTED': 'rejected',
            'CLOSED': 'canceled',
            'FAILED': 'failed',
            'STOP_TRIGGERED': 'triggered',
            'DONE': 'closed',
        }
        return self.safe_string(statuses, status, status)

    def parse_order(self, order: dict, market: Market = None) -> Order:
        #
        # createOrder
        #
        #     {
        #         "order_id": "d5492c24-2995-4c18-993a-5b8bf8fffc0d",
        #         "client_id": "d75fb03b-b599-49e9-b926-3f0b6d103206",
        #         "account_id": "a4c699f6-338d-4a26-941f-8f9853bfc4b9",
        #         "instrument_code": "BTC_EUR",
        #         "time": "2019-08-01T08:00:44.026Z",
        #         "side": "BUY",
        #         "price": "5000",
        #         "amount": "1",
        #         "filled_amount": "0.5",
        #         "type": "LIMIT",
        #         "time_in_force": "GOOD_TILL_CANCELLED"
        #     }
        #
        # fetchOrder, fetchOpenOrders, fetchClosedOrders
        #
        #     {
        #         "order": {
        #             "order_id": "66756a10-3e86-48f4-9678-b634c4b135b2",
        #             "account_id": "1eb2ad5d-55f1-40b5-bc92-7dc05869e905",
        #             "instrument_code": "BTC_EUR",
        #             "amount": "1234.5678",
        #             "filled_amount": "1234.5678",
        #             "side": "BUY",
        #             "type": "LIMIT",
        #             "status": "OPEN",
        #             "sequence": 123456789,
        #             "price": "1234.5678",
        #             "average_price": "1234.5678",
        #             "reason": "INSUFFICIENT_FUNDS",
        #             "time": "2019-08-24T14:15:22Z",
        #             "time_in_force": "GOOD_TILL_CANCELLED",
        #             "time_last_updated": "2019-08-24T14:15:22Z",
        #             "expire_after": "2019-08-24T14:15:22Z",
        #             "is_post_only": False,
        #             "time_triggered": "2019-08-24T14:15:22Z",
        #             "trigger_price": "1234.5678"
        #         },
        #         "trades": [
        #             {
        #                 "fee": {
        #                     "fee_amount": "0.0014",
        #                     "fee_currency": "BTC",
        #                     "fee_percentage": "0.1",
        #                     "fee_group_id": "default",
        #                     "fee_type": "TAKER",
        #                     "running_trading_volume": "0.0"
        #                 },
        #                 "trade": {
        #                     "trade_id": "fdff2bcc-37d6-4a2d-92a5-46e09c868664",
        #                     "order_id": "36bb2437-7402-4794-bf26-4bdf03526439",
        #                     "account_id": "a4c699f6-338d-4a26-941f-8f9853bfc4b9",
        #                     "amount": "1.4",
        #                     "side": "BUY",
        #                     "instrument_code": "BTC_EUR",
        #                     "price": "7341.4",
        #                     "time": "2019-09-27T15:05:32.564Z",
        #                     "sequence": 48670
        #                 }
        #             }
        #         ]
        #     }
        #
        rawOrder = self.safe_value(order, 'order', order)
        id = self.safe_string(rawOrder, 'order_id')
        clientOrderId = self.safe_string(rawOrder, 'client_id')
        timestamp = self.parse8601(self.safe_string(rawOrder, 'time'))
        rawStatus = self.parse_order_status(self.safe_string(rawOrder, 'status'))
        status = self.parse_order_status(rawStatus)
        marketId = self.safe_string(rawOrder, 'instrument_code')
        symbol = self.safe_symbol(marketId, market, '_')
        price = self.safe_string(rawOrder, 'price')
        amount = self.safe_string(rawOrder, 'amount')
        filled = self.safe_string(rawOrder, 'filled_amount')
        side = self.safe_string_lower(rawOrder, 'side')
        type = self.safe_string_lower(rawOrder, 'type')
        timeInForce = self.parse_time_in_force(self.safe_string(rawOrder, 'time_in_force'))
        postOnly = self.safe_value(rawOrder, 'is_post_only')
        rawTrades = self.safe_value(order, 'trades', [])
        return self.safe_order({
            'id': id,
            'clientOrderId': clientOrderId,
            'info': order,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'symbol': symbol,
            'type': self.parse_order_type(type),
            'timeInForce': timeInForce,
            'postOnly': postOnly,
            'side': side,
            'price': price,
            'triggerPrice': self.safe_number(rawOrder, 'trigger_price'),
            'amount': amount,
            'cost': None,
            'average': None,
            'filled': filled,
            'remaining': None,
            'status': status,
            # 'fee': None,
            'trades': rawTrades,
        }, market)

    def parse_order_type(self, type: Str):
        types: dict = {
            'booked': 'limit',
        }
        return self.safe_string(types, type, type)

    def parse_time_in_force(self, timeInForce: Str):
        timeInForces: dict = {
            'GOOD_TILL_CANCELLED': 'GTC',
            'GOOD_TILL_TIME': 'GTT',
            'IMMEDIATE_OR_CANCELLED': 'IOC',
            'FILL_OR_KILL': 'FOK',
        }
        return self.safe_string(timeInForces, timeInForce, timeInForce)

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

        https://docs.onetrading.com/#create-order

        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.triggerPrice]: onetrading only does stop limit orders and does not do stop market
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        uppercaseType = type.upper()
        request: dict = {
            'instrument_code': market['id'],
            'type': uppercaseType,  # LIMIT, MARKET, STOP
            'side': side.upper(),  # or SELL
            'amount': self.amount_to_precision(symbol, amount),
            # "price": "1234.5678",  # required for LIMIT and STOP orders
            # "client_id": "d75fb03b-b599-49e9-b926-3f0b6d103206",  # optional
            # "time_in_force": "GOOD_TILL_CANCELLED",  # limit orders only, GOOD_TILL_CANCELLED, GOOD_TILL_TIME, IMMEDIATE_OR_CANCELLED and FILL_OR_KILL
            # "expire_after": "2020-07-02T19:40:13Z",  # required for GOOD_TILL_TIME
            # "is_post_only": False,  # limit orders only, optional
            # "trigger_price": "1234.5678"  # required for stop orders
        }
        priceIsRequired = False
        if uppercaseType == 'LIMIT' or uppercaseType == 'STOP':
            priceIsRequired = True
        triggerPrice = self.safe_number_n(params, ['triggerPrice', 'trigger_price', 'stopPrice'])
        if triggerPrice is not None:
            if uppercaseType == 'MARKET':
                raise BadRequest(self.id + ' createOrder() cannot place stop market orders, only stop limit')
            request['trigger_price'] = self.price_to_precision(symbol, triggerPrice)
            request['type'] = 'STOP'
            params = self.omit(params, ['triggerPrice', 'trigger_price', 'stopPrice'])
        elif uppercaseType == 'STOP':
            raise ArgumentsRequired(self.id + ' createOrder() requires a triggerPrice param for ' + type + ' orders')
        if priceIsRequired:
            request['price'] = self.price_to_precision(symbol, price)
        clientOrderId = self.safe_string_2(params, 'clientOrderId', 'client_id')
        if clientOrderId is not None:
            request['client_id'] = clientOrderId
            params = self.omit(params, ['clientOrderId', 'client_id'])
        timeInForce = self.safe_string_2(params, 'timeInForce', 'time_in_force', 'GOOD_TILL_CANCELLED')
        params = self.omit(params, 'timeInForce')
        request['time_in_force'] = timeInForce
        response = self.privatePostAccountOrders(self.extend(request, params))
        #
        #     {
        #         "order_id": "d5492c24-2995-4c18-993a-5b8bf8fffc0d",
        #         "client_id": "d75fb03b-b599-49e9-b926-3f0b6d103206",
        #         "account_id": "a4c699f6-338d-4a26-941f-8f9853bfc4b9",
        #         "instrument_code": "BTC_EUR",
        #         "time": "2019-08-01T08:00:44.026Z",
        #         "side": "BUY",
        #         "price": "5000",
        #         "amount": "1",
        #         "filled_amount": "0.5",
        #         "type": "LIMIT",
        #         "time_in_force": "GOOD_TILL_CANCELLED"
        #     }
        #
        return self.parse_order(response, market)

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

        https://docs.onetrading.com/#close-order-by-order-id

        :param str id: order id
        :param str symbol: not used by bitmex cancelOrder()
        :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()
        clientOrderId = self.safe_string_2(params, 'clientOrderId', 'client_id')
        params = self.omit(params, ['clientOrderId', 'client_id'])
        method = 'privateDeleteAccountOrdersOrderId'
        request: dict = {}
        if clientOrderId is not None:
            method = 'privateDeleteAccountOrdersClientClientId'
            request['client_id'] = clientOrderId
        else:
            request['order_id'] = id
        response = None
        if method == 'privateDeleteAccountOrdersOrderId':
            response = self.privateDeleteAccountOrdersOrderId(self.extend(request, params))
        else:
            response = self.privateDeleteAccountOrdersClientClientId(self.extend(request, params))
        #
        # responds with an empty body
        #
        return self.parse_order(response)

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

        https://docs.onetrading.com/#close-all-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
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        request: dict = {}
        if symbol is not None:
            market = self.market(symbol)
            request['instrument_code'] = market['id']
        response = self.privateDeleteAccountOrders(self.extend(request, params))
        #
        #     [
        #         "a10e9bd1-8f72-4cfe-9f1b-7f1c8a9bd8ee"
        #     ]
        #
        return [self.safe_order({'info': response})]

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

        https://docs.onetrading.com/#close-all-orders

        :param str[] ids: order ids
        :param str symbol: unified market symbol, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        request: dict = {
            'ids': ','.join(ids),
        }
        response = self.privateDeleteAccountOrders(self.extend(request, params))
        #
        #     [
        #         "a10e9bd1-8f72-4cfe-9f1b-7f1c8a9bd8ee"
        #     ]
        #
        order = self.safe_order({'info': response})
        return [order]

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

        https://docs.onetrading.com/#get-order

        :param str id: the order id
        :param str symbol: not used by onetrading fetchOrder
        :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.privateGetAccountOrdersOrderId(self.extend(request, params))
        #
        #     {
        #         "order": {
        #             "order_id": "36bb2437-7402-4794-bf26-4bdf03526439",
        #             "account_id": "a4c699f6-338d-4a26-941f-8f9853bfc4b9",
        #             "time_last_updated": "2019-09-27T15:05:35.096Z",
        #             "sequence": 48782,
        #             "price": "7349.2",
        #             "filled_amount": "100.0",
        #             "status": "FILLED_FULLY",
        #             "amount": "100.0",
        #             "instrument_code": "BTC_EUR",
        #             "side": "BUY",
        #             "time": "2019-09-27T15:05:32.063Z",
        #             "type": "MARKET"
        #         },
        #         "trades": [
        #             {
        #                 "fee": {
        #                     "fee_amount": "0.0014",
        #                     "fee_currency": "BTC",
        #                     "fee_percentage": "0.1",
        #                     "fee_group_id": "default",
        #                     "fee_type": "TAKER",
        #                     "running_trading_volume": "0.0"
        #                 },
        #                 "trade": {
        #                     "trade_id": "fdff2bcc-37d6-4a2d-92a5-46e09c868664",
        #                     "order_id": "36bb2437-7402-4794-bf26-4bdf03526439",
        #                     "account_id": "a4c699f6-338d-4a26-941f-8f9853bfc4b9",
        #                     "amount": "1.4",
        #                     "side": "BUY",
        #                     "instrument_code": "BTC_EUR",
        #                     "price": "7341.4",
        #                     "time": "2019-09-27T15:05:32.564Z",
        #                     "sequence": 48670
        #                 }
        #             }
        #         ]
        #     }
        #
        return self.parse_order(response)

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

        https://docs.onetrading.com/#get-orders

        :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
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        request: dict = {
            # 'from': self.iso8601(since),
            # 'to': self.iso8601(self.milliseconds()),  # max range is 100 days
            # 'instrument_code': market['id'],
            # 'with_cancelled_and_rejected': False,  # default is False, orders which have been cancelled by the user before being filled or rejected by the system, additionally, all inactive filled orders which would return with "with_just_filled_inactive"
            # 'with_just_filled_inactive': False,  # orders which have been filled and are no longer open, use of "with_cancelled_and_rejected" extends "with_just_filled_inactive" and in case both are specified the latter is ignored
            # 'with_just_orders': False,  # do not return any trades corresponsing to the orders, it may be significanly faster and should be used if user is not interesting in trade information
            # 'max_page_size': 100,
            # 'cursor': 'string',  # pointer specifying the position from which the next pages should be returned
        }
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['instrument_code'] = market['id']
        if since is not None:
            to = self.safe_string(params, 'to')
            if to is None:
                raise ArgumentsRequired(self.id + ' fetchOpenOrders() requires a "to" iso8601 string param with the since argument is specified, max range is 100 days')
            request['from'] = self.iso8601(since)
        if limit is not None:
            request['max_page_size'] = limit
        response = self.privateGetAccountOrders(self.extend(request, params))
        #
        #     {
        #         "order_history": [
        #             {
        #                 "order": {
        #                     "trigger_price": "12089.88",
        #                     "order_id": "d453ca12-c650-46dd-9dee-66910d96bfc0",
        #                     "account_id": "ef3a5f4c-cfcd-415e-ba89-5a9abf47b28a",
        #                     "instrument_code": "BTC_USDT",
        #                     "time": "2019-08-23T10:02:31.663Z",
        #                     "side": "SELL",
        #                     "price": "10159.76",
        #                     "average_price": "10159.76",
        #                     "amount": "0.2",
        #                     "filled_amount": "0.2",
        #                     "type": "STOP",
        #                     "sequence": 8,
        #                     "status": "FILLED_FULLY"
        #                 },
        #                 "trades": [
        #                     {
        #                         "fee": {
        #                             "fee_amount": "0.4188869",
        #                             "fee_currency": "USDT",
        #                             "fee_percentage": "0.1",
        #                             "fee_group_id": "default",
        #                             "fee_type": "TAKER",
        #                             "running_trading_volume": "0.0"
        #                         },
        #                         "trade": {
        #                             "trade_id": "ec82896f-fd1b-4cbb-89df-a9da85ccbb4b",
        #                             "order_id": "d453ca12-c650-46dd-9dee-66910d96bfc0",
        #                             "account_id": "ef3a5f4c-cfcd-415e-ba89-5a9abf47b28a",
        #                             "amount": "0.2",
        #                             "side": "SELL",
        #                             "instrument_code": "BTC_USDT",
        #                             "price": "10159.76",
        #                             "time": "2019-08-23T10:02:32.663Z",
        #                             "sequence": 9
        #                         }
        #                     }
        #                 ]
        #             },
        #             {
        #                 "order": {
        #                     "order_id": "5151a99e-f414-418f-8cf1-2568d0a63ea5",
        #                     "account_id": "ef3a5f4c-cfcd-415e-ba89-5a9abf47b28a",
        #                     "instrument_code": "BTC_USDT",
        #                     "time": "2019-08-23T10:01:36.773Z",
        #                     "side": "SELL",
        #                     "price": "12289.88",
        #                     "amount": "0.5",
        #                     "filled_amount": "0.0",
        #                     "type": "LIMIT",
        #                     "sequence": 7,
        #                     "status": "OPEN"
        #                 },
        #                 "trades": []
        #             },
        #             {
        #                 "order": {
        #                     "order_id": "ac80d857-75e1-4733-9070-fd4288395fdc",
        #                     "account_id": "ef3a5f4c-cfcd-415e-ba89-5a9abf47b28a",
        #                     "instrument_code": "BTC_USDT",
        #                     "time": "2019-08-23T10:01:25.031Z",
        #                     "side": "SELL",
        #                     "price": "11089.88",
        #                     "amount": "0.1",
        #                     "filled_amount": "0.0",
        #                     "type": "LIMIT",
        #                     "sequence": 6,
        #                     "status": "OPEN"
        #                 },
        #                 "trades": []
        #             }
        #         ],
        #         "max_page_size": 100
        #     }
        #
        orderHistory = self.safe_list(response, 'order_history', [])
        return self.parse_orders(orderHistory, market, since, limit)

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

        https://docs.onetrading.com/#get-orders

        :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
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        request: dict = {
            'with_cancelled_and_rejected': True,  # default is False, orders which have been cancelled by the user before being filled or rejected by the system, additionally, all inactive filled orders which would return with "with_just_filled_inactive"
        }
        return self.fetch_open_orders(symbol, since, limit, self.extend(request, params))

    def fetch_order_trades(self, id: str, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        fetch all the trades made from a single order

        https://docs.onetrading.com/#trades-for-order

        :param str id: order id
        :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 to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        """
        self.load_markets()
        request: dict = {
            'order_id': id,
            # 'max_page_size': 100,
            # 'cursor': 'string',  # pointer specifying the position from which the next pages should be returned
        }
        if limit is not None:
            request['max_page_size'] = limit
        response = self.privateGetAccountOrdersOrderIdTrades(self.extend(request, params))
        #
        #     {
        #         "trade_history": [
        #             {
        #                 "trade": {
        #                     "trade_id": "2b42efcd-d5b7-4a56-8e12-b69ffd68c5ef",
        #                     "order_id": "66756a10-3e86-48f4-9678-b634c4b135b2",
        #                     "account_id": "c2d0076a-c20d-41f8-9e9a-1a1d028b2b58",
        #                     "amount": "1234.5678",
        #                     "side": "BUY",
        #                     "instrument_code": "BTC_EUR",
        #                     "price": "1234.5678",
        #                     "time": "2019-08-24T14:15:22Z",
        #                     "price_tick_sequence": 0,
        #                     "sequence": 123456789
        #                 },
        #                 "fee": {
        #                     "fee_amount": "1234.5678",
        #                     "fee_percentage": "1234.5678",
        #                     "fee_group_id": "default",
        #                     "running_trading_volume": "1234.5678",
        #                     "fee_currency": "BTC",
        #                     "fee_type": "TAKER"
        #                 }
        #             }
        #         ],
        #         "max_page_size": 0,
        #         "cursor": "string"
        #     }
        #
        tradeHistory = self.safe_value(response, 'trade_history', [])
        market = None
        if symbol is not None:
            market = self.market(symbol)
        return self.parse_trades(tradeHistory, market, since, limit)

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

        https://docs.onetrading.com/#all-trades

        :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
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        """
        self.load_markets()
        request: dict = {
            # 'from': self.iso8601(since),
            # 'to': self.iso8601(self.milliseconds()),  # max range is 100 days
            # 'instrument_code': market['id'],
            # 'max_page_size': 100,
            # 'cursor': 'string',  # pointer specifying the position from which the next pages should be returned
        }
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['instrument_code'] = market['id']
        if since is not None:
            to = self.safe_string(params, 'to')
            if to is None:
                raise ArgumentsRequired(self.id + ' fetchMyTrades() requires a "to" iso8601 string param with the since argument is specified, max range is 100 days')
            request['from'] = self.iso8601(since)
        if limit is not None:
            request['max_page_size'] = limit
        response = self.privateGetAccountTrades(self.extend(request, params))
        #
        #     {
        #         "trade_history": [
        #             {
        #                 "trade": {
        #                     "trade_id": "2b42efcd-d5b7-4a56-8e12-b69ffd68c5ef",
        #                     "order_id": "66756a10-3e86-48f4-9678-b634c4b135b2",
        #                     "account_id": "c2d0076a-c20d-41f8-9e9a-1a1d028b2b58",
        #                     "amount": "1234.5678",
        #                     "side": "BUY",
        #                     "instrument_code": "BTC_EUR",
        #                     "price": "1234.5678",
        #                     "time": "2019-08-24T14:15:22Z",
        #                     "price_tick_sequence": 0,
        #                     "sequence": 123456789
        #                 },
        #                 "fee": {
        #                     "fee_amount": "1234.5678",
        #                     "fee_percentage": "1234.5678",
        #                     "fee_group_id": "default",
        #                     "running_trading_volume": "1234.5678",
        #                     "fee_currency": "BTC",
        #                     "fee_type": "TAKER"
        #                 }
        #             }
        #         ],
        #         "max_page_size": 0,
        #         "cursor": "string"
        #     }
        #
        tradeHistory = self.safe_list(response, 'trade_history', [])
        return self.parse_trades(tradeHistory, market, since, limit)

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = self.urls['api'][api] + '/' + self.version + '/' + self.implode_params(path, params)
        query = self.omit(params, self.extract_params(path))
        if api == 'public':
            if query:
                url += '?' + self.urlencode(query)
        elif api == 'private':
            self.check_required_credentials()
            headers = {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + self.apiKey,
            }
            if method == 'POST':
                body = self.json(query)
                headers['Content-Type'] = 'application/json'
            else:
                if query:
                    url += '?' + self.urlencode(query)
        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 response is None:
            return None
        #
        #     {"error":"MISSING_FROM_PARAM"}
        #     {"error":"MISSING_TO_PARAM"}
        #     {"error":"CANDLESTICKS_TIME_RANGE_TOO_BIG"}
        #
        message = self.safe_string(response, 'error')
        if message is not None:
            feedback = self.id + ' ' + body
            self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
            self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback)
            raise ExchangeError(feedback)  # unknown message
        return None
