# -*- 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.timex import ImplicitAPI
from ccxt.base.types import Any, Balances, Currencies, Currency, DepositAddress, Int, Market, Num, Order, OrderBook, OrderSide, OrderType, Str, Strings, Ticker, Tickers, Trade, TradingFeeInterface, Transaction
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 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.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class timex(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(timex, self).describe(), {
            'id': 'timex',
            'name': 'TimeX',
            'countries': ['AU'],
            'version': 'v1',
            'rateLimit': 1500,
            'has': {
                'CORS': None,
                'spot': True,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'addMargin': False,
                'borrowCrossMargin': False,
                'borrowIsolatedMargin': False,
                'borrowMargin': False,
                'cancelOrder': True,
                'cancelOrders': True,
                'closeAllPositions': False,
                'closePosition': False,
                'createOrder': True,
                'createReduceOnlyOrder': False,
                'createStopLimitOrder': False,
                'createStopMarketOrder': False,
                'createStopOrder': False,
                'editOrder': True,
                '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': True,
                'fetchDepositAddresses': False,
                'fetchDepositAddressesByNetwork': False,
                'fetchDeposits': True,
                'fetchFundingHistory': False,
                'fetchFundingInterval': False,
                'fetchFundingIntervals': False,
                'fetchFundingRate': False,
                'fetchFundingRateHistory': False,
                'fetchFundingRates': False,
                'fetchGreeks': False,
                'fetchIndexOHLCV': False,
                'fetchIsolatedBorrowRate': False,
                'fetchIsolatedBorrowRates': False,
                'fetchIsolatedPositions': 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,
                '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': True,
                'fetchTradingFee': True,  # maker fee only
                'fetchUnderlyingAssets': False,
                'fetchVolatilityHistory': False,
                'fetchWithdrawal': False,
                'fetchWithdrawals': True,
                'reduceMargin': False,
                'repayCrossMargin': False,
                'repayIsolatedMargin': False,
                'setLeverage': False,
                'setMargin': False,
                'setMarginMode': False,
                'setPositionMode': False,
            },
            'timeframes': {
                '1m': 'I1',
                '5m': 'I5',
                '15m': 'I15',
                '30m': 'I30',
                '1h': 'H1',
                '2h': 'H2',
                '4h': 'H4',
                '6h': 'H6',
                '12h': 'H12',
                '1d': 'D1',
                '1w': 'W1',
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/70423869-6839ab00-1a7f-11ea-8f94-13ae72c31115.jpg',
                'api': {
                    'rest': 'https://plasma-relay-backend.timex.io',
                },
                'www': 'https://timex.io',
                'doc': 'https://plasma-relay-backend.timex.io/swagger-ui/index.html',
                'referral': 'https://timex.io/?refcode=1x27vNkTbP1uwkCck',
            },
            'api': {
                'addressbook': {
                    'get': [
                        'me',
                    ],
                    'post': [
                        '',
                        'id/{id}',
                        'id/{id}/remove',
                    ],
                },
                'custody': {
                    'get': [
                        'credentials',  # Get api key for address
                        'credentials/h/{hash}',  # Get api key by hash
                        'credentials/k/{key}',  # Get api key by key
                        'credentials/me',
                        'credentials/me/address',  # Get api key by hash
                        'deposit-addresses',  # Get deposit addresses list
                        'deposit-addresses/h/{hash}',  # Get deposit address by hash
                    ],
                },
                'history': {
                    'get': [
                        'orders',  # Gets historical orders
                        'orders/details',  # Gets order details
                        'orders/export/csv',  # Export orders to csv
                        'trades',  # Gets historical trades
                        'trades/export/csv',  # Export trades to csv
                    ],
                },
                'currencies': {
                    'get': [
                        'a/{address}',  # Gets currency by address
                        'i/{id}',  # Gets currency by id
                        's/{symbol}',  # Gets currency by symbol
                    ],
                    'post': [
                        'perform',  # Creates new currency
                        'prepare',  # Prepare creates new currency
                        'remove/perform',  # Removes currency by symbol
                        's/{symbol}/remove/prepare',  # Prepare remove currency by symbol
                        's/{symbol}/update/perform',  # Prepare update currency by symbol
                        's/{symbol}/update/prepare',  # Prepare update currency by symbol
                    ],
                },
                'manager': {
                    'get': [
                        'deposits',
                        'transfers',
                        'withdrawals',
                    ],
                },
                'markets': {
                    'get': [
                        'i/{id}',  # Gets market by id
                        's/{symbol}',  # Gets market by symbol
                    ],
                    'post': [
                        'perform',  # Creates new market
                        'prepare',  # Prepare creates new market
                        'remove/perform',  # Removes market by symbol
                        's/{symbol}/remove/prepare',  # Prepare remove market by symbol
                        's/{symbol}/update/perform',  # Prepare update market by symbol
                        's/{symbol}/update/prepare',  # Prepare update market by symbol
                    ],
                },
                'public': {
                    'get': [
                        'candles',  # Gets candles
                        'currencies',  # Gets all the currencies
                        'markets',  # Gets all the markets
                        'orderbook',  # Gets orderbook
                        'orderbook/raw',  # Gets raw orderbook
                        'orderbook/v2',  # Gets orderbook v2
                        'tickers',  # Gets all the tickers
                        'trades',  # Gets trades
                    ],
                },
                'statistics': {
                    'get': [
                        'address',  # calculateAddressStatistics
                    ],
                },
                'trading': {
                    'get': [
                        'balances',  # Get trading balances for all(or selected) currencies
                        'fees',  # Get trading fee rates for all(or selected) markets
                        'orders',  # Gets open orders
                    ],
                    'post': [
                        'orders',  # Create new order
                        'orders/json',  # Create orders
                    ],
                    'put': [
                        'orders',  # Cancel or update orders
                        'orders/json',  # Update orders
                    ],
                    'delete': [
                        'orders',  # Delete orders
                        'orders/json',  # Delete orders
                    ],
                },
                'tradingview': {
                    'get': [
                        'config',  # Gets config
                        'history',  # Gets history
                        'symbol_info',  # Gets symbol info
                        'time',  # Gets time
                    ],
                },
            },
            'precisionMode': TICK_SIZE,
            'exceptions': {
                'exact': {
                    '0': ExchangeError,
                    '1': NotSupported,
                    '4000': BadRequest,
                    '4001': BadRequest,
                    '4002': InsufficientFunds,
                    '4003': AuthenticationError,
                    '4004': AuthenticationError,
                    '4005': BadRequest,
                    '4006': BadRequest,
                    '4007': BadRequest,
                    '4300': PermissionDenied,
                    '4100': AuthenticationError,
                    '4400': OrderNotFound,
                    '5001': InvalidOrder,
                    '5002': ExchangeError,
                    '400': BadRequest,
                    '401': AuthenticationError,
                    '403': PermissionDenied,
                    '404': OrderNotFound,
                    '429': RateLimitExceeded,
                    '500': ExchangeError,
                    '503': ExchangeNotAvailable,
                },
                'broad': {
                    'Insufficient': InsufficientFunds,
                },
            },
            'options': {
                'expireIn': 31536000,  # 365 × 24 × 60 × 60
                'fetchTickers': {
                    'period': '1d',
                },
                'fetchTrades': {
                    'sort': 'timestamp,asc',
                },
                'fetchMyTrades': {
                    'sort': 'timestamp,asc',
                },
                'fetchOpenOrders': {
                    'sort': 'createdAt,asc',
                },
                'fetchClosedOrders': {
                    'sort': 'createdAt,asc',
                },
                'defaultSort': 'timestamp,asc',
                'defaultSortOrders': 'createdAt,asc',
            },
            'features': {
                'spot': {
                    'sandbox': False,
                    'createOrder': {
                        'marginMode': False,
                        'triggerPrice': False,
                        'triggerDirection': False,
                        'triggerPriceType': None,
                        'stopLossPrice': False,
                        'takeProfitPrice': False,
                        'attachedStopLossTakeProfit': None,
                        # todo
                        'timeInForce': {
                            'IOC': True,
                            'FOK': True,
                            'PO': False,
                            'GTD': True,
                        },
                        'hedged': False,
                        'trailing': False,
                        'leverage': False,
                        'marketBuyByCost': False,
                        'marketBuyRequiresPrice': False,
                        'selfTradePrevention': False,
                        'iceberg': False,
                    },
                    'createOrders': None,
                    'fetchMyTrades': {
                        'marginMode': False,
                        'limit': 100,  # todo
                        'daysBack': 100000,  # todo
                        'untilDays': 100000,  # todo
                        'symbolRequired': False,
                    },
                    'fetchOrder': {
                        'marginMode': False,
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOpenOrders': {
                        'marginMode': False,
                        'limit': 100,  # todo
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOrders': None,  # todo
                    'fetchClosedOrders': {
                        'marginMode': False,
                        'limit': 100,  # todo
                        'daysBack': 100000,  # todo
                        'daysBackCanceled': 1,  # todo
                        'untilDays': 100000,  # todo
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOHLCV': {
                        'limit': None,
                    },
                },
                '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
        :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.tradingviewGetTime(params)
        #
        #     1708682617
        #
        return self.parse_to_int(response) * 1000

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

        https://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Public/listMarkets

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = self.publicGetMarkets(params)
        #
        #     [
        #         {
        #             "symbol": "ETHBTC",
        #             "name": "ETH/BTC",
        #             "baseCurrency": "ETH",
        #             "baseTokenAddress": "0x45932db54b38af1f5a57136302eeba66a5975c15",
        #             "quoteCurrency": "BTC",
        #             "quoteTokenAddress": "0x8370fbc6ddec1e18b4e41e72ed943e238458487c",
        #             "feeCurrency": "BTC",
        #             "feeTokenAddress": "0x8370fbc6ddec1e18b4e41e72ed943e238458487c",
        #             "quantityIncrement": "0.0000001",
        #             "takerFee": "0.005",
        #             "makerFee": "0.0025",
        #             "tickSize": "0.00000001",
        #             "baseMinSize": "0.0001",
        #             "quoteMinSize": "0.00001",
        #             "locked": False
        #         }
        #     ]
        #
        return self.parse_markets(response)

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

        https://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Public/listCurrencies

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        """
        response = self.publicGetCurrencies(params)
        #
        #     [
        #         {
        #             "symbol": "BTC",
        #             "name": "Bitcoin",
        #             "address": "0x8370fbc6ddec1e18b4e41e72ed943e238458487c",
        #             "icon": "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggb3BhY2l0eT0iMC41IiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTMwIDUzQzQyLjcwMjUgNTMgNTMgNDIuNzAyNSA1MyAzMEM1MyAxNy4yOTc1IDQyLjcwMjUgNyAzMCA3QzE3LjI5NzUgNyA3IDE3LjI5NzUgNyAzMEM3IDQyLjcwMjUgMTcuMjk3NSA1MyAzMCA1M1pNMzAgNTVDNDMuODA3MSA1NSA1NSA0My44MDcxIDU1IDMwQzU1IDE2LjE5MjkgNDMuODA3MSA1IDMwIDVDMTYuMTkyOSA1IDUgMTYuMTkyOSA1IDMwQzUgNDMuODA3MSAxNi4xOTI5IDU1IDMwIDU1WiIvPgo8cGF0aCBkPSJNNDAuOTQyNSAyNi42NTg1QzQxLjQwMDMgMjMuNjExMyAzOS4wNzA1IDIxLjk3MzIgMzUuODg0OCAyMC44ODA0TDM2LjkxODIgMTYuNzUyNkwzNC4zOTUxIDE2LjEyNjRMMzMuMzg5IDIwLjE0NTVDMzIuNzI1OCAxOS45ODA5IDMyLjA0NDUgMTkuODI1NiAzMS4zNjc1IDE5LjY3MTdMMzIuMzgwOCAxNS42MjYyTDI5Ljg1OTEgMTVMMjguODI1IDE5LjEyNjRDMjguMjc2IDE5LjAwMTkgMjcuNzM3IDE4Ljg3ODggMjcuMjEzOSAxOC43NDkzTDI3LjIxNjggMTguNzM2NEwyMy43MzcyIDE3Ljg3MTJMMjMuMDY2IDIwLjU1NDhDMjMuMDY2IDIwLjU1NDggMjQuOTM4IDIwLjk4MjEgMjQuODk4NSAyMS4wMDg1QzI1LjkyMDQgMjEuMjYyNiAyNi4xMDUgMjEuOTM2IDI2LjA3NDEgMjIuNDY5OUwyNC44OTcgMjcuMTcyNEMyNC45Njc1IDI3LjE5MDMgMjUuMDU4NyAyNy4yMTYgMjUuMTU5MyAyNy4yNTYxQzI1LjA3NTMgMjcuMjM1NCAyNC45ODU0IDI3LjIxMjQgMjQuODkyNyAyNy4xOTAzTDIzLjI0MjggMzMuNzc3OEMyMy4xMTc3IDM0LjA4NjkgMjIuODAwOCAzNC41NTA2IDIyLjA4NjUgMzQuMzc0NkMyMi4xMTE3IDM0LjQxMTEgMjAuMjUyNiAzMy45MTg3IDIwLjI1MjYgMzMuOTE4N0wxOSAzNi43OTQ5TDIyLjI4MzQgMzcuNjFDMjIuODk0MiAzNy43NjI0IDIzLjQ5MjggMzcuOTIyIDI0LjA4MjEgMzguMDcyM0wyMy4wMzggNDIuMjQ3NEwyNS41NTgyIDQyLjg3MzZMMjYuNTkyMyAzOC43NDI5QzI3LjI4MDcgMzguOTI5IDI3Ljk0OSAzOS4xMDA3IDI4LjYwMyAzOS4yNjI0TDI3LjU3MjUgNDMuMzczOEwzMC4wOTU2IDQ0TDMxLjEzOTcgMzkuODMyOEMzNS40NDIyIDQwLjY0MzYgMzguNjc3NCA0MC4zMTY2IDQwLjAzOTIgMzYuNDQxNEM0MS4xMzY1IDMzLjMyMTIgMzkuOTg0NiAzMS41MjEzIDM3LjcyMDkgMzAuMzQ3N0MzOS4zNjk0IDI5Ljk2OTEgNDAuNjExMiAyOC44ODkyIDQwLjk0MjUgMjYuNjU4NVYyNi42NTg1Wk0zNS4xNzc3IDM0LjcwODhDMzQuMzk4IDM3LjgyOSAyOS4xMjI2IDM2LjE0MjIgMjcuNDEyMiAzNS43MTkzTDI4Ljc5NzcgMzAuMTg4MUMzMC41MDgxIDMwLjYxMzIgMzUuOTkyNiAzMS40NTQ4IDM1LjE3NzcgMzQuNzA4OFpNMzUuOTU4MSAyNi42MTM0QzM1LjI0NjcgMjkuNDUxNyAzMC44NTU5IDI4LjAwOTcgMjkuNDMxNiAyNy42NTYxTDMwLjY4NzcgMjIuNjM5NUMzMi4xMTIgMjIuOTkzIDM2LjY5OSAyMy42NTI4IDM1Ljk1ODEgMjYuNjEzNFoiLz4KPC9zdmc+Cg==",
        #             "background": "transparent",
        #             "fiatSymbol": "BTC",
        #             "decimals": 8,
        #             "tradeDecimals": 20,
        #             "displayDecimals": 4,
        #             "crypto": True,
        #             "depositEnabled": True,
        #             "withdrawalEnabled": True,
        #             "transferEnabled": True,
        #             "buyEnabled": False,
        #             "purchaseEnabled": False,
        #             "redeemEnabled": False,
        #             "active": True,
        #             "withdrawalFee": "50000000000000000",
        #             "purchaseCommissions": []
        #         },
        #     ]
        #
        return self.parse_currencies(response)

    def fetch_deposits(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
        """
        fetch all deposits made to an account

        https://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Manager/getDeposits

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        address = self.safe_string(params, 'address')
        params = self.omit(params, 'address')
        if address is None:
            raise ArgumentsRequired(self.id + ' fetchDeposits() requires an address parameter')
        request: dict = {
            'address': address,
        }
        response = self.managerGetDeposits(self.extend(request, params))
        #
        #     [
        #         {
        #             "from": "0x1134cc86b45039cc211c6d1d2e4b3c77f60207ed",
        #             "timestamp": "2022-01-01T00:00:00Z",
        #             "to": "0x1134cc86b45039cc211c6d1d2e4b3c77f60207ed",
        #             "token": "0x6baad3fe5d0fd4be604420e728adbd68d67e119e",
        #             "transferHash": "0x5464cdff35448314e178b8677ea41e670ea0f2533f4e52bfbd4e4a6cfcdef4c2",
        #             "value": "100"
        #         }
        #     ]
        #
        currency = self.safe_currency(code)
        return self.parse_transactions(response, currency, since, limit)

    def fetch_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
        """
        fetch all withdrawals made to an account

        https://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Manager/getWithdraws

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of transaction structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        address = self.safe_string(params, 'address')
        params = self.omit(params, 'address')
        if address is None:
            raise ArgumentsRequired(self.id + ' fetchDeposits() requires an address parameter')
        request: dict = {
            'address': address,
        }
        response = self.managerGetWithdrawals(self.extend(request, params))
        #
        #     [
        #         {
        #             "from": "0x1134cc86b45039cc211c6d1d2e4b3c77f60207ed",
        #             "timestamp": "2022-01-01T00:00:00Z",
        #             "to": "0x1134cc86b45039cc211c6d1d2e4b3c77f60207ed",
        #             "token": "0x6baad3fe5d0fd4be604420e728adbd68d67e119e",
        #             "transferHash": "0x5464cdff35448314e178b8677ea41e670ea0f2533f4e52bfbd4e4a6cfcdef4c2",
        #             "value": "100"
        #         }
        #     ]
        #
        currency = self.safe_currency(code)
        return self.parse_transactions(response, currency, since, limit)

    def get_currency_by_address(self, address):
        currencies = self.currencies
        for i in range(0, len(currencies)):
            currency = currencies[i]
            info = self.safe_value(currency, 'info', {})
            a = self.safe_string(info, 'address')
            if a == address:
                return currency
        return None

    def parse_transaction(self, transaction: dict, currency: Currency = None) -> Transaction:
        #
        #     {
        #         "from": "0x1134cc86b45039cc211c6d1d2e4b3c77f60207ed",
        #         "timestamp": "2022-01-01T00:00:00Z",
        #         "to": "0x1134cc86b45039cc211c6d1d2e4b3c77f60207ed",
        #         "token": "0x6baad3fe5d0fd4be604420e728adbd68d67e119e",
        #         "transferHash": "0x5464cdff35448314e178b8677ea41e670ea0f2533f4e52bfbd4e4a6cfcdef4c2",
        #         "value": "100"
        #     }
        #
        datetime = self.safe_string(transaction, 'timestamp')
        currencyAddresss = self.safe_string(transaction, 'token', '')
        currency = self.get_currency_by_address(currencyAddresss)
        return {
            'info': transaction,
            'id': self.safe_string(transaction, 'transferHash'),
            'txid': self.safe_string(transaction, 'txid'),
            'timestamp': self.parse8601(datetime),
            'datetime': datetime,
            'network': None,
            'address': None,
            'addressTo': self.safe_string(transaction, 'to'),
            'addressFrom': self.safe_string(transaction, 'from'),
            'tag': None,
            'tagTo': None,
            'tagFrom': None,
            'type': None,
            'amount': self.safe_number(transaction, 'value'),
            'currency': self.safe_currency_code(None, currency),
            'status': 'ok',
            'updated': None,
            'internal': None,
            'comment': None,
            'fee': None,
        }

    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://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Public/listTickers

        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        self.load_markets()
        period = self.safe_string(self.options['fetchTickers'], 'period', '1d')
        request: dict = {
            'period': self.timeframes[period],  # I1, I5, I15, I30, H1, H2, H4, H6, H12, D1, W1
        }
        response = self.publicGetTickers(self.extend(request, params))
        #
        #     [
        #         {
        #             "ask": 0.017,
        #             "bid": 0.016,
        #             "high": 0.019,
        #             "last": 0.017,
        #             "low": 0.015,
        #             "market": "TIME/ETH",
        #             "open": 0.016,
        #             "period": "H1",
        #             "timestamp": "2018-12-14T20:50:36.134Z",
        #             "volume": 4.57,
        #             "volumeQuote": 0.07312
        #         }
        #     ]
        #
        return self.parse_tickers(response, symbols)

    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://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Public/listTickers

        :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)
        period = self.safe_string(self.options['fetchTickers'], 'period', '1d')
        request: dict = {
            'market': market['id'],
            'period': self.timeframes[period],  # I1, I5, I15, I30, H1, H2, H4, H6, H12, D1, W1
        }
        response = self.publicGetTickers(self.extend(request, params))
        #
        #     [
        #         {
        #             "ask": 0.017,
        #             "bid": 0.016,
        #             "high": 0.019,
        #             "last": 0.017,
        #             "low": 0.015,
        #             "market": "TIME/ETH",
        #             "open": 0.016,
        #             "period": "H1",
        #             "timestamp": "2018-12-14T20:50:36.134Z",
        #             "volume": 4.57,
        #             "volumeQuote": 0.07312
        #         }
        #     ]
        #
        ticker = self.safe_dict(response, 0)
        return self.parse_ticker(ticker, market)

    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://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Public/orderbookV2

        :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 = {
            'market': market['id'],
        }
        if limit is not None:
            request['limit'] = limit
        response = self.publicGetOrderbookV2(self.extend(request, params))
        #
        #     {
        #         "timestamp":"2019-12-05T00:21:09.538",
        #         "bid":[
        #             {
        #                 "index":"2",
        #                 "price":"0.02024007",
        #                 "baseTokenAmount":"0.0096894",
        #                 "baseTokenCumulativeAmount":"0.0096894",
        #                 "quoteTokenAmount":"0.000196114134258",
        #                 "quoteTokenCumulativeAmount":"0.000196114134258"
        #             },
        #         "ask":[
        #             {
        #                 "index":"-3",
        #                 "price":"0.02024012",
        #                 "baseTokenAmount":"0.005",
        #                 "baseTokenCumulativeAmount":"0.005",
        #                 "quoteTokenAmount":"0.0001012006",
        #                 "quoteTokenCumulativeAmount":"0.0001012006"
        #             },
        #         ]
        #     }
        #
        timestamp = self.parse8601(self.safe_string(response, 'timestamp'))
        return self.parse_order_book(response, symbol, timestamp, 'bid', 'ask', 'price', 'baseTokenAmount')

    def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
        """
        get the list of most recent trades for a particular symbol

        https://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Public/listTrades

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        """
        self.load_markets()
        market = self.market(symbol)
        options = self.safe_value(self.options, 'fetchTrades', {})
        defaultSort = self.safe_value(options, 'sort', 'timestamp,asc')
        sort = self.safe_string(params, 'sort', defaultSort)
        query = self.omit(params, 'sort')
        request: dict = {
            # 'address': 'string',  # trade’s member account(?)
            # 'cursor': 1234,  # int64(?)
            # 'from': self.iso8601(since),
            'market': market['id'],
            # 'page': 0,  # results page you want to retrieve 0 .. N
            # 'size': limit,  # number of records per page, 100 by default
            'sort': sort,  # array[string], sorting criteria in the format "property,asc" or "property,desc", default is ascending
            # 'till': self.iso8601(self.milliseconds()),
        }
        if since is not None:
            request['from'] = self.iso8601(since)
        if limit is not None:
            request['size'] = limit  # default is 100
        response = self.publicGetTrades(self.extend(request, query))
        #
        #     [
        #         {
        #             "id":1,
        #             "timestamp":"2019-06-25T17:01:50.309",
        #             "direction":"BUY",
        #             "price":"0.027",
        #             "quantity":"0.001"
        #         }
        #     ]
        #
        return self.parse_trades(response, market, since, limit)

    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://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Public/listCandles

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest candle to fetch
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'market': market['id'],
            'period': self.safe_string(self.timeframes, timeframe, timeframe),
        }
        # if since and limit are not specified
        duration = self.parse_timeframe(timeframe)
        until = self.safe_integer(params, 'until')
        if limit is None:
            limit = 1000  # exchange provides tens of thousands of data, but we set generous default value
        if since is not None:
            request['from'] = self.iso8601(since)
            if until is None:
                request['till'] = self.iso8601(self.sum(since, self.sum(limit, 1) * duration * 1000))
            else:
                request['till'] = self.iso8601(until)
        elif until is not None:
            request['till'] = self.iso8601(until)
            fromTimestamp = until - self.sum(limit, 1) * duration * 1000
            request['from'] = self.iso8601(fromTimestamp)
        else:
            now = self.milliseconds()
            request['till'] = self.iso8601(now)
            request['from'] = self.iso8601(now - self.sum(limit, 1) * duration * 1000 - 1)
        params = self.omit(params, 'until')
        response = self.publicGetCandles(self.extend(request, params))
        #
        #     [
        #         {
        #             "timestamp":"2019-12-04T23:00:00",
        #             "open":"0.02024009",
        #             "high":"0.02024009",
        #             "low":"0.02024009",
        #             "close":"0.02024009",
        #             "volume":"0.00008096036",
        #             "volumeQuote":"0.004",
        #         },
        #     ]
        #
        return self.parse_ohlcvs(response, market, timeframe, since, limit)

    def parse_balance(self, response) -> Balances:
        result: dict = {
            'info': response,
            'timestamp': None,
            'datetime': None,
        }
        for i in range(0, len(response)):
            balance = response[i]
            currencyId = self.safe_string(balance, 'currency')
            code = self.safe_currency_code(currencyId)
            account = self.account()
            account['total'] = self.safe_string(balance, 'totalBalance')
            account['used'] = self.safe_string(balance, 'lockedBalance')
            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://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Trading/getBalances

        :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.tradingGetBalances(params)
        #
        #     [
        #         {"currency":"BTC","totalBalance":"0","lockedBalance":"0"},
        #         {"currency":"AUDT","totalBalance":"0","lockedBalance":"0"},
        #         {"currency":"ETH","totalBalance":"0","lockedBalance":"0"},
        #         {"currency":"TIME","totalBalance":"0","lockedBalance":"0"},
        #         {"currency":"USDT","totalBalance":"0","lockedBalance":"0"}
        #     ]
        #
        return self.parse_balance(response)

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

        https://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Trading/createOrder

        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or '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
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        uppercaseSide = side.upper()
        uppercaseType = type.upper()
        postOnly = self.safe_bool(params, 'postOnly', False)
        if postOnly:
            uppercaseType = 'POST_ONLY'
            params = self.omit(params, ['postOnly'])
        request: dict = {
            'symbol': market['id'],
            'quantity': self.amount_to_precision(symbol, amount),
            'side': uppercaseSide,
            'orderTypes': uppercaseType,
            # 'clientOrderId': '123',
            # 'expireIn': 1575523308,  # in seconds
            # 'expireTime': 1575523308,  # unix timestamp
        }
        query = params
        if (uppercaseType == 'LIMIT') or (uppercaseType == 'POST_ONLY'):
            request['price'] = self.price_to_precision(symbol, price)
            defaultExpireIn = self.safe_integer(self.options, 'expireIn')
            expireTime = self.safe_value(params, 'expireTime')
            expireIn = self.safe_value(params, 'expireIn', defaultExpireIn)
            if expireTime is not None:
                request['expireTime'] = expireTime
            elif expireIn is not None:
                request['expireIn'] = expireIn
            else:
                raise InvalidOrder(self.id + ' createOrder() method requires a expireTime or expireIn param for a ' + type + ' order, you can also set the expireIn exchange-wide option')
            query = self.omit(params, ['expireTime', 'expireIn'])
        else:
            request['price'] = 0
        response = self.tradingPostOrders(self.extend(request, query))
        #
        #     {
        #         "orders": [
        #             {
        #                 "cancelledQuantity": "0.3",
        #                 "clientOrderId": "my-order-1",
        #                 "createdAt": "1970-01-01T00:00:00",
        #                 "cursorId": 50,
        #                 "expireTime": "1970-01-01T00:00:00",
        #                 "filledQuantity": "0.3",
        #                 "id": "string",
        #                 "price": "0.017",
        #                 "quantity": "0.3",
        #                 "side": "BUY",
        #                 "symbol": "TIMEETH",
        #                 "type": "LIMIT",
        #                 "updatedAt": "1970-01-01T00:00:00"
        #             }
        #         ]
        #     }
        #
        orders = self.safe_value(response, 'orders', [])
        order = self.safe_dict(orders, 0, {})
        return self.parse_order(order, market)

    def edit_order(self, id: str, symbol: str, type: OrderType, side: OrderSide, amount: Num = None, price: Num = None, params={}):
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'id': id,
        }
        if amount is not None:
            request['quantity'] = self.amount_to_precision(symbol, amount)
        if price is not None:
            request['price'] = self.price_to_precision(symbol, price)
        response = self.tradingPutOrders(self.extend(request, params))
        #
        #     {
        #         "changedOrders": [
        #             {
        #                 "newOrder": {
        #                 "cancelledQuantity": "0.3",
        #                 "clientOrderId": "my-order-1",
        #                 "createdAt": "1970-01-01T00:00:00",
        #                 "cursorId": 50,
        #                 "expireTime": "1970-01-01T00:00:00",
        #                 "filledQuantity": "0.3",
        #                 "id": "string",
        #                 "price": "0.017",
        #                 "quantity": "0.3",
        #                 "side": "BUY",
        #                 "symbol": "TIMEETH",
        #                 "type": "LIMIT",
        #                 "updatedAt": "1970-01-01T00:00:00"
        #                 },
        #                 "oldId": "string",
        #             },
        #         ],
        #         "unchangedOrders": ["string"],
        #     }
        #
        if 'unchangedOrders' in response:
            orderIds = self.safe_value(response, 'unchangedOrders', [])
            orderId = self.safe_string(orderIds, 0)
            return self.safe_order({
                'id': orderId,
                'info': response,
            })
        orders = self.safe_value(response, 'changedOrders', [])
        firstOrder = self.safe_value(orders, 0, {})
        order = self.safe_dict(firstOrder, 'newOrder', {})
        return self.parse_order(order, market)

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

        https://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Trading/deleteOrders

        :param str id: order id
        :param str symbol: not used by timex 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()
        orders = self.cancel_orders([id], symbol, params)
        return self.safe_dict(orders, 0)

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

        https://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Trading/deleteOrders

        :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 = {
            'id': ids,
        }
        response = self.tradingDeleteOrders(self.extend(request, params))
        #
        #     {
        #         "changedOrders": [
        #             {
        #                 "newOrder": {
        #                     "cancelledQuantity": "0.3",
        #                     "clientOrderId": "my-order-1",
        #                     "createdAt": "1970-01-01T00:00:00",
        #                     "cursorId": 50,
        #                     "expireTime": "1970-01-01T00:00:00",
        #                     "filledQuantity": "0.3",
        #                     "id": "string",
        #                     "price": "0.017",
        #                     "quantity": "0.3",
        #                     "side": "BUY",
        #                     "symbol": "TIMEETH",
        #                     "type": "LIMIT",
        #                     "updatedAt": "1970-01-01T00:00:00"
        #                 },
        #                 "oldId": "string",
        #             },
        #         ],
        #         "unchangedOrders": ["string"],
        #     }
        #
        changedOrders = self.safe_list(response, 'changedOrders', [])
        unchangedOrders = self.safe_list(response, 'unchangedOrders', [])
        orders = []
        for i in range(0, len(changedOrders)):
            newOrder = self.safe_dict(changedOrders[i], 'newOrder')
            orders.append(self.parse_order(newOrder))
        for i in range(0, len(unchangedOrders)):
            orders.append(self.safe_order({
                'info': unchangedOrders[i],
                'id': unchangedOrders[i],
                'status': 'unchanged',
            }))
        return orders

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

        https://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/History/getOrderDetails

        :param str id: order id
        :param str symbol: not used by timex 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 = {
            'orderHash': id,
        }
        response = self.historyGetOrdersDetails(request)
        #
        #     {
        #         "order": {
        #             "cancelledQuantity": "0.3",
        #             "clientOrderId": "my-order-1",
        #             "createdAt": "1970-01-01T00:00:00",
        #             "cursorId": 50,
        #             "expireTime": "1970-01-01T00:00:00",
        #             "filledQuantity": "0.3",
        #             "id": "string",
        #             "price": "0.017",
        #             "quantity": "0.3",
        #             "side": "BUY",
        #             "symbol": "TIMEETH",
        #             "type": "LIMIT",
        #             "updatedAt": "1970-01-01T00:00:00"
        #         },
        #         "trades": [
        #             {
        #                 "fee": "0.3",
        #                 "id": 100,
        #                 "makerOrTaker": "MAKER",
        #                 "makerOrderId": "string",
        #                 "price": "0.017",
        #                 "quantity": "0.3",
        #                 "side": "BUY",
        #                 "symbol": "TIMEETH",
        #                 "takerOrderId": "string",
        #                 "timestamp": "2019-12-05T07:48:26.310Z"
        #             }
        #         ]
        #     }
        #
        order = self.safe_value(response, 'order', {})
        trades = self.safe_list(response, 'trades', [])
        return self.parse_order(self.extend(order, {'trades': trades}))

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

        https://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Trading/getOpenOrders

        :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()
        options = self.safe_value(self.options, 'fetchOpenOrders', {})
        defaultSort = self.safe_value(options, 'sort', 'createdAt,asc')
        sort = self.safe_string(params, 'sort', defaultSort)
        query = self.omit(params, 'sort')
        request: dict = {
            # 'clientOrderId': '123',  # order’s client id list for filter
            # page: 0,  # results page you want to retrieve(0 .. N)
            'sort': sort,  # sorting criteria in the format "property,asc" or "property,desc", default order is ascending, multiple sort criteria are supported
        }
        market: Market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if limit is not None:
            request['size'] = limit
        response = self.tradingGetOrders(self.extend(request, query))
        #
        #     {
        #         "orders": [
        #             {
        #                 "cancelledQuantity": "0.3",
        #                 "clientOrderId": "my-order-1",
        #                 "createdAt": "1970-01-01T00:00:00",
        #                 "cursorId": 50,
        #                 "expireTime": "1970-01-01T00:00:00",
        #                 "filledQuantity": "0.3",
        #                 "id": "string",
        #                 "price": "0.017",
        #                 "quantity": "0.3",
        #                 "side": "BUY",
        #                 "symbol": "TIMEETH",
        #                 "type": "LIMIT",
        #                 "updatedAt": "1970-01-01T00:00:00"
        #             }
        #         ]
        #     }
        #
        orders = self.safe_list(response, 'orders', [])
        return self.parse_orders(orders, market, since, limit)

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

        https://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/History/getOrders

        :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>`
        """
        self.load_markets()
        options = self.safe_value(self.options, 'fetchClosedOrders', {})
        defaultSort = self.safe_value(options, 'sort', 'createdAt,asc')
        sort = self.safe_string(params, 'sort', defaultSort)
        query = self.omit(params, 'sort')
        request: dict = {
            # 'clientOrderId': '123',  # order’s client id list for filter
            # page: 0,  # results page you want to retrieve(0 .. N)
            'sort': sort,  # sorting criteria in the format "property,asc" or "property,desc", default order is ascending, multiple sort criteria are supported
            'side': 'BUY',  # or 'SELL'
            # 'till': self.iso8601(self.milliseconds()),
        }
        market: Market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            request['from'] = self.iso8601(since)
        if limit is not None:
            request['size'] = limit
        response = self.historyGetOrders(self.extend(request, query))
        #
        #     {
        #         "orders": [
        #             {
        #                 "cancelledQuantity": "0.3",
        #                 "clientOrderId": "my-order-1",
        #                 "createdAt": "1970-01-01T00:00:00",
        #                 "cursorId": 50,
        #                 "expireTime": "1970-01-01T00:00:00",
        #                 "filledQuantity": "0.3",
        #                 "id": "string",
        #                 "price": "0.017",
        #                 "quantity": "0.3",
        #                 "side": "BUY",
        #                 "symbol": "TIMEETH",
        #                 "type": "LIMIT",
        #                 "updatedAt": "1970-01-01T00:00:00"
        #             }
        #         ]
        #     }
        #
        orders = self.safe_list(response, 'orders', [])
        return self.parse_orders(orders, 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://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/History/getTrades_1

        :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()
        options = self.safe_value(self.options, 'fetchMyTrades', {})
        defaultSort = self.safe_value(options, 'sort', 'timestamp,asc')
        sort = self.safe_string(params, 'sort', defaultSort)
        query = self.omit(params, 'sort')
        request: dict = {
            # 'cursorId': 123,  # int64(?)
            # 'from': self.iso8601(since),
            # 'makerOrderId': '1234',  # maker order hash
            # 'owner': '...',  # owner address(?)
            # 'page': 0,  # results page you want to retrieve(0 .. N)
            # 'side': 'BUY',  # or 'SELL'
            # 'size': limit,
            'sort': sort,  # sorting criteria in the format "property,asc" or "property,desc", default order is ascending, multiple sort criteria are supported
            # 'symbol': market['id'],
            # 'takerOrderId': '1234',
            # 'till': self.iso8601(self.milliseconds()),
        }
        market: Market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            request['from'] = self.iso8601(since)
        if limit is not None:
            request['size'] = limit
        response = self.historyGetTrades(self.extend(request, query))
        #
        #     {
        #         "trades": [
        #             {
        #                 "fee": "0.3",
        #                 "id": 100,
        #                 "makerOrTaker": "MAKER",
        #                 "makerOrderId": "string",
        #                 "price": "0.017",
        #                 "quantity": "0.3",
        #                 "side": "BUY",
        #                 "symbol": "TIMEETH",
        #                 "takerOrderId": "string",
        #                 "timestamp": "2019-12-08T04:54:11.171Z"
        #             }
        #         ]
        #     }
        #
        trades = self.safe_list(response, 'trades', [])
        return self.parse_trades(trades, market, since, limit)

    def parse_trading_fee(self, fee: dict, market: Market = None) -> TradingFeeInterface:
        #
        #     {
        #         "fee": 0.0075,
        #         "market": "ETHBTC"
        #     }
        #
        marketId = self.safe_string(fee, 'market')
        rate = self.safe_number(fee, 'fee')
        return {
            'info': fee,
            'symbol': self.safe_symbol(marketId, market),
            'maker': rate,
            'taker': rate,
            'percentage': None,
            'tierBased': None,
        }

    def fetch_trading_fee(self, symbol: str, params={}) -> TradingFeeInterface:
        """
        fetch the trading fees for a market

        https://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Trading/getFees

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/#/?id=fee-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'markets': market['id'],
        }
        response = self.tradingGetFees(self.extend(request, params))
        #
        #     [
        #         {
        #             "fee": 0.0075,
        #             "market": "ETHBTC"
        #         }
        #     ]
        #
        result = self.safe_value(response, 0, {})
        return self.parse_trading_fee(result, market)

    def parse_market(self, market: dict) -> Market:
        #
        #     {
        #         "symbol": "ETHBTC",
        #         "name": "ETH/BTC",
        #         "baseCurrency": "ETH",
        #         "baseTokenAddress": "0x45932db54b38af1f5a57136302eeba66a5975c15",
        #         "quoteCurrency": "BTC",
        #         "quoteTokenAddress": "0x8370fbc6ddec1e18b4e41e72ed943e238458487c",
        #         "feeCurrency": "BTC",
        #         "feeTokenAddress": "0x8370fbc6ddec1e18b4e41e72ed943e238458487c",
        #         "quantityIncrement": "0.0000001",
        #         "takerFee": "0.005",
        #         "makerFee": "0.0025",
        #         "tickSize": "0.00000001",
        #         "baseMinSize": "0.0001",
        #         "quoteMinSize": "0.00001",
        #         "locked": False
        #     }
        #
        locked = self.safe_value(market, 'locked')
        id = self.safe_string(market, 'symbol')
        baseId = self.safe_string(market, 'baseCurrency')
        quoteId = self.safe_string(market, 'quoteCurrency')
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        amountIncrement = self.safe_string(market, 'quantityIncrement')
        minBase = self.safe_string(market, 'baseMinSize')
        minAmount = Precise.string_max(amountIncrement, minBase)
        priceIncrement = self.safe_string(market, 'tickSize')
        minCost = self.safe_number(market, 'quoteMinSize')
        return {
            'id': id,
            'symbol': base + '/' + quote,
            'base': base,
            'quote': quote,
            'settle': None,
            'baseId': baseId,
            'quoteId': quoteId,
            'settleId': None,
            'type': 'spot',
            'spot': True,
            'margin': False,
            'swap': False,
            'future': False,
            'option': False,
            'active': not locked,
            'contract': False,
            'linear': None,
            'inverse': None,
            'taker': self.safe_number(market, 'takerFee'),
            'maker': self.safe_number(market, 'makerFee'),
            'contractSize': None,
            'expiry': None,
            'expiryDatetime': None,
            'strike': None,
            'optionType': None,
            'precision': {
                'amount': self.safe_number(market, 'quantityIncrement'),
                'price': self.safe_number(market, 'tickSize'),
            },
            'limits': {
                'leverage': {
                    'min': None,
                    'max': None,
                },
                'amount': {
                    'min': self.parse_number(minAmount),
                    'max': None,
                },
                'price': {
                    'min': self.parse_number(priceIncrement),
                    'max': None,
                },
                'cost': {
                    'min': minCost,
                    'max': None,
                },
            },
            'created': None,
            'info': market,
        }

    def parse_currency(self, currency: dict) -> Currency:
        #
        #     {
        #         "symbol": "BTC",
        #         "name": "Bitcoin",
        #         "address": "0x8370fbc6ddec1e18b4e41e72ed943e238458487c",
        #         "icon": "data:image/svg+xml;base64,PHN2ZyB3aWR...mc+Cg==",
        #         "background": "transparent",
        #         "fiatSymbol": "BTC",
        #         "decimals": 8,
        #         "tradeDecimals": 20,
        #         "displayDecimals": 4,
        #         "crypto": True,
        #         "depositEnabled": True,
        #         "withdrawalEnabled": True,
        #         "transferEnabled": True,
        #         "buyEnabled": False,
        #         "purchaseEnabled": False,
        #         "redeemEnabled": False,
        #         "active": True,
        #         "withdrawalFee": "50000000000000000",
        #         "purchaseCommissions": []
        #     }
        #
        # https://github.com/ccxt/ccxt/issues/6878
        #
        #     {
        #         "symbol":"XRP",
        #         "name":"Ripple",
        #         "address":"0x0dc8882914f3ddeebf4cec6dc20edb99df3def6c",
        #         "decimals":6,
        #         "tradeDecimals":16,
        #         "depositEnabled":true,
        #         "withdrawalEnabled":true,
        #         "transferEnabled":true,
        #         "active":true
        #     }
        #
        id = self.safe_string(currency, 'symbol')
        code = self.safe_currency_code(id)
        # fee = self.safe_number(currency, 'withdrawalFee')
        feeString = self.safe_string(currency, 'withdrawalFee')
        tradeDecimals = self.safe_integer(currency, 'tradeDecimals')
        fee = None
        if (feeString is not None) and (tradeDecimals is not None):
            feeStringLen = len(feeString)
            dotIndex = feeStringLen - tradeDecimals
            if dotIndex > 0:
                whole = feeString[0:dotIndex]
                fraction = feeString[-dotIndex:]
                fee = self.parse_number(whole + '.' + fraction)
            else:
                fraction = '.'
                for i in range(0, -dotIndex):
                    fraction += '0'
                fee = self.parse_number(fraction + feeString)
        return self.safe_currency_structure({
            'id': code,
            'code': code,
            'info': currency,
            'type': None,
            'name': self.safe_string(currency, 'name'),
            'active': self.safe_bool(currency, 'active'),
            'deposit': self.safe_bool(currency, 'depositEnabled'),
            'withdraw': self.safe_bool(currency, 'withdrawalEnabled'),
            'fee': fee,
            'precision': self.parse_number(self.parse_precision(self.safe_string(currency, 'decimals'))),
            'limits': {
                'withdraw': {'min': None, 'max': None},
                'amount': {'min': None, 'max': None},
            },
            'networks': {},
        })

    def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
        #
        #     {
        #         "ask": 0.017,
        #         "bid": 0.016,
        #         "high": 0.019,
        #         "last": 0.017,
        #         "low": 0.015,
        #         "market": "TIME/ETH",
        #         "open": 0.016,
        #         "period": "H1",
        #         "timestamp": "2018-12-14T20:50:36.134Z",
        #         "volume": 4.57,
        #         "volumeQuote": 0.07312
        #     }
        #
        marketId = self.safe_string(ticker, 'market')
        symbol = self.safe_symbol(marketId, market, '/')
        timestamp = self.parse8601(self.safe_string(ticker, 'timestamp'))
        last = self.safe_string(ticker, 'last')
        open = self.safe_string(ticker, 'open')
        return self.safe_ticker({
            'symbol': symbol,
            'info': ticker,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': self.safe_string(ticker, 'high'),
            'low': self.safe_string(ticker, 'low'),
            'bid': self.safe_string(ticker, 'bid'),
            'bidVolume': None,
            'ask': self.safe_string(ticker, 'ask'),
            'askVolume': None,
            'vwap': None,
            'open': open,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': None,
            'percentage': None,
            'average': None,
            'baseVolume': self.safe_string(ticker, 'volume'),
            'quoteVolume': self.safe_string(ticker, 'volumeQuote'),
        }, market)

    def parse_trade(self, trade: dict, market: Market = None) -> Trade:
        #
        # fetchTrades(public)
        #
        #     {
        #         "id":1,
        #         "timestamp":"2019-06-25T17:01:50.309",
        #         "direction":"BUY",
        #         "price":"0.027",
        #         "quantity":"0.001"
        #     }
        #
        # fetchMyTrades, fetchOrder(private)
        #
        #     {
        #         "id": "7613414",
        #         "makerOrderId": "0x8420af060722f560098f786a2894d4358079b6ea5d14b395969ed77bc87a623a",
        #         "takerOrderId": "0x1235ef158a361815b54c9988b6241c85aedcbc1fe81caf8df8587d5ab0373d1a",
        #         "symbol": "LTCUSDT",
        #         "side": "BUY",
        #         "quantity": "0.2",
        #         "fee": "0.22685",
        #         "feeToken": "USDT",
        #         "price": "226.85",
        #         "makerOrTaker": "TAKER",
        #         "timestamp": "2021-04-09T15:39:45.608"
        #    }
        #
        marketId = self.safe_string(trade, 'symbol')
        symbol = self.safe_symbol(marketId, market)
        timestamp = self.parse8601(self.safe_string(trade, 'timestamp'))
        priceString = self.safe_string(trade, 'price')
        amountString = self.safe_string(trade, 'quantity')
        price = self.parse_number(priceString)
        amount = self.parse_number(amountString)
        cost = self.parse_number(Precise.string_mul(priceString, amountString))
        id = self.safe_string(trade, 'id')
        side = self.safe_string_lower_2(trade, 'direction', 'side')
        takerOrMaker = self.safe_string_lower(trade, 'makerOrTaker')
        orderId: Str = None
        if takerOrMaker is not None:
            orderId = self.safe_string(trade, takerOrMaker + 'OrderId')
        fee = None
        feeCost = self.safe_number(trade, 'fee')
        feeCurrency = self.safe_currency_code(self.safe_string(trade, 'feeToken'))
        if feeCost is not None:
            fee = {
                'cost': feeCost,
                'currency': feeCurrency,
            }
        return self.safe_trade({
            'info': trade,
            'id': id,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': symbol,
            'order': orderId,
            'type': None,
            'side': side,
            'price': price,
            'amount': amount,
            'cost': cost,
            'takerOrMaker': takerOrMaker,
            'fee': fee,
        })

    def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
        #
        #     {
        #         "timestamp":"2019-12-04T23:00:00",
        #         "open":"0.02024009",
        #         "high":"0.02024009",
        #         "low":"0.02024009",
        #         "close":"0.02024009",
        #         "volume":"0.00008096036",
        #         "volumeQuote":"0.004",
        #     }
        #
        return [
            self.parse8601(self.safe_string(ohlcv, 'timestamp')),
            self.safe_number(ohlcv, 'open'),
            self.safe_number(ohlcv, 'high'),
            self.safe_number(ohlcv, 'low'),
            self.safe_number(ohlcv, 'close'),
            self.safe_number(ohlcv, 'volume'),
        ]

    def parse_order(self, order: dict, market: Market = None) -> Order:
        #
        # fetchOrder, createOrder, cancelOrder, cancelOrders, fetchOpenOrders, fetchClosedOrders
        #
        #     {
        #         "cancelledQuantity": "0.3",
        #         "clientOrderId": "my-order-1",
        #         "createdAt": "1970-01-01T00:00:00",
        #         "cursorId": 50,
        #         "expireTime": "1970-01-01T00:00:00",
        #         "filledQuantity": "0.3",
        #         "id": "string",
        #         "price": "0.017",
        #         "quantity": "0.3",
        #         "side": "BUY",
        #         "symbol": "TIMEETH",
        #         "type": "LIMIT",
        #         "updatedAt": "1970-01-01T00:00:00"
        #         "trades": [],  # injected from the outside
        #     }
        #
        id = self.safe_string(order, 'id')
        type = self.safe_string_lower(order, 'type')
        side = self.safe_string_lower(order, 'side')
        marketId = self.safe_string(order, 'symbol')
        symbol = self.safe_symbol(marketId, market)
        timestamp = self.parse8601(self.safe_string(order, 'createdAt'))
        price = self.safe_string(order, 'price')
        amount = self.safe_string(order, 'quantity')
        filled = self.safe_string(order, 'filledQuantity')
        canceledQuantity = self.omit_zero(self.safe_string(order, 'cancelledQuantity'))
        status: str
        if Precise.string_equals(filled, amount):
            status = 'closed'
        elif canceledQuantity is not None:
            status = 'canceled'
        else:
            status = 'open'
        rawTrades = self.safe_value(order, 'trades', [])
        clientOrderId = self.safe_string(order, 'clientOrderId')
        return self.safe_order({
            'info': order,
            'id': id,
            'clientOrderId': clientOrderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'symbol': symbol,
            'type': type,
            'timeInForce': None,
            'postOnly': None,
            'side': side,
            'price': price,
            'triggerPrice': None,
            'amount': amount,
            'cost': None,
            'average': None,
            'filled': filled,
            'remaining': None,
            'status': status,
            'fee': None,
            'trades': rawTrades,
        }, market)

    def fetch_deposit_address(self, code: str, params={}) -> DepositAddress:
        """
        fetch the deposit address for a currency associated with self account, does not accept params["network"]

        https://plasma-relay-backend.timex.io/swagger-ui/index.html?urls.primaryName=Relay#/Currency/selectCurrencyBySymbol

        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        """
        self.load_markets()
        currency = self.currency(code)
        request: dict = {
            'symbol': currency['code'],
        }
        response = self.currenciesGetSSymbol(self.extend(request, params))
        #
        #    {
        #        id: '1',
        #        currency: {
        #            symbol: 'BTC',
        #            name: 'Bitcoin',
        #            address: '0x8370fbc6ddec1e18b4e41e72ed943e238458487c',
        #            decimals: '8',
        #            tradeDecimals: '20',
        #            fiatSymbol: 'BTC',
        #            depositEnabled: True,
        #            withdrawalEnabled: True,
        #            transferEnabled: True,
        #            active: True
        #        }
        #    }
        #
        data = self.safe_dict(response, 'currency', {})
        return self.parse_deposit_address(data, currency)

    def parse_deposit_address(self, depositAddress, currency: Currency = None) -> DepositAddress:
        #
        #    {
        #        symbol: 'BTC',
        #        name: 'Bitcoin',
        #        address: '0x8370fbc6ddec1e18b4e41e72ed943e238458487c',
        #        decimals: '8',
        #        tradeDecimals: '20',
        #        fiatSymbol: 'BTC',
        #        depositEnabled: True,
        #        withdrawalEnabled: True,
        #        transferEnabled: True,
        #        active: True
        #    }
        #
        currencyId = self.safe_string(depositAddress, 'symbol')
        return {
            'info': depositAddress,
            'currency': self.safe_currency_code(currencyId, currency),
            'network': None,
            'address': self.safe_string(depositAddress, 'address'),
            'tag': None,
        }

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        paramsToExtract = self.extract_params(path)
        path = self.implode_params(path, params)
        params = self.omit(params, paramsToExtract)
        url = self.urls['api']['rest'] + '/' + api + '/' + path
        if params:
            url += '?' + self.urlencode_with_array_repeat(params)
        if api != 'public' and api != 'tradingview':
            self.check_required_credentials()
            auth = self.string_to_base64(self.apiKey + ':' + self.secret)
            secret = 'Basic ' + auth
            headers = {'authorization': secret}
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, statusCode: int, statusText: str, url: str, method: str, responseHeaders: dict, responseBody, response, requestHeaders, requestBody):
        if response is None:
            return None
        if statusCode >= 400:
            #
            #     {"error":{"timestamp":"05.12.2019T05:25:43.584+0000","status":"BAD_REQUEST","message":"Insufficient ETH balance. Required: 1, actual: 0.","code":4001}}
            #     {"error":{"timestamp":"05.12.2019T04:03:25.419+0000","status":"FORBIDDEN","message":"Access denied","code":4300}}
            #
            feedback = self.id + ' ' + responseBody
            error = self.safe_value(response, 'error')
            if error is None:
                error = response
            code = self.safe_string_2(error, 'code', 'status')
            message = self.safe_string_2(error, 'message', 'debugMessage')
            self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback)
            self.throw_exactly_matched_exception(self.exceptions['exact'], code, feedback)
            self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
            raise ExchangeError(feedback)
        return None
