<gh_stars>1-10
# -*- coding: utf-8 -*-

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

from ccxt.async_support.base.exchange import Exchange
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import RequestTimeout
from ccxt.base.decimal_to_precision import TRUNCATE
from ccxt.base.decimal_to_precision import DECIMAL_PLACES
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class hitbtc(Exchange):

    def describe(self):
        return self.deep_extend(super(hitbtc, self).describe(), {
            'id': 'hitbtc',
            'name': 'HitBTC',
            'countries': ['HK'],
            # 300 requests per second => 1000ms / 300 = 3.333ms between requests on average(Trading)
            # 100 requests per second =>( 1000ms / rateLimit ) / 100 => cost = 3.0003(Market Data)
            # 10 requests per second =>( 1000ms / rateLimit ) / 10 => cost = 30.003(Other Requests)
            'rateLimit': 3.333,
            'version': '2',
            'pro': True,
            'has': {
                'CORS': None,
                'spot': True,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'addMargin': False,
                'cancelOrder': True,
                'createDepositAddress': True,
                'createOrder': True,
                'createReduceOnlyOrder': False,
                'editOrder': True,
                'fetchBalance': True,
                'fetchBorrowRate': False,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchBorrowRates': False,
                'fetchBorrowRatesPerSymbol': False,
                'fetchClosedOrders': True,
                'fetchCurrencies': True,
                'fetchDepositAddress': True,
                'fetchDeposits': None,
                'fetchFundingHistory': False,
                'fetchFundingRate': False,
                'fetchFundingRateHistory': False,
                'fetchFundingRates': False,
                'fetchIndexOHLCV': False,
                'fetchLeverage': False,
                'fetchLeverageTiers': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenOrder': True,
                'fetchOpenOrders': True,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrders': None,
                'fetchOrderTrades': True,
                'fetchPosition': False,
                'fetchPositions': False,
                'fetchPositionsRisk': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTrades': True,
                'fetchTradingFee': True,
                'fetchTradingFees': False,
                'fetchTransactions': True,
                'fetchWithdrawals': None,
                'reduceMargin': False,
                'setLeverage': False,
                'setMarginMode': False,
                'setPositionMode': False,
                'transfer': True,
                'withdraw': True,
            },
            'timeframes': {
                '1m': 'M1',
                '3m': 'M3',
                '5m': 'M5',
                '15m': 'M15',
                '30m': 'M30',  # default
                '1h': 'H1',
                '4h': 'H4',
                '1d': 'D1',
                '1w': 'D7',
                '1M': '1M',
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766555-8eaec20e-5edc-11e7-9c5b-6dc69fc42f5e.jpg',
                'test': {
                    'public': 'https://api.demo.hitbtc.com',
                    'private': 'https://api.demo.hitbtc.com',
                },
                'api': {
                    'public': 'https://api.hitbtc.com',
                    'private': 'https://api.hitbtc.com',
                },
                'www': 'https://hitbtc.com',
                'referral': 'https://hitbtc.com/?ref_id=5a5d39a65d466',
                'doc': [
                    'https://api.hitbtc.com/v2',
                ],
                'fees': [
                    'https://hitbtc.com/fees-and-limits',
                    'https://support.hitbtc.com/hc/en-us/articles/115005148605-Fees-and-limits',
                ],
            },
            'api': {
                'public': {
                    'get': {
                        'currency': 3,  # Available Currencies
                        'currency/{currency}': 3,  # Get currency info
                        'symbol': 3,  # Available Currency Symbols
                        'symbol/{symbol}': 3,  # Get symbol info
                        'ticker': 3,  # Ticker list for all symbols
                        'ticker/{symbol}': 3,  # Ticker for symbol
                        'trades': 3,
                        'trades/{symbol}': 3,  # Trades
                        'orderbook': 3,
                        'orderbook/{symbol}': 3,  # Orderbook
                        'candles': 3,
                        'candles/{symbol}': 3,  # Candles
                    },
                },
                'private': {
                    'get': {
                        'trading/balance': 30,  # Get trading balance
                        'order': 30,  # List your current open orders
                        'order/{clientOrderId}': 30,  # Get a single order by clientOrderId
                        'trading/fee/all': 30,  # Get trading fee rate
                        'trading/fee/{symbol}': 30,  # Get trading fee rate
                        'margin/account': 30,
                        'margin/account/{symbol}': 30,
                        'margin/position': 30,
                        'margin/position/{symbol}': 30,
                        'margin/order': 30,
                        'margin/order/{clientOrderId}': 30,
                        'history/order': 30,  # Get historical orders
                        'history/trades': 30,  # Get historical trades
                        'history/order/{orderId}/trades': 30,  # Get historical trades by specified order
                        'account/balance': 30,  # Get main acccount balance
                        'account/crypto/address/{currency}': 30,  # Get current address
                        'account/crypto/addresses/{currency}': 30,  # Get last 10 deposit addresses for currency
                        'account/crypto/used-addresses/{currency}': 30,  # Get last 10 unique addresses used for withdraw by currency
                        'account/crypto/estimate-withdraw': 30,
                        'account/crypto/is-mine/{address}': 30,
                        'account/transactions': 30,  # Get account transactions
                        'account/transactions/{id}': 30,  # Get account transaction by id
                        'sub-acc': 30,
                        'sub-acc/acl': 30,
                        'sub-acc/balance/{subAccountUserID}': 30,
                        'sub-acc/deposit-address/{subAccountUserId}/{currency}': 30,
                    },
                    'post': {
                        'order': 1,  # Create new order
                        'margin/order': 1,
                        'account/crypto/address/{currency}': 1,  # Create new crypto deposit address
                        'account/crypto/withdraw': 1,  # Withdraw crypto
                        'account/crypto/transfer-convert': 1,
                        'account/transfer': 1,  # Transfer amount to trading account or to main account
                        'account/transfer/internal': 1,
                        'sub-acc/freeze': 1,
                        'sub-acc/activate': 1,
                        'sub-acc/transfer': 1,
                    },
                    'put': {
                        'order/{clientOrderId}': 1,  # Create new order
                        'margin/account/{symbol}': 1,
                        'margin/order/{clientOrderId}': 1,
                        'account/crypto/withdraw/{id}': 1,  # Commit crypto withdrawal
                        'sub-acc/acl/{subAccountUserId}': 1,
                    },
                    'delete': {
                        'order': 1,  # Cancel all open orders
                        'order/{clientOrderId}': 1,  # Cancel order
                        'margin/account': 1,
                        'margin/account/{symbol}': 1,
                        'margin/position': 1,
                        'margin/position/{symbol}': 1,
                        'margin/order': 1,
                        'margin/order/{clientOrderId}': 1,
                        'account/crypto/withdraw/{id}': 1,  # Rollback crypto withdrawal
                    },
                    # outdated?
                    'patch': {
                        'order/{clientOrderId}': 1,  # Cancel Replace order
                    },
                },
            },
            'precisionMode': TICK_SIZE,
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'maker': 0.1 / 100,
                    'taker': 0.2 / 100,
                },
            },
            'options': {
                'networks': {
                    'ETH': 'T20',
                    'ERC20': 'T20',
                    'TRX': 'TTRX',
                    'TRC20': 'TTRX',
                    'OMNI': '',
                },
                'defaultTimeInForce': 'FOK',
                'accountsByType': {
                    'funding': 'bank',
                    'spot': 'exchange',
                },
                'fetchBalanceMethod': {
                    'account': 'account',
                    'bank': 'account',
                    'main': 'account',
                    'funding': 'account',
                    'exchange': 'trading',
                    'spot': 'trading',
                    'trade': 'trading',
                    'trading': 'trading',
                },
            },
            'commonCurrencies': {
                'AUTO': 'Cube',
                'BCC': 'BCC',  # initial symbol for Bitcoin Cash, now inactive
                'BDP': 'BidiPass',
                'BET': 'DAO.Casino',
                'BIT': 'BitRewards',
                'BOX': 'BOX Token',
                'CPT': 'Cryptaur',  # conflict with CPT = Contents Protocol https://github.com/ccxt/ccxt/issues/4920 and https://github.com/ccxt/ccxt/issues/6081
                'GET': 'Themis',
                'GMT': 'GMT Token',
                'HSR': 'HC',
                'IQ': 'IQ.Cash',
                'LNC': 'LinkerCoin',
                'PLA': 'PlayChip',
                'PNT': 'Penta',
                'SBTC': 'Super Bitcoin',
                'STEPN': 'GMT',
                'STX': 'STOX',
                'TV': 'Tokenville',
                'USD': 'USDT',
                'XMT': 'MTL',
                'XPNT': 'PNT',
            },
            'exceptions': {
                '504': RequestTimeout,  # {"error":{"code":504,"message":"Gateway Timeout"}}
                '1002': AuthenticationError,  # {"error":{"code":1002,"message":"Authorization failed","description":""}}
                '1003': PermissionDenied,  # "Action is forbidden for self API key"
                '2010': InvalidOrder,  # "Quantity not a valid number"
                '2001': BadSymbol,  # "Symbol not found"
                '2011': InvalidOrder,  # "Quantity too low"
                '2020': InvalidOrder,  # "Price not a valid number"
                '20002': OrderNotFound,  # canceling non-existent order
                '20001': InsufficientFunds,  # {"error":{"code":20001,"message":"Insufficient funds","description":"Check that the funds are sufficient, given commissions"}}
                '20010': BadSymbol,  # {"error":{"code":20010,"message":"Exchange temporary closed","description":"Exchange market for self symbol is temporary closed"}}
                '20045': InvalidOrder,  # {"error":{"code":20045,"message":"Fat finger limit exceeded"}}
            },
        })

    def fee_to_precision(self, symbol, fee):
        return self.decimal_to_precision(fee, TRUNCATE, 8, DECIMAL_PLACES)

    async def fetch_markets(self, params={}):
        response = await self.publicGetSymbol(params)
        #
        #     [
        #         {
        #             "id":"BCNBTC",
        #             "baseCurrency":"BCN",
        #             "quoteCurrency":"BTC",
        #             "quantityIncrement":"100",
        #             "tickSize":"0.00000000001",
        #             "takeLiquidityRate":"0.002",
        #             "provideLiquidityRate":"0.001",
        #             "feeCurrency":"BTC"
        #         }
        #     ]
        #
        result = []
        for i in range(0, len(response)):
            market = response[i]
            id = self.safe_string(market, 'id')
            baseId = self.safe_string(market, 'baseCurrency')
            quoteId = self.safe_string(market, 'quoteCurrency')
            base = self.safe_currency_code(baseId)
            quote = self.safe_currency_code(quoteId)
            # bequant fix
            symbol = base + '/' + quote
            if id.find('_') >= 0:
                symbol = id
            lotString = self.safe_string(market, 'quantityIncrement')
            stepString = self.safe_string(market, 'tickSize')
            lot = self.parse_number(lotString)
            step = self.parse_number(stepString)
            feeCurrencyId = self.safe_string(market, 'feeCurrency')
            result.append(self.extend(self.fees['trading'], {
                'id': id,
                'symbol': symbol,
                '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': True,
                'contract': False,
                'linear': None,
                'inverse': None,
                'taker': self.safe_number(market, 'takeLiquidityRate'),
                'maker': self.safe_number(market, 'provideLiquidityRate'),
                'contractSize': None,
                'expiry': None,
                'expiryDatetime': None,
                'strike': None,
                'optionType': None,
                'feeCurrency': self.safe_currency_code(feeCurrencyId),
                'precision': {
                    'amount': lot,
                    'price': step,
                },
                'limits': {
                    'leverage': {
                        'min': None,
                        'max': None,
                    },
                    'amount': {
                        'min': lot,
                        'max': None,
                    },
                    'price': {
                        'min': step,
                        'max': None,
                    },
                    'cost': {
                        'min': self.parse_number(Precise.string_mul(lotString, stepString)),
                        'max': None,
                    },
                },
                'info': market,
            }))
        return result

    async def transfer(self, code, amount, fromAccount, toAccount, params={}):
        # account can be "exchange" or "bank", with aliases "main" or "trading" respectively
        await self.load_markets()
        currency = self.currency(code)
        requestAmount = self.currency_to_precision(code, amount)
        request = {
            'currency': currency['id'],
            'amount': requestAmount,
        }
        type = self.safe_string(params, 'type')
        if type is None:
            accountsByType = self.safe_value(self.options, 'accountsByType', {})
            fromId = self.safe_string(accountsByType, fromAccount, fromAccount)
            toId = self.safe_string(accountsByType, toAccount, toAccount)
            if fromId == toId:
                raise ExchangeError(self.id + ' transfer() from and to cannot be the same account')
            type = fromId + 'To' + self.capitalize(toId)
        request['type'] = type
        response = await self.privatePostAccountTransfer(self.extend(request, params))
        #
        #     {
        #         'id': '2db6ebab-fb26-4537-9ef8-1a689472d236'
        #     }
        #
        transfer = self.parse_transfer(response, currency)
        return self.extend(transfer, {
            'fromAccount': fromAccount,
            'toAccount': toAccount,
            'amount': self.parse_number(requestAmount),
        })

    def parse_transfer(self, transfer, currency=None):
        #
        #     {
        #         'id': '2db6ebab-fb26-4537-9ef8-1a689472d236'
        #     }
        #
        timestamp = self.milliseconds()
        return {
            'id': self.safe_string(transfer, 'id'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'currency': self.safe_currency_code(None, currency),
            'amount': None,
            'fromAccount': None,
            'toAccount': None,
            'status': None,
            'info': transfer,
        }

    async def fetch_currencies(self, params={}):
        response = await self.publicGetCurrency(params)
        #
        #     [
        #         {
        #             "id":"XPNT",
        #             "fullName":"pToken",
        #             "crypto":true,
        #             "payinEnabled":true,
        #             "payinPaymentId":false,
        #             "payinConfirmations":9,
        #             "payoutEnabled":true,
        #             "payoutIsPaymentId":false,
        #             "transferEnabled":true,
        #             "delisted":false,
        #             "payoutFee":"26.510000000000",
        #             "precisionPayout":18,
        #             "precisionTransfer":8
        #         }
        #     ]
        #
        result = {}
        for i in range(0, len(response)):
            currency = response[i]
            id = self.safe_string(currency, 'id')
            # todo: will need to rethink the fees
            # to add support for multiple withdrawal/deposit methods and
            # differentiated fees for each particular method
            decimals = self.safe_integer(currency, 'precisionTransfer', 8)
            precision = 1 / math.pow(10, decimals)
            code = self.safe_currency_code(id)
            payin = self.safe_value(currency, 'payinEnabled')
            payout = self.safe_value(currency, 'payoutEnabled')
            transfer = self.safe_value(currency, 'transferEnabled')
            active = payin and payout and transfer
            if 'disabled' in currency:
                if currency['disabled']:
                    active = False
            type = 'fiat'
            if ('crypto' in currency) and currency['crypto']:
                type = 'crypto'
            name = self.safe_string(currency, 'fullName')
            result[code] = {
                'id': id,
                'code': code,
                'type': type,
                'payin': payin,
                'payout': payout,
                'transfer': transfer,
                'info': currency,
                'name': name,
                'active': active,
                'deposit': payin,
                'withdraw': payout,
                'fee': self.safe_number(currency, 'payoutFee'),  # todo: redesign
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': 1 / math.pow(10, decimals),
                        'max': math.pow(10, decimals),
                    },
                    'withdraw': {
                        'min': None,
                        'max': math.pow(10, precision),
                    },
                },
            }
        return result

    def parse_trading_fee(self, fee, market=None):
        #
        #
        #     {
        #         takeLiquidityRate: '0.001',
        #         provideLiquidityRate: '-0.0001'
        #     }
        #
        return {
            'info': fee,
            'symbol': self.safe_symbol(None, market),
            'maker': self.safe_number(fee, 'provideLiquidityRate'),
            'taker': self.safe_number(fee, 'takeLiquidityRate'),
            'percentage': True,
            'tierBased': True,
        }

    async def fetch_trading_fee(self, symbol, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.privateGetTradingFeeSymbol(request)
        #
        #     {
        #         takeLiquidityRate: '0.001',
        #         provideLiquidityRate: '-0.0001'
        #     }
        #
        return self.parse_trading_fee(response, market)

    def parse_balance(self, response):
        result = {
            '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['free'] = self.safe_string(balance, 'available')
            account['used'] = self.safe_string(balance, 'reserved')
            result[code] = account
        return self.safe_balance(result)

    async def fetch_balance(self, params={}):
        await self.load_markets()
        type = self.safe_string(params, 'type', 'trading')
        fetchBalanceAccounts = self.safe_value(self.options, 'fetchBalanceMethod', {})
        typeId = self.safe_string(fetchBalanceAccounts, type)
        if typeId is None:
            raise ExchangeError(self.id + ' fetchBalance() account type must be either main or trading')
        method = 'privateGet' + self.capitalize(typeId) + 'Balance'
        query = self.omit(params, 'type')
        response = await getattr(self, method)(query)
        #
        #     [
        #         {"currency":"SPI","available":"0","reserved":"0"},
        #         {"currency":"GRPH","available":"0","reserved":"0"},
        #         {"currency":"DGTX","available":"0","reserved":"0"},
        #     ]
        #
        return self.parse_balance(response)

    def parse_ohlcv(self, ohlcv, market=None):
        #
        #     {
        #         "timestamp":"2015-08-20T19:01:00.000Z",
        #         "open":"0.006",
        #         "close":"0.006",
        #         "min":"0.006",
        #         "max":"0.006",
        #         "volume":"0.003",
        #         "volumeQuote":"0.000018"
        #     }
        #
        return [
            self.parse8601(self.safe_string(ohlcv, 'timestamp')),
            self.safe_number(ohlcv, 'open'),
            self.safe_number(ohlcv, 'max'),
            self.safe_number(ohlcv, 'min'),
            self.safe_number(ohlcv, 'close'),
            self.safe_number(ohlcv, 'volume'),
        ]

    async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            'period': self.timeframes[timeframe],
        }
        if since is not None:
            request['from'] = self.iso8601(since)
        if limit is not None:
            request['limit'] = limit
        response = await self.publicGetCandlesSymbol(self.extend(request, params))
        #
        #     [
        #         {"timestamp":"2015-08-20T19:01:00.000Z","open":"0.006","close":"0.006","min":"0.006","max":"0.006","volume":"0.003","volumeQuote":"0.000018"},
        #         {"timestamp":"2015-08-20T19:03:00.000Z","open":"0.006","close":"0.006","min":"0.006","max":"0.006","volume":"0.013","volumeQuote":"0.000078"},
        #         {"timestamp":"2015-08-20T19:06:00.000Z","open":"0.0055","close":"0.005","min":"0.005","max":"0.0055","volume":"0.003","volumeQuote":"0.0000155"},
        #     ]
        #
        return self.parse_ohlcvs(response, market, timeframe, since, limit)

    async def fetch_order_book(self, symbol, limit=None, params={}):
        await self.load_markets()
        request = {
            'symbol': self.market_id(symbol),
        }
        if limit is not None:
            request['limit'] = limit  # default = 100, 0 = unlimited
        response = await self.publicGetOrderbookSymbol(self.extend(request, params))
        return self.parse_order_book(response, symbol, None, 'bid', 'ask', 'price', 'size')

    def parse_ticker(self, ticker, market=None):
        timestamp = self.parse8601(ticker['timestamp'])
        symbol = self.safe_symbol(None, market)
        baseVolume = self.safe_string(ticker, 'volume')
        quoteVolume = self.safe_string(ticker, 'volumeQuote')
        open = self.safe_string(ticker, 'open')
        last = self.safe_string(ticker, 'last')
        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, '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': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market, False)

    async def fetch_tickers(self, symbols=None, params={}):
        await self.load_markets()
        response = await self.publicGetTicker(params)
        result = {}
        for i in range(0, len(response)):
            ticker = response[i]
            marketId = self.safe_string(ticker, 'symbol')
            market = self.safe_market(marketId)
            symbol = market['symbol']
            result[symbol] = self.parse_ticker(ticker, market)
        return self.filter_by_array(result, 'symbol', symbols)

    async def fetch_ticker(self, symbol, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.publicGetTickerSymbol(self.extend(request, params))
        if 'message' in response:
            raise ExchangeError(self.id + ' ' + response['message'])
        return self.parse_ticker(response, market)

    def parse_trade(self, trade, market=None):
        # createMarketOrder
        #
        #  {      fee: "0.0004644",
        #           id:  386394956,
        #        price: "0.4644",
        #     quantity: "1",
        #    timestamp: "2018-10-25T16:41:44.780Z"}
        #
        # fetchTrades
        #
        # {id: 974786185,
        #   price: '0.032462',
        #   quantity: '0.3673',
        #   side: 'buy',
        #   timestamp: '2020-10-16T12:57:39.846Z'}
        #
        # fetchMyTrades
        #
        # {id: 277210397,
        #   clientOrderId: '6e102f3e7f3f4e04aeeb1cdc95592f1a',
        #   orderId: 28102855393,
        #   symbol: 'ETHBTC',
        #   side: 'sell',
        #   quantity: '0.002',
        #   price: '0.073365',
        #   fee: '0.000000147',
        #   timestamp: '2018-04-28T18:39:55.345Z'}
        #
        #  {
        #      "id":1568938909,
        #      "orderId":793293348428,
        #      "clientOrderId":"fbc5c5b753e8476cb14697458cb928ef",
        #      "symbol":"DOGEUSD",
        #      "side":"sell",
        #      "quantity":"100",
        #      "price":"0.03904191",
        #      "fee":"0.009760477500",
        #      "timestamp":"2022-01-25T15:15:41.353Z",
        #      "taker":true
        #  }
        #
        timestamp = self.parse8601(trade['timestamp'])
        marketId = self.safe_string(trade, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        fee = None
        feeCostString = self.safe_string(trade, 'fee')
        if feeCostString is not None:
            feeCurrencyCode = market['feeCurrency'] if market else None
            fee = {
                'cost': feeCostString,
                'currency': feeCurrencyCode,
            }
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        orderId = self.safe_string(trade, 'clientOrderId')
        priceString = self.safe_string(trade, 'price')
        amountString = self.safe_string(trade, 'quantity')
        side = self.safe_string(trade, 'side')
        id = self.safe_string(trade, 'id')
        return self.safe_trade({
            'info': trade,
            'id': id,
            'order': orderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': symbol,
            'type': None,
            'side': side,
            'takerOrMaker': None,
            'price': priceString,
            'amount': amountString,
            'cost': None,
            'fee': fee,
        }, market)

    async def fetch_transactions(self, code=None, since=None, limit=None, params={}):
        await self.load_markets()
        currency = None
        request = {}
        if code is not None:
            currency = self.currency(code)
            request['asset'] = currency['id']
        if since is not None:
            request['startTime'] = since
        response = await self.privateGetAccountTransactions(self.extend(request, params))
        return self.parse_transactions(response, currency, since, limit)

    def parse_transaction(self, transaction, currency=None):
        #
        # transactions
        #
        #     {
        #         id: '<PASSWORD>',
        #         index: 1044718371,
        #         type: 'payout',  # payout, payin
        #         status: 'success',
        #         currency: 'ETH',
        #         amount: '4.522683200000000000000000',
        #         createdAt: '2018-06-07T00:43:32.426Z',
        #         updatedAt: '2018-06-07T00:45:36.447Z',
        #         hash: '0x973e5683dfdf80a1fb1e0b96e19085b6489221d2ddf864daa46903c5ec283a0f',
        #         address: '0xC5a59b21948C1d230c8C54f05590000Eb3e1252c',
        #         fee: '0.00958',
        #     },
        #     {
        #         id: '<PASSWORD>',
        #         index: 1044714672,
        #         type: 'exchangeToBank',  # exchangeToBank, bankToExchange, withdraw
        #         status: 'success',
        #         currency: 'ETH',
        #         amount: '4.532263200000000000',
        #         createdAt: '2018-06-07T00:42:39.543Z',
        #         updatedAt: '2018-06-07T00:42:39.683Z',
        #     },
        #
        # withdraw
        #
        #     {
        #         "id": "d2ce578f-647d-4fa0-b1aa-4a27e5ee597b"
        #     }
        #
        id = self.safe_string(transaction, 'id')
        timestamp = self.parse8601(self.safe_string(transaction, 'createdAt'))
        updated = self.parse8601(self.safe_string(transaction, 'updatedAt'))
        currencyId = self.safe_string(transaction, 'currency')
        code = self.safe_currency_code(currencyId, currency)
        status = self.parse_transaction_status(self.safe_string(transaction, 'status'))
        amount = self.safe_number(transaction, 'amount')
        address = self.safe_string(transaction, 'address')
        txid = self.safe_string(transaction, 'hash')
        fee = None
        feeCost = self.safe_number(transaction, 'fee')
        if feeCost is not None:
            fee = {
                'cost': feeCost,
                'currency': code,
            }
        type = self.parse_transaction_type(self.safe_string(transaction, 'type'))
        return {
            'info': transaction,
            'id': id,
            'txid': txid,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'network': None,
            'address': address,
            'addressTo': None,
            'addressFrom': None,
            'tag': None,
            'tagTo': None,
            'tagFrom': None,
            'type': type,
            'amount': amount,
            'currency': code,
            'status': status,
            'updated': updated,
            'fee': fee,
        }

    def parse_transaction_status(self, status):
        statuses = {
            'pending': 'pending',
            'failed': 'failed',
            'success': 'ok',
        }
        return self.safe_string(statuses, status, status)

    def parse_transaction_type(self, type):
        types = {
            'payin': 'deposit',
            'payout': 'withdrawal',
            'withdraw': 'withdrawal',
        }
        return self.safe_string(types, type, type)

    async def fetch_trades(self, symbol, since=None, limit=None, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit
        if since is not None:
            request['sort'] = 'ASC'
            request['from'] = self.iso8601(since)
        response = await self.publicGetTradesSymbol(self.extend(request, params))
        return self.parse_trades(response, market, since, limit)

    async def create_order(self, symbol, type, side, amount, price=None, params={}):
        await self.load_markets()
        market = self.market(symbol)
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        # their max accepted length is 32 characters
        uuid = self.uuid()
        parts = uuid.split('-')
        clientOrderId = ''.join(parts)
        clientOrderId = clientOrderId[0:32]
        amount = float(amount)
        request = {
            'clientOrderId': clientOrderId,
            'symbol': market['id'],
            'side': side,
            'quantity': self.amount_to_precision(symbol, amount),
            'type': type,
        }
        if type == 'limit':
            request['price'] = self.price_to_precision(symbol, price)
        else:
            request['timeInForce'] = self.options['defaultTimeInForce']
        response = await self.privatePostOrder(self.extend(request, params))
        order = self.parse_order(response)
        if order['status'] == 'rejected':
            raise InvalidOrder(self.id + ' order was rejected by the exchange ' + self.json(order))
        return order

    async def edit_order(self, id, symbol, type, side, amount=None, price=None, params={}):
        await self.load_markets()
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        # their max accepted length is 32 characters
        uuid = self.uuid()
        parts = uuid.split('-')
        requestClientId = ''.join(parts)
        requestClientId = requestClientId[0:32]
        request = {
            'clientOrderId': id,
            'requestClientId': requestClientId,
        }
        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 = await self.privatePatchOrderClientOrderId(self.extend(request, params))
        return self.parse_order(response)

    async def cancel_order(self, id, symbol=None, params={}):
        await self.load_markets()
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        request = {
            'clientOrderId': id,
        }
        response = await self.privateDeleteOrderClientOrderId(self.extend(request, params))
        return self.parse_order(response)

    def parse_order_status(self, status):
        statuses = {
            'new': 'open',
            'suspended': 'open',
            'partiallyFilled': 'open',
            'filled': 'closed',
            'canceled': 'canceled',
            'expired': 'failed',
        }
        return self.safe_string(statuses, status, status)

    def parse_order(self, order, market=None):
        #
        # createMarketOrder
        #
        #     {
        #         clientOrderId: "fe36aa5e190149bf9985fb673bbb2ea0",
        #         createdAt: "2018-10-25T16:41:44.780Z",
        #         cumQuantity: "1",
        #         id: "66799540063",
        #         quantity: "1",
        #         side: "sell",
        #         status: "filled",
        #         symbol: "XRPUSDT",
        #         timeInForce: "FOK",
        #         tradesReport: [
        #             {
        #                 fee: "0.0004644",
        #                 id:  386394956,
        #                 price: "0.4644",
        #                 quantity: "1",
        #                 timestamp: "2018-10-25T16:41:44.780Z"
        #             }
        #         ],
        #         type: "market",
        #         updatedAt: "2018-10-25T16:41:44.780Z"
        #     }
        #
        #     {
        #         "id": 119499457455,
        #         "clientOrderId": "87baab109d58401b9202fa0749cb8288",
        #         "symbol": "ETHUSD",
        #         "side": "buy",
        #         "status": "filled",
        #         "type": "market",
        #         "timeInForce": "FOK",
        #         "quantity": "0.0007",
        #         "price": "181.487",
        #         "avgPrice": "164.989",
        #         "cumQuantity": "0.0007",
        #         "createdAt": "2019-04-17T13:27:38.062Z",
        #         "updatedAt": "2019-04-17T13:27:38.062Z"
        #     }
        #
        created = self.parse8601(self.safe_string(order, 'createdAt'))
        updated = self.parse8601(self.safe_string(order, 'updatedAt'))
        marketId = self.safe_string(order, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        amount = self.safe_string(order, 'quantity')
        filled = self.safe_string(order, 'cumQuantity')
        status = self.parse_order_status(self.safe_string(order, 'status'))
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        id = self.safe_string(order, 'clientOrderId')
        clientOrderId = id
        price = self.safe_string(order, 'price')
        type = self.safe_string(order, 'type')
        side = self.safe_string(order, 'side')
        trades = self.safe_value(order, 'tradesReport')
        fee = None
        average = self.safe_string(order, 'avgPrice')
        timeInForce = self.safe_string(order, 'timeInForce')
        return self.safe_order({
            'id': id,
            'clientOrderId': clientOrderId,  # https://github.com/ccxt/ccxt/issues/5674
            'timestamp': created,
            'datetime': self.iso8601(created),
            'lastTradeTimestamp': updated,
            'status': status,
            'symbol': symbol,
            'type': type,
            'timeInForce': timeInForce,
            'side': side,
            'price': price,
            'stopPrice': None,
            'average': average,
            'amount': amount,
            'cost': None,
            'filled': filled,
            'remaining': None,
            'fee': fee,
            'trades': trades,
            'info': order,
        }, market)

    async def fetch_order(self, id, symbol=None, params={}):
        await self.load_markets()
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        request = {
            'clientOrderId': id,
        }
        response = await self.privateGetHistoryOrder(self.extend(request, params))
        numOrders = len(response)
        if numOrders > 0:
            return self.parse_order(response[0])
        raise OrderNotFound(self.id + ' order ' + id + ' not found')

    async def fetch_open_order(self, id, symbol=None, params={}):
        await self.load_markets()
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        request = {
            'clientOrderId': id,
        }
        response = await self.privateGetOrderClientOrderId(self.extend(request, params))
        return self.parse_order(response)

    async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
        await self.load_markets()
        market = None
        request = {}
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        response = await self.privateGetOrder(self.extend(request, params))
        return self.parse_orders(response, market, since, limit)

    async def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
        await self.load_markets()
        market = None
        request = {}
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if limit is not None:
            request['limit'] = limit
        if since is not None:
            request['from'] = self.iso8601(since)
        response = await self.privateGetHistoryOrder(self.extend(request, params))
        parsedOrders = self.parse_orders(response, market)
        orders = []
        for i in range(0, len(parsedOrders)):
            order = parsedOrders[i]
            status = order['status']
            if (status == 'closed') or (status == 'canceled'):
                orders.append(order)
        return self.filter_by_since_limit(orders, since, limit)

    async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
        await self.load_markets()
        request = {
            # 'symbol': 'BTC/USD',  # optional
            # 'sort':   'DESC',  # or 'ASC'
            # 'by':     'timestamp',  # or 'id' String timestamp by default, or id
            # 'from':   'Datetime or Number',  # ISO 8601
            # 'till':   'Datetime or Number',
            # 'limit':  100,
            # 'offset': 0,
        }
        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['limit'] = limit
        response = await self.privateGetHistoryTrades(self.extend(request, params))
        #
        #     [
        #         {
        #             "id": 9535486,
        #             "clientOrderId": "f8dbaab336d44d5ba3ff578098a68454",
        #             "orderId": 816088377,
        #             "symbol": "ETHBTC",
        #             "side": "sell",
        #             "quantity": "0.061",
        #             "price": "0.045487",
        #             "fee": "0.000002775",
        #             "timestamp": "2017-05-17T12:32:57.848Z"
        #         },
        #         {
        #             "id": 9535437,
        #             "clientOrderId": "27b9bfc068b44194b1f453c7af511ed6",
        #             "orderId": 816088021,
        #             "symbol": "ETHBTC",
        #             "side": "buy",
        #             "quantity": "0.038",
        #             "price": "0.046000",
        #             "fee": "-0.000000174",
        #             "timestamp": "2017-05-17T12:30:57.848Z"
        #         }
        #     ]
        #
        return self.parse_trades(response, market, since, limit)

    async def fetch_order_trades(self, id, symbol=None, since=None, limit=None, params={}):
        # The id needed here is the exchange's id, and not the clientOrderID,
        # which is the id that is stored in the unified order id
        # To get the exchange's id you need to grab it from order['info']['id']
        await self.load_markets()
        market = None
        if symbol is not None:
            market = self.market(symbol)
        request = {
            'orderId': id,
        }
        response = await self.privateGetHistoryOrderOrderIdTrades(self.extend(request, params))
        numOrders = len(response)
        if numOrders > 0:
            return self.parse_trades(response, market, since, limit)
        raise OrderNotFound(self.id + ' order ' + id + ' not found, ' + self.id + '.fetchOrderTrades() requires an exchange-specific order id, you need to grab it from order["info"]["id"]')

    async def create_deposit_address(self, code, params={}):
        await self.load_markets()
        currency = self.currency(code)
        request = {
            'currency': currency['id'],
        }
        response = await self.privatePostAccountCryptoAddressCurrency(self.extend(request, params))
        address = self.safe_string(response, 'address')
        self.check_address(address)
        tag = self.safe_string(response, 'paymentId')
        return {
            'currency': currency,
            'address': address,
            'tag': tag,
            'info': response,
        }

    async def fetch_deposit_address(self, code, params={}):
        await self.load_markets()
        currency = self.currency(code)
        request = {
            'currency': currency['id'],
        }
        network = self.safe_string(params, 'network')
        if network is not None:
            params = self.omit(params, 'network')
            networks = self.safe_value(self.options, 'networks')
            endpart = self.safe_string(networks, network, network)
            request['currency'] += endpart
        response = await self.privateGetAccountCryptoAddressCurrency(self.extend(request, params))
        address = self.safe_string(response, 'address')
        self.check_address(address)
        tag = self.safe_string(response, 'paymentId')
        return {
            'currency': currency['code'],
            'address': address,
            'tag': tag,
            'network': None,
            'info': response,
        }

    async def convert_currency_network(self, code, amount, fromNetwork, toNetwork, params):
        await self.load_markets()
        currency = self.currency(code)
        networks = self.safe_value(self.options, 'networks', {})
        fromNetwork = self.safe_string(networks, fromNetwork, fromNetwork)  # handle ETH>ERC20 alias
        toNetwork = self.safe_string(networks, toNetwork, toNetwork)  # handle ETH>ERC20 alias
        if fromNetwork == toNetwork:
            raise ExchangeError(self.id + ' convertCurrencyNetwork() fromNetwork cannot be the same as toNetwork')
        request = {
            'fromCurrency': currency['id'] + fromNetwork,
            'toCurrency': currency['id'] + toNetwork,
            'amount': float(self.currency_to_precision(code, amount)),
        }
        response = await self.privatePostAccountCryptoTransferConvert(self.extend(request, params))
        return {
            'info': response,
        }

    async def withdraw(self, code, amount, address, tag=None, params={}):
        tag, params = self.handle_withdraw_tag_and_params(tag, params)
        await self.load_markets()
        self.check_address(address)
        currency = self.currency(code)
        request = {
            'currency': currency['id'],
            'amount': float(amount),
            'address': address,
        }
        if tag:
            request['paymentId'] = tag
        networks = self.safe_value(self.options, 'networks', {})
        network = self.safe_string_upper(params, 'network')  # self line allows the user to specify either ERC20 or ETH
        network = self.safe_string(networks, network, network)  # handle ERC20>ETH alias
        if network is not None:
            request['currency'] += network  # when network the currency need to be changed to currency + network
            params = self.omit(params, 'network')
        response = await self.privatePostAccountCryptoWithdraw(self.extend(request, params))
        #
        #     {
        #         "id": "d2ce578f-647d-4fa0-b1aa-4a27e5ee597b"
        #     }
        #
        return self.parse_transaction(response, currency)

    def nonce(self):
        return self.milliseconds()

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = '/api/' + self.version + '/'
        query = self.omit(params, self.extract_params(path))
        if api == 'public':
            url += api + '/' + self.implode_params(path, params)
            if query:
                url += '?' + self.urlencode(query)
        else:
            self.check_required_credentials()
            url += self.implode_params(path, params)
            if method == 'GET':
                if query:
                    url += '?' + self.urlencode(query)
            elif query:
                body = self.json(query)
            payload = self.encode(self.apiKey + ':' + self.secret)
            auth = self.string_to_base64(payload)
            headers = {
                'Authorization': 'Basic ' + self.decode(auth),
                'Content-Type': 'application/json',
            }
        url = self.urls['api'][api] + url
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
        if response is None:
            return
        if code >= 400:
            feedback = self.id + ' ' + body
            # {"code":504,"message":"Gateway Timeout","description":""}
            if (code == 503) or (code == 504):
                raise ExchangeNotAvailable(feedback)
            # fallback to default error handler on rate limit errors
            # {"code":429,"message":"Too many requests","description":"Too many requests"}
            if code == 429:
                return
            # {"error":{"code":20002,"message":"Order not found","description":""}}
            if body[0] == '{':
                if 'error' in response:
                    errorCode = self.safe_string(response['error'], 'code')
                    self.throw_exactly_matched_exception(self.exceptions, errorCode, feedback)
                    message = self.safe_string(response['error'], 'message')
                    if message == 'Duplicate clientOrderId':
                        raise InvalidOrder(feedback)
            raise ExchangeError(feedback)

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

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

from ccxt.async_support.base.exchange import Exchange
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import RequestTimeout
from ccxt.base.decimal_to_precision import TRUNCATE
from ccxt.base.decimal_to_precision import DECIMAL_PLACES
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class hitbtc(Exchange):

    def describe(self):
        return self.deep_extend(super(hitbtc, self).describe(), {
            'id': 'hitbtc',
            'name': 'HitBTC',
            'countries': ['HK'],
            # 300 requests per second => 1000ms / 300 = 3.333ms between requests on average(Trading)
            # 100 requests per second =>( 1000ms / rateLimit ) / 100 => cost = 3.0003(Market Data)
            # 10 requests per second =>( 1000ms / rateLimit ) / 10 => cost = 30.003(Other Requests)
            'rateLimit': 3.333,
            'version': '2',
            'pro': True,
            'has': {
                'CORS': None,
                'spot': True,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'addMargin': False,
                'cancelOrder': True,
                'createDepositAddress': True,
                'createOrder': True,
                'createReduceOnlyOrder': False,
                'editOrder': True,
                'fetchBalance': True,
                'fetchBorrowRate': False,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchBorrowRates': False,
                'fetchBorrowRatesPerSymbol': False,
                'fetchClosedOrders': True,
                'fetchCurrencies': True,
                'fetchDepositAddress': True,
                'fetchDeposits': None,
                'fetchFundingHistory': False,
                'fetchFundingRate': False,
                'fetchFundingRateHistory': False,
                'fetchFundingRates': False,
                'fetchIndexOHLCV': False,
                'fetchLeverage': False,
                'fetchLeverageTiers': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenOrder': True,
                'fetchOpenOrders': True,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrders': None,
                'fetchOrderTrades': True,
                'fetchPosition': False,
                'fetchPositions': False,
                'fetchPositionsRisk': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTrades': True,
                'fetchTradingFee': True,
                'fetchTradingFees': False,
                'fetchTransactions': True,
                'fetchWithdrawals': None,
                'reduceMargin': False,
                'setLeverage': False,
                'setMarginMode': False,
                'setPositionMode': False,
                'transfer': True,
                'withdraw': True,
            },
            'timeframes': {
                '1m': 'M1',
                '3m': 'M3',
                '5m': 'M5',
                '15m': 'M15',
                '30m': 'M30',  # default
                '1h': 'H1',
                '4h': 'H4',
                '1d': 'D1',
                '1w': 'D7',
                '1M': '1M',
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766555-8eaec20e-5edc-11e7-9c5b-6dc69fc42f5e.jpg',
                'test': {
                    'public': 'https://api.demo.hitbtc.com',
                    'private': 'https://api.demo.hitbtc.com',
                },
                'api': {
                    'public': 'https://api.hitbtc.com',
                    'private': 'https://api.hitbtc.com',
                },
                'www': 'https://hitbtc.com',
                'referral': 'https://hitbtc.com/?ref_id=5a5d39a65d466',
                'doc': [
                    'https://api.hitbtc.com/v2',
                ],
                'fees': [
                    'https://hitbtc.com/fees-and-limits',
                    'https://support.hitbtc.com/hc/en-us/articles/115005148605-Fees-and-limits',
                ],
            },
            'api': {
                'public': {
                    'get': {
                        'currency': 3,  # Available Currencies
                        'currency/{currency}': 3,  # Get currency info
                        'symbol': 3,  # Available Currency Symbols
                        'symbol/{symbol}': 3,  # Get symbol info
                        'ticker': 3,  # Ticker list for all symbols
                        'ticker/{symbol}': 3,  # Ticker for symbol
                        'trades': 3,
                        'trades/{symbol}': 3,  # Trades
                        'orderbook': 3,
                        'orderbook/{symbol}': 3,  # Orderbook
                        'candles': 3,
                        'candles/{symbol}': 3,  # Candles
                    },
                },
                'private': {
                    'get': {
                        'trading/balance': 30,  # Get trading balance
                        'order': 30,  # List your current open orders
                        'order/{clientOrderId}': 30,  # Get a single order by clientOrderId
                        'trading/fee/all': 30,  # Get trading fee rate
                        'trading/fee/{symbol}': 30,  # Get trading fee rate
                        'margin/account': 30,
                        'margin/account/{symbol}': 30,
                        'margin/position': 30,
                        'margin/position/{symbol}': 30,
                        'margin/order': 30,
                        'margin/order/{clientOrderId}': 30,
                        'history/order': 30,  # Get historical orders
                        'history/trades': 30,  # Get historical trades
                        'history/order/{orderId}/trades': 30,  # Get historical trades by specified order
                        'account/balance': 30,  # Get main acccount balance
                        'account/crypto/address/{currency}': 30,  # Get current address
                        'account/crypto/addresses/{currency}': 30,  # Get last 10 deposit addresses for currency
                        'account/crypto/used-addresses/{currency}': 30,  # Get last 10 unique addresses used for withdraw by currency
                        'account/crypto/estimate-withdraw': 30,
                        'account/crypto/is-mine/{address}': 30,
                        'account/transactions': 30,  # Get account transactions
                        'account/transactions/{id}': 30,  # Get account transaction by id
                        'sub-acc': 30,
                        'sub-acc/acl': 30,
                        'sub-acc/balance/{subAccountUserID}': 30,
                        'sub-acc/deposit-address/{subAccountUserId}/{currency}': 30,
                    },
                    'post': {
                        'order': 1,  # Create new order
                        'margin/order': 1,
                        'account/crypto/address/{currency}': 1,  # Create new crypto deposit address
                        'account/crypto/withdraw': 1,  # Withdraw crypto
                        'account/crypto/transfer-convert': 1,
                        'account/transfer': 1,  # Transfer amount to trading account or to main account
                        'account/transfer/internal': 1,
                        'sub-acc/freeze': 1,
                        'sub-acc/activate': 1,
                        'sub-acc/transfer': 1,
                    },
                    'put': {
                        'order/{clientOrderId}': 1,  # Create new order
                        'margin/account/{symbol}': 1,
                        'margin/order/{clientOrderId}': 1,
                        'account/crypto/withdraw/{id}': 1,  # Commit crypto withdrawal
                        'sub-acc/acl/{subAccountUserId}': 1,
                    },
                    'delete': {
                        'order': 1,  # Cancel all open orders
                        'order/{clientOrderId}': 1,  # Cancel order
                        'margin/account': 1,
                        'margin/account/{symbol}': 1,
                        'margin/position': 1,
                        'margin/position/{symbol}': 1,
                        'margin/order': 1,
                        'margin/order/{clientOrderId}': 1,
                        'account/crypto/withdraw/{id}': 1,  # Rollback crypto withdrawal
                    },
                    # outdated?
                    'patch': {
                        'order/{clientOrderId}': 1,  # Cancel Replace order
                    },
                },
            },
            'precisionMode': TICK_SIZE,
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'maker': 0.1 / 100,
                    'taker': 0.2 / 100,
                },
            },
            'options': {
                'networks': {
                    'ETH': 'T20',
                    'ERC20': 'T20',
                    'TRX': 'TTRX',
                    'TRC20': 'TTRX',
                    'OMNI': '',
                },
                'defaultTimeInForce': 'FOK',
                'accountsByType': {
                    'funding': 'bank',
                    'spot': 'exchange',
                },
                'fetchBalanceMethod': {
                    'account': 'account',
                    'bank': 'account',
                    'main': 'account',
                    'funding': 'account',
                    'exchange': 'trading',
                    'spot': 'trading',
                    'trade': 'trading',
                    'trading': 'trading',
                },
            },
            'commonCurrencies': {
                'AUTO': 'Cube',
                'BCC': 'BCC',  # initial symbol for Bitcoin Cash, now inactive
                'BDP': 'BidiPass',
                'BET': 'DAO.Casino',
                'BIT': 'BitRewards',
                'BOX': 'BOX Token',
                'CPT': 'Cryptaur',  # conflict with CPT = Contents Protocol https://github.com/ccxt/ccxt/issues/4920 and https://github.com/ccxt/ccxt/issues/6081
                'GET': 'Themis',
                'GMT': 'GMT Token',
                'HSR': 'HC',
                'IQ': 'IQ.Cash',
                'LNC': 'LinkerCoin',
                'PLA': 'PlayChip',
                'PNT': 'Penta',
                'SBTC': 'Super Bitcoin',
                'STEPN': 'GMT',
                'STX': 'STOX',
                'TV': 'Tokenville',
                'USD': 'USDT',
                'XMT': 'MTL',
                'XPNT': 'PNT',
            },
            'exceptions': {
                '504': RequestTimeout,  # {"error":{"code":504,"message":"Gateway Timeout"}}
                '1002': AuthenticationError,  # {"error":{"code":1002,"message":"Authorization failed","description":""}}
                '1003': PermissionDenied,  # "Action is forbidden for self API key"
                '2010': InvalidOrder,  # "Quantity not a valid number"
                '2001': BadSymbol,  # "Symbol not found"
                '2011': InvalidOrder,  # "Quantity too low"
                '2020': InvalidOrder,  # "Price not a valid number"
                '20002': OrderNotFound,  # canceling non-existent order
                '20001': InsufficientFunds,  # {"error":{"code":20001,"message":"Insufficient funds","description":"Check that the funds are sufficient, given commissions"}}
                '20010': BadSymbol,  # {"error":{"code":20010,"message":"Exchange temporary closed","description":"Exchange market for self symbol is temporary closed"}}
                '20045': InvalidOrder,  # {"error":{"code":20045,"message":"Fat finger limit exceeded"}}
            },
        })

    def fee_to_precision(self, symbol, fee):
        return self.decimal_to_precision(fee, TRUNCATE, 8, DECIMAL_PLACES)

    async def fetch_markets(self, params={}):
        response = await self.publicGetSymbol(params)
        #
        #     [
        #         {
        #             "id":"BCNBTC",
        #             "baseCurrency":"BCN",
        #             "quoteCurrency":"BTC",
        #             "quantityIncrement":"100",
        #             "tickSize":"0.00000000001",
        #             "takeLiquidityRate":"0.002",
        #             "provideLiquidityRate":"0.001",
        #             "feeCurrency":"BTC"
        #         }
        #     ]
        #
        result = []
        for i in range(0, len(response)):
            market = response[i]
            id = self.safe_string(market, 'id')
            baseId = self.safe_string(market, 'baseCurrency')
            quoteId = self.safe_string(market, 'quoteCurrency')
            base = self.safe_currency_code(baseId)
            quote = self.safe_currency_code(quoteId)
            # bequant fix
            symbol = base + '/' + quote
            if id.find('_') >= 0:
                symbol = id
            lotString = self.safe_string(market, 'quantityIncrement')
            stepString = self.safe_string(market, 'tickSize')
            lot = self.parse_number(lotString)
            step = self.parse_number(stepString)
            feeCurrencyId = self.safe_string(market, 'feeCurrency')
            result.append(self.extend(self.fees['trading'], {
                'id': id,
                'symbol': symbol,
                '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': True,
                'contract': False,
                'linear': None,
                'inverse': None,
                'taker': self.safe_number(market, 'takeLiquidityRate'),
                'maker': self.safe_number(market, 'provideLiquidityRate'),
                'contractSize': None,
                'expiry': None,
                'expiryDatetime': None,
                'strike': None,
                'optionType': None,
                'feeCurrency': self.safe_currency_code(feeCurrencyId),
                'precision': {
                    'amount': lot,
                    'price': step,
                },
                'limits': {
                    'leverage': {
                        'min': None,
                        'max': None,
                    },
                    'amount': {
                        'min': lot,
                        'max': None,
                    },
                    'price': {
                        'min': step,
                        'max': None,
                    },
                    'cost': {
                        'min': self.parse_number(Precise.string_mul(lotString, stepString)),
                        'max': None,
                    },
                },
                'info': market,
            }))
        return result

    async def transfer(self, code, amount, fromAccount, toAccount, params={}):
        # account can be "exchange" or "bank", with aliases "main" or "trading" respectively
        await self.load_markets()
        currency = self.currency(code)
        requestAmount = self.currency_to_precision(code, amount)
        request = {
            'currency': currency['id'],
            'amount': requestAmount,
        }
        type = self.safe_string(params, 'type')
        if type is None:
            accountsByType = self.safe_value(self.options, 'accountsByType', {})
            fromId = self.safe_string(accountsByType, fromAccount, fromAccount)
            toId = self.safe_string(accountsByType, toAccount, toAccount)
            if fromId == toId:
                raise ExchangeError(self.id + ' transfer() from and to cannot be the same account')
            type = fromId + 'To' + self.capitalize(toId)
        request['type'] = type
        response = await self.privatePostAccountTransfer(self.extend(request, params))
        #
        #     {
        #         'id': '2db6ebab-fb26-4537-9ef8-1a689472d236'
        #     }
        #
        transfer = self.parse_transfer(response, currency)
        return self.extend(transfer, {
            'fromAccount': fromAccount,
            'toAccount': toAccount,
            'amount': self.parse_number(requestAmount),
        })

    def parse_transfer(self, transfer, currency=None):
        #
        #     {
        #         'id': '2db6ebab-fb26-4537-9ef8-1a689472d236'
        #     }
        #
        timestamp = self.milliseconds()
        return {
            'id': self.safe_string(transfer, 'id'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'currency': self.safe_currency_code(None, currency),
            'amount': None,
            'fromAccount': None,
            'toAccount': None,
            'status': None,
            'info': transfer,
        }

    async def fetch_currencies(self, params={}):
        response = await self.publicGetCurrency(params)
        #
        #     [
        #         {
        #             "id":"XPNT",
        #             "fullName":"pToken",
        #             "crypto":true,
        #             "payinEnabled":true,
        #             "payinPaymentId":false,
        #             "payinConfirmations":9,
        #             "payoutEnabled":true,
        #             "payoutIsPaymentId":false,
        #             "transferEnabled":true,
        #             "delisted":false,
        #             "payoutFee":"26.510000000000",
        #             "precisionPayout":18,
        #             "precisionTransfer":8
        #         }
        #     ]
        #
        result = {}
        for i in range(0, len(response)):
            currency = response[i]
            id = self.safe_string(currency, 'id')
            # todo: will need to rethink the fees
            # to add support for multiple withdrawal/deposit methods and
            # differentiated fees for each particular method
            decimals = self.safe_integer(currency, 'precisionTransfer', 8)
            precision = 1 / math.pow(10, decimals)
            code = self.safe_currency_code(id)
            payin = self.safe_value(currency, 'payinEnabled')
            payout = self.safe_value(currency, 'payoutEnabled')
            transfer = self.safe_value(currency, 'transferEnabled')
            active = payin and payout and transfer
            if 'disabled' in currency:
                if currency['disabled']:
                    active = False
            type = 'fiat'
            if ('crypto' in currency) and currency['crypto']:
                type = 'crypto'
            name = self.safe_string(currency, 'fullName')
            result[code] = {
                'id': id,
                'code': code,
                'type': type,
                'payin': payin,
                'payout': payout,
                'transfer': transfer,
                'info': currency,
                'name': name,
                'active': active,
                'deposit': payin,
                'withdraw': payout,
                'fee': self.safe_number(currency, 'payoutFee'),  # todo: redesign
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': 1 / math.pow(10, decimals),
                        'max': math.pow(10, decimals),
                    },
                    'withdraw': {
                        'min': None,
                        'max': math.pow(10, precision),
                    },
                },
            }
        return result

    def parse_trading_fee(self, fee, market=None):
        #
        #
        #     {
        #         takeLiquidityRate: '0.001',
        #         provideLiquidityRate: '-0.0001'
        #     }
        #
        return {
            'info': fee,
            'symbol': self.safe_symbol(None, market),
            'maker': self.safe_number(fee, 'provideLiquidityRate'),
            'taker': self.safe_number(fee, 'takeLiquidityRate'),
            'percentage': True,
            'tierBased': True,
        }

    async def fetch_trading_fee(self, symbol, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.privateGetTradingFeeSymbol(request)
        #
        #     {
        #         takeLiquidityRate: '0.001',
        #         provideLiquidityRate: '-0.0001'
        #     }
        #
        return self.parse_trading_fee(response, market)

    def parse_balance(self, response):
        result = {
            '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['free'] = self.safe_string(balance, 'available')
            account['used'] = self.safe_string(balance, 'reserved')
            result[code] = account
        return self.safe_balance(result)

    async def fetch_balance(self, params={}):
        await self.load_markets()
        type = self.safe_string(params, 'type', 'trading')
        fetchBalanceAccounts = self.safe_value(self.options, 'fetchBalanceMethod', {})
        typeId = self.safe_string(fetchBalanceAccounts, type)
        if typeId is None:
            raise ExchangeError(self.id + ' fetchBalance() account type must be either main or trading')
        method = 'privateGet' + self.capitalize(typeId) + 'Balance'
        query = self.omit(params, 'type')
        response = await getattr(self, method)(query)
        #
        #     [
        #         {"currency":"SPI","available":"0","reserved":"0"},
        #         {"currency":"GRPH","available":"0","reserved":"0"},
        #         {"currency":"DGTX","available":"0","reserved":"0"},
        #     ]
        #
        return self.parse_balance(response)

    def parse_ohlcv(self, ohlcv, market=None):
        #
        #     {
        #         "timestamp":"2015-08-20T19:01:00.000Z",
        #         "open":"0.006",
        #         "close":"0.006",
        #         "min":"0.006",
        #         "max":"0.006",
        #         "volume":"0.003",
        #         "volumeQuote":"0.000018"
        #     }
        #
        return [
            self.parse8601(self.safe_string(ohlcv, 'timestamp')),
            self.safe_number(ohlcv, 'open'),
            self.safe_number(ohlcv, 'max'),
            self.safe_number(ohlcv, 'min'),
            self.safe_number(ohlcv, 'close'),
            self.safe_number(ohlcv, 'volume'),
        ]

    async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            'period': self.timeframes[timeframe],
        }
        if since is not None:
            request['from'] = self.iso8601(since)
        if limit is not None:
            request['limit'] = limit
        response = await self.publicGetCandlesSymbol(self.extend(request, params))
        #
        #     [
        #         {"timestamp":"2015-08-20T19:01:00.000Z","open":"0.006","close":"0.006","min":"0.006","max":"0.006","volume":"0.003","volumeQuote":"0.000018"},
        #         {"timestamp":"2015-08-20T19:03:00.000Z","open":"0.006","close":"0.006","min":"0.006","max":"0.006","volume":"0.013","volumeQuote":"0.000078"},
        #         {"timestamp":"2015-08-20T19:06:00.000Z","open":"0.0055","close":"0.005","min":"0.005","max":"0.0055","volume":"0.003","volumeQuote":"0.0000155"},
        #     ]
        #
        return self.parse_ohlcvs(response, market, timeframe, since, limit)

    async def fetch_order_book(self, symbol, limit=None, params={}):
        await self.load_markets()
        request = {
            'symbol': self.market_id(symbol),
        }
        if limit is not None:
            request['limit'] = limit  # default = 100, 0 = unlimited
        response = await self.publicGetOrderbookSymbol(self.extend(request, params))
        return self.parse_order_book(response, symbol, None, 'bid', 'ask', 'price', 'size')

    def parse_ticker(self, ticker, market=None):
        timestamp = self.parse8601(ticker['timestamp'])
        symbol = self.safe_symbol(None, market)
        baseVolume = self.safe_string(ticker, 'volume')
        quoteVolume = self.safe_string(ticker, 'volumeQuote')
        open = self.safe_string(ticker, 'open')
        last = self.safe_string(ticker, 'last')
        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, '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': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market, False)

    async def fetch_tickers(self, symbols=None, params={}):
        await self.load_markets()
        response = await self.publicGetTicker(params)
        result = {}
        for i in range(0, len(response)):
            ticker = response[i]
            marketId = self.safe_string(ticker, 'symbol')
            market = self.safe_market(marketId)
            symbol = market['symbol']
            result[symbol] = self.parse_ticker(ticker, market)
        return self.filter_by_array(result, 'symbol', symbols)

    async def fetch_ticker(self, symbol, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.publicGetTickerSymbol(self.extend(request, params))
        if 'message' in response:
            raise ExchangeError(self.id + ' ' + response['message'])
        return self.parse_ticker(response, market)

    def parse_trade(self, trade, market=None):
        # createMarketOrder
        #
        #  {      fee: "0.0004644",
        #           id:  386394956,
        #        price: "0.4644",
        #     quantity: "1",
        #    timestamp: "2018-10-25T16:41:44.780Z"}
        #
        # fetchTrades
        #
        # {id: 974786185,
        #   price: '0.032462',
        #   quantity: '0.3673',
        #   side: 'buy',
        #   timestamp: '2020-10-16T12:57:39.846Z'}
        #
        # fetchMyTrades
        #
        # {id: 277210397,
        #   clientOrderId: '6e102f3e7f3f4e04aeeb1cdc95592f1a',
        #   orderId: 28102855393,
        #   symbol: 'ETHBTC',
        #   side: 'sell',
        #   quantity: '0.002',
        #   price: '0.073365',
        #   fee: '0.000000147',
        #   timestamp: '2018-04-28T18:39:55.345Z'}
        #
        #  {
        #      "id":1568938909,
        #      "orderId":793293348428,
        #      "clientOrderId":"fbc5c5b753e8476cb14697458cb928ef",
        #      "symbol":"DOGEUSD",
        #      "side":"sell",
        #      "quantity":"100",
        #      "price":"0.03904191",
        #      "fee":"0.009760477500",
        #      "timestamp":"2022-01-25T15:15:41.353Z",
        #      "taker":true
        #  }
        #
        timestamp = self.parse8601(trade['timestamp'])
        marketId = self.safe_string(trade, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        fee = None
        feeCostString = self.safe_string(trade, 'fee')
        if feeCostString is not None:
            feeCurrencyCode = market['feeCurrency'] if market else None
            fee = {
                'cost': feeCostString,
                'currency': feeCurrencyCode,
            }
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        orderId = self.safe_string(trade, 'clientOrderId')
        priceString = self.safe_string(trade, 'price')
        amountString = self.safe_string(trade, 'quantity')
        side = self.safe_string(trade, 'side')
        id = self.safe_string(trade, 'id')
        return self.safe_trade({
            'info': trade,
            'id': id,
            'order': orderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': symbol,
            'type': None,
            'side': side,
            'takerOrMaker': None,
            'price': priceString,
            'amount': amountString,
            'cost': None,
            'fee': fee,
        }, market)

    async def fetch_transactions(self, code=None, since=None, limit=None, params={}):
        await self.load_markets()
        currency = None
        request = {}
        if code is not None:
            currency = self.currency(code)
            request['asset'] = currency['id']
        if since is not None:
            request['startTime'] = since
        response = await self.privateGetAccountTransactions(self.extend(request, params))
        return self.parse_transactions(response, currency, since, limit)

    def parse_transaction(self, transaction, currency=None):
        #
        # transactions
        #
        #     {
        #         id: '<PASSWORD>',
        #         index: 1044718371,
        #         type: 'payout',  # payout, payin
        #         status: 'success',
        #         currency: 'ETH',
        #         amount: '4.522683200000000000000000',
        #         createdAt: '2018-06-07T00:43:32.426Z',
        #         updatedAt: '2018-06-07T00:45:36.447Z',
        #         hash: '0x973e5683dfdf80a1fb1e0b96e19085b6489221d2ddf864daa46903c5ec283a0f',
        #         address: '0xC5a59b21948C1d230c8C54f05590000Eb3e1252c',
        #         fee: '0.00958',
        #     },
        #     {
        #         id: '<PASSWORD>',
        #         index: 1044714672,
        #         type: 'exchangeToBank',  # exchangeToBank, bankToExchange, withdraw
        #         status: 'success',
        #         currency: 'ETH',
        #         amount: '4.532263200000000000',
        #         createdAt: '2018-06-07T00:42:39.543Z',
        #         updatedAt: '2018-06-07T00:42:39.683Z',
        #     },
        #
        # withdraw
        #
        #     {
        #         "id": "d2ce578f-647d-4fa0-b1aa-4a27e5ee597b"
        #     }
        #
        id = self.safe_string(transaction, 'id')
        timestamp = self.parse8601(self.safe_string(transaction, 'createdAt'))
        updated = self.parse8601(self.safe_string(transaction, 'updatedAt'))
        currencyId = self.safe_string(transaction, 'currency')
        code = self.safe_currency_code(currencyId, currency)
        status = self.parse_transaction_status(self.safe_string(transaction, 'status'))
        amount = self.safe_number(transaction, 'amount')
        address = self.safe_string(transaction, 'address')
        txid = self.safe_string(transaction, 'hash')
        fee = None
        feeCost = self.safe_number(transaction, 'fee')
        if feeCost is not None:
            fee = {
                'cost': feeCost,
                'currency': code,
            }
        type = self.parse_transaction_type(self.safe_string(transaction, 'type'))
        return {
            'info': transaction,
            'id': id,
            'txid': txid,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'network': None,
            'address': address,
            'addressTo': None,
            'addressFrom': None,
            'tag': None,
            'tagTo': None,
            'tagFrom': None,
            'type': type,
            'amount': amount,
            'currency': code,
            'status': status,
            'updated': updated,
            'fee': fee,
        }

    def parse_transaction_status(self, status):
        statuses = {
            'pending': 'pending',
            'failed': 'failed',
            'success': 'ok',
        }
        return self.safe_string(statuses, status, status)

    def parse_transaction_type(self, type):
        types = {
            'payin': 'deposit',
            'payout': 'withdrawal',
            'withdraw': 'withdrawal',
        }
        return self.safe_string(types, type, type)

    async def fetch_trades(self, symbol, since=None, limit=None, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit
        if since is not None:
            request['sort'] = 'ASC'
            request['from'] = self.iso8601(since)
        response = await self.publicGetTradesSymbol(self.extend(request, params))
        return self.parse_trades(response, market, since, limit)

    async def create_order(self, symbol, type, side, amount, price=None, params={}):
        await self.load_markets()
        market = self.market(symbol)
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        # their max accepted length is 32 characters
        uuid = self.uuid()
        parts = uuid.split('-')
        clientOrderId = ''.join(parts)
        clientOrderId = clientOrderId[0:32]
        amount = float(amount)
        request = {
            'clientOrderId': clientOrderId,
            'symbol': market['id'],
            'side': side,
            'quantity': self.amount_to_precision(symbol, amount),
            'type': type,
        }
        if type == 'limit':
            request['price'] = self.price_to_precision(symbol, price)
        else:
            request['timeInForce'] = self.options['defaultTimeInForce']
        response = await self.privatePostOrder(self.extend(request, params))
        order = self.parse_order(response)
        if order['status'] == 'rejected':
            raise InvalidOrder(self.id + ' order was rejected by the exchange ' + self.json(order))
        return order

    async def edit_order(self, id, symbol, type, side, amount=None, price=None, params={}):
        await self.load_markets()
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        # their max accepted length is 32 characters
        uuid = self.uuid()
        parts = uuid.split('-')
        requestClientId = ''.join(parts)
        requestClientId = requestClientId[0:32]
        request = {
            'clientOrderId': id,
            'requestClientId': requestClientId,
        }
        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 = await self.privatePatchOrderClientOrderId(self.extend(request, params))
        return self.parse_order(response)

    async def cancel_order(self, id, symbol=None, params={}):
        await self.load_markets()
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        request = {
            'clientOrderId': id,
        }
        response = await self.privateDeleteOrderClientOrderId(self.extend(request, params))
        return self.parse_order(response)

    def parse_order_status(self, status):
        statuses = {
            'new': 'open',
            'suspended': 'open',
            'partiallyFilled': 'open',
            'filled': 'closed',
            'canceled': 'canceled',
            'expired': 'failed',
        }
        return self.safe_string(statuses, status, status)

    def parse_order(self, order, market=None):
        #
        # createMarketOrder
        #
        #     {
        #         clientOrderId: "fe36aa5e190149bf9985fb673bbb2ea0",
        #         createdAt: "2018-10-25T16:41:44.780Z",
        #         cumQuantity: "1",
        #         id: "66799540063",
        #         quantity: "1",
        #         side: "sell",
        #         status: "filled",
        #         symbol: "XRPUSDT",
        #         timeInForce: "FOK",
        #         tradesReport: [
        #             {
        #                 fee: "0.0004644",
        #                 id:  386394956,
        #                 price: "0.4644",
        #                 quantity: "1",
        #                 timestamp: "2018-10-25T16:41:44.780Z"
        #             }
        #         ],
        #         type: "market",
        #         updatedAt: "2018-10-25T16:41:44.780Z"
        #     }
        #
        #     {
        #         "id": 119499457455,
        #         "clientOrderId": "87baab109d58401b9202fa0749cb8288",
        #         "symbol": "ETHUSD",
        #         "side": "buy",
        #         "status": "filled",
        #         "type": "market",
        #         "timeInForce": "FOK",
        #         "quantity": "0.0007",
        #         "price": "181.487",
        #         "avgPrice": "164.989",
        #         "cumQuantity": "0.0007",
        #         "createdAt": "2019-04-17T13:27:38.062Z",
        #         "updatedAt": "2019-04-17T13:27:38.062Z"
        #     }
        #
        created = self.parse8601(self.safe_string(order, 'createdAt'))
        updated = self.parse8601(self.safe_string(order, 'updatedAt'))
        marketId = self.safe_string(order, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        amount = self.safe_string(order, 'quantity')
        filled = self.safe_string(order, 'cumQuantity')
        status = self.parse_order_status(self.safe_string(order, 'status'))
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        id = self.safe_string(order, 'clientOrderId')
        clientOrderId = id
        price = self.safe_string(order, 'price')
        type = self.safe_string(order, 'type')
        side = self.safe_string(order, 'side')
        trades = self.safe_value(order, 'tradesReport')
        fee = None
        average = self.safe_string(order, 'avgPrice')
        timeInForce = self.safe_string(order, 'timeInForce')
        return self.safe_order({
            'id': id,
            'clientOrderId': clientOrderId,  # https://github.com/ccxt/ccxt/issues/5674
            'timestamp': created,
            'datetime': self.iso8601(created),
            'lastTradeTimestamp': updated,
            'status': status,
            'symbol': symbol,
            'type': type,
            'timeInForce': timeInForce,
            'side': side,
            'price': price,
            'stopPrice': None,
            'average': average,
            'amount': amount,
            'cost': None,
            'filled': filled,
            'remaining': None,
            'fee': fee,
            'trades': trades,
            'info': order,
        }, market)

    async def fetch_order(self, id, symbol=None, params={}):
        await self.load_markets()
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        request = {
            'clientOrderId': id,
        }
        response = await self.privateGetHistoryOrder(self.extend(request, params))
        numOrders = len(response)
        if numOrders > 0:
            return self.parse_order(response[0])
        raise OrderNotFound(self.id + ' order ' + id + ' not found')

    async def fetch_open_order(self, id, symbol=None, params={}):
        await self.load_markets()
        # we use clientOrderId as the order id with self exchange intentionally
        # because most of their endpoints will require clientOrderId
        # explained here: https://github.com/ccxt/ccxt/issues/5674
        request = {
            'clientOrderId': id,
        }
        response = await self.privateGetOrderClientOrderId(self.extend(request, params))
        return self.parse_order(response)

    async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
        await self.load_markets()
        market = None
        request = {}
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        response = await self.privateGetOrder(self.extend(request, params))
        return self.parse_orders(response, market, since, limit)

    async def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
        await self.load_markets()
        market = None
        request = {}
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if limit is not None:
            request['limit'] = limit
        if since is not None:
            request['from'] = self.iso8601(since)
        response = await self.privateGetHistoryOrder(self.extend(request, params))
        parsedOrders = self.parse_orders(response, market)
        orders = []
        for i in range(0, len(parsedOrders)):
            order = parsedOrders[i]
            status = order['status']
            if (status == 'closed') or (status == 'canceled'):
                orders.append(order)
        return self.filter_by_since_limit(orders, since, limit)

    async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
        await self.load_markets()
        request = {
            # 'symbol': 'BTC/USD',  # optional
            # 'sort':   'DESC',  # or 'ASC'
            # 'by':     'timestamp',  # or 'id' String timestamp by default, or id
            # 'from':   'Datetime or Number',  # ISO 8601
            # 'till':   'Datetime or Number',
            # 'limit':  100,
            # 'offset': 0,
        }
        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['limit'] = limit
        response = await self.privateGetHistoryTrades(self.extend(request, params))
        #
        #     [
        #         {
        #             "id": 9535486,
        #             "clientOrderId": "f8dbaab336d44d5ba3ff578098a68454",
        #             "orderId": 816088377,
        #             "symbol": "ETHBTC",
        #             "side": "sell",
        #             "quantity": "0.061",
        #             "price": "0.045487",
        #             "fee": "0.000002775",
        #             "timestamp": "2017-05-17T12:32:57.848Z"
        #         },
        #         {
        #             "id": 9535437,
        #             "clientOrderId": "27b9bfc068b44194b1f453c7af511ed6",
        #             "orderId": 816088021,
        #             "symbol": "ETHBTC",
        #             "side": "buy",
        #             "quantity": "0.038",
        #             "price": "0.046000",
        #             "fee": "-0.000000174",
        #             "timestamp": "2017-05-17T12:30:57.848Z"
        #         }
        #     ]
        #
        return self.parse_trades(response, market, since, limit)

    async def fetch_order_trades(self, id, symbol=None, since=None, limit=None, params={}):
        # The id needed here is the exchange's id, and not the clientOrderID,
        # which is the id that is stored in the unified order id
        # To get the exchange's id you need to grab it from order['info']['id']
        await self.load_markets()
        market = None
        if symbol is not None:
            market = self.market(symbol)
        request = {
            'orderId': id,
        }
        response = await self.privateGetHistoryOrderOrderIdTrades(self.extend(request, params))
        numOrders = len(response)
        if numOrders > 0:
            return self.parse_trades(response, market, since, limit)
        raise OrderNotFound(self.id + ' order ' + id + ' not found, ' + self.id + '.fetchOrderTrades() requires an exchange-specific order id, you need to grab it from order["info"]["id"]')

    async def create_deposit_address(self, code, params={}):
        await self.load_markets()
        currency = self.currency(code)
        request = {
            'currency': currency['id'],
        }
        response = await self.privatePostAccountCryptoAddressCurrency(self.extend(request, params))
        address = self.safe_string(response, 'address')
        self.check_address(address)
        tag = self.safe_string(response, 'paymentId')
        return {
            'currency': currency,
            'address': address,
            'tag': tag,
            'info': response,
        }

    async def fetch_deposit_address(self, code, params={}):
        await self.load_markets()
        currency = self.currency(code)
        request = {
            'currency': currency['id'],
        }
        network = self.safe_string(params, 'network')
        if network is not None:
            params = self.omit(params, 'network')
            networks = self.safe_value(self.options, 'networks')
            endpart = self.safe_string(networks, network, network)
            request['currency'] += endpart
        response = await self.privateGetAccountCryptoAddressCurrency(self.extend(request, params))
        address = self.safe_string(response, 'address')
        self.check_address(address)
        tag = self.safe_string(response, 'paymentId')
        return {
            'currency': currency['code'],
            'address': address,
            'tag': tag,
            'network': None,
            'info': response,
        }

    async def convert_currency_network(self, code, amount, fromNetwork, toNetwork, params):
        await self.load_markets()
        currency = self.currency(code)
        networks = self.safe_value(self.options, 'networks', {})
        fromNetwork = self.safe_string(networks, fromNetwork, fromNetwork)  # handle ETH>ERC20 alias
        toNetwork = self.safe_string(networks, toNetwork, toNetwork)  # handle ETH>ERC20 alias
        if fromNetwork == toNetwork:
            raise ExchangeError(self.id + ' convertCurrencyNetwork() fromNetwork cannot be the same as toNetwork')
        request = {
            'fromCurrency': currency['id'] + fromNetwork,
            'toCurrency': currency['id'] + toNetwork,
            'amount': float(self.currency_to_precision(code, amount)),
        }
        response = await self.privatePostAccountCryptoTransferConvert(self.extend(request, params))
        return {
            'info': response,
        }

    async def withdraw(self, code, amount, address, tag=None, params={}):
        tag, params = self.handle_withdraw_tag_and_params(tag, params)
        await self.load_markets()
        self.check_address(address)
        currency = self.currency(code)
        request = {
            'currency': currency['id'],
            'amount': float(amount),
            'address': address,
        }
        if tag:
            request['paymentId'] = tag
        networks = self.safe_value(self.options, 'networks', {})
        network = self.safe_string_upper(params, 'network')  # self line allows the user to specify either ERC20 or ETH
        network = self.safe_string(networks, network, network)  # handle ERC20>ETH alias
        if network is not None:
            request['currency'] += network  # when network the currency need to be changed to currency + network
            params = self.omit(params, 'network')
        response = await self.privatePostAccountCryptoWithdraw(self.extend(request, params))
        #
        #     {
        #         "id": "d2ce578f-647d-4fa0-b1aa-4a27e5ee597b"
        #     }
        #
        return self.parse_transaction(response, currency)

    def nonce(self):
        return self.milliseconds()

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = '/api/' + self.version + '/'
        query = self.omit(params, self.extract_params(path))
        if api == 'public':
            url += api + '/' + self.implode_params(path, params)
            if query:
                url += '?' + self.urlencode(query)
        else:
            self.check_required_credentials()
            url += self.implode_params(path, params)
            if method == 'GET':
                if query:
                    url += '?' + self.urlencode(query)
            elif query:
                body = self.json(query)
            payload = self.encode(self.apiKey + ':' + self.secret)
            auth = self.string_to_base64(payload)
            headers = {
                'Authorization': 'Basic ' + self.decode(auth),
                'Content-Type': 'application/json',
            }
        url = self.urls['api'][api] + url
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
        if response is None:
            return
        if code >= 400:
            feedback = self.id + ' ' + body
            # {"code":504,"message":"Gateway Timeout","description":""}
            if (code == 503) or (code == 504):
                raise ExchangeNotAvailable(feedback)
            # fallback to default error handler on rate limit errors
            # {"code":429,"message":"Too many requests","description":"Too many requests"}
            if code == 429:
                return
            # {"error":{"code":20002,"message":"Order not found","description":""}}
            if body[0] == '{':
                if 'error' in response:
                    errorCode = self.safe_string(response['error'], 'code')
                    self.throw_exactly_matched_exception(self.exceptions, errorCode, feedback)
                    message = self.safe_string(response['error'], 'message')
                    if message == 'Duplicate clientOrderId':
                        raise InvalidOrder(feedback)
            raise ExchangeError(feedback)
# -*- 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 # 300 requests per second => 1000ms / 300 = 3.333ms between requests on average(Trading) # 100 requests per second =>( 1000ms / rateLimit ) / 100 => cost = 3.0003(Market Data) # 10 requests per second =>( 1000ms / rateLimit ) / 10 => cost = 30.003(Other Requests) # default # Available Currencies # Get currency info # Available Currency Symbols # Get symbol info # Ticker list for all symbols # Ticker for symbol # Trades # Orderbook # Candles # Get trading balance # List your current open orders # Get a single order by clientOrderId # Get trading fee rate # Get trading fee rate # Get historical orders # Get historical trades # Get historical trades by specified order # Get main acccount balance # Get current address # Get last 10 deposit addresses for currency # Get last 10 unique addresses used for withdraw by currency # Get account transactions # Get account transaction by id # Create new order # Create new crypto deposit address # Withdraw crypto # Transfer amount to trading account or to main account # Create new order # Commit crypto withdrawal # Cancel all open orders # Cancel order # Rollback crypto withdrawal # outdated? # Cancel Replace order # initial symbol for Bitcoin Cash, now inactive # conflict with CPT = Contents Protocol https://github.com/ccxt/ccxt/issues/4920 and https://github.com/ccxt/ccxt/issues/6081 # {"error":{"code":504,"message":"Gateway Timeout"}} # {"error":{"code":1002,"message":"Authorization failed","description":""}} # "Action is forbidden for self API key" # "Quantity not a valid number" # "Symbol not found" # "Quantity too low" # "Price not a valid number" # canceling non-existent order # {"error":{"code":20001,"message":"Insufficient funds","description":"Check that the funds are sufficient, given commissions"}} # {"error":{"code":20010,"message":"Exchange temporary closed","description":"Exchange market for self symbol is temporary closed"}} # {"error":{"code":20045,"message":"Fat finger limit exceeded"}} # #     [ #         { #             "id":"BCNBTC", #             "baseCurrency":"BCN", #             "quoteCurrency":"BTC", #             "quantityIncrement":"100", #             "tickSize":"0.00000000001", #             "takeLiquidityRate":"0.002", #             "provideLiquidityRate":"0.001", #             "feeCurrency":"BTC" #         } #     ] # # bequant fix # account can be "exchange" or "bank", with aliases "main" or "trading" respectively # #     { #         'id': '2db6ebab-fb26-4537-9ef8-1a689472d236' #     } # # #     { #         'id': '2db6ebab-fb26-4537-9ef8-1a689472d236' #     } # # #     [ #         { #             "id":"XPNT", #             "fullName":"pToken", #             "crypto":true, #             "payinEnabled":true, #             "payinPaymentId":false, #             "payinConfirmations":9, #             "payoutEnabled":true, #             "payoutIsPaymentId":false, #             "transferEnabled":true, #             "delisted":false, #             "payoutFee":"26.510000000000", #             "precisionPayout":18, #             "precisionTransfer":8 #         } #     ] # # todo: will need to rethink the fees # to add support for multiple withdrawal/deposit methods and # differentiated fees for each particular method # todo: redesign # # #     { #         takeLiquidityRate: '0.001', #         provideLiquidityRate: '-0.0001' #     } # # #     { #         takeLiquidityRate: '0.001', #         provideLiquidityRate: '-0.0001' #     } # # #     [ #         {"currency":"SPI","available":"0","reserved":"0"}, #         {"currency":"GRPH","available":"0","reserved":"0"}, #         {"currency":"DGTX","available":"0","reserved":"0"}, #     ] # # #     { #         "timestamp":"2015-08-20T19:01:00.000Z", #         "open":"0.006", #         "close":"0.006", #         "min":"0.006", #         "max":"0.006", #         "volume":"0.003", #         "volumeQuote":"0.000018" #     } # # #     [ #         {"timestamp":"2015-08-20T19:01:00.000Z","open":"0.006","close":"0.006","min":"0.006","max":"0.006","volume":"0.003","volumeQuote":"0.000018"}, #         {"timestamp":"2015-08-20T19:03:00.000Z","open":"0.006","close":"0.006","min":"0.006","max":"0.006","volume":"0.013","volumeQuote":"0.000078"}, #         {"timestamp":"2015-08-20T19:06:00.000Z","open":"0.0055","close":"0.005","min":"0.005","max":"0.0055","volume":"0.003","volumeQuote":"0.0000155"}, #     ] # # default = 100, 0 = unlimited # createMarketOrder # #  {      fee: "0.0004644", #           id:  386394956, #        price: "0.4644", #     quantity: "1", #    timestamp: "2018-10-25T16:41:44.780Z"} # # fetchTrades # # {id: 974786185, #   price: '0.032462', #   quantity: '0.3673', #   side: 'buy', #   timestamp: '2020-10-16T12:57:39.846Z'} # # fetchMyTrades # # {id: 277210397, #   clientOrderId: '6e102f3e7f3f4e04aeeb1cdc95592f1a', #   orderId: 28102855393, #   symbol: 'ETHBTC', #   side: 'sell', #   quantity: '0.002', #   price: '0.073365', #   fee: '0.000000147', #   timestamp: '2018-04-28T18:39:55.345Z'} # #  { #      "id":1568938909, #      "orderId":793293348428, #      "clientOrderId":"fbc5c5b753e8476cb14697458cb928ef", #      "symbol":"DOGEUSD", #      "side":"sell", #      "quantity":"100", #      "price":"0.03904191", #      "fee":"0.009760477500", #      "timestamp":"2022-01-25T15:15:41.353Z", #      "taker":true #  } # # we use clientOrderId as the order id with self exchange intentionally # because most of their endpoints will require clientOrderId # explained here: https://github.com/ccxt/ccxt/issues/5674 # # transactions # #     { #         id: '<PASSWORD>', #         index: 1044718371, #         type: 'payout',  # payout, payin #         status: 'success', #         currency: 'ETH', #         amount: '4.522683200000000000000000', #         createdAt: '2018-06-07T00:43:32.426Z', #         updatedAt: '2018-06-07T00:45:36.447Z', #         hash: '0x973e5683dfdf80a1fb1e0b96e19085b6489221d2ddf864daa46903c5ec283a0f', #         address: '0xC5a59b21948C1d230c8C54f05590000Eb3e1252c', #         fee: '0.00958', #     }, #     { #         id: '<PASSWORD>', #         index: 1044714672, #         type: 'exchangeToBank',  # exchangeToBank, bankToExchange, withdraw #         status: 'success', #         currency: 'ETH', #         amount: '4.532263200000000000', #         createdAt: '2018-06-07T00:42:39.543Z', #         updatedAt: '2018-06-07T00:42:39.683Z', #     }, # # withdraw # #     { #         "id": "d2ce578f-647d-4fa0-b1aa-4a27e5ee597b" #     } # # we use clientOrderId as the order id with self exchange intentionally # because most of their endpoints will require clientOrderId # explained here: https://github.com/ccxt/ccxt/issues/5674 # their max accepted length is 32 characters # we use clientOrderId as the order id with self exchange intentionally # because most of their endpoints will require clientOrderId # explained here: https://github.com/ccxt/ccxt/issues/5674 # their max accepted length is 32 characters # we use clientOrderId as the order id with self exchange intentionally # because most of their endpoints will require clientOrderId # explained here: https://github.com/ccxt/ccxt/issues/5674 # # createMarketOrder # #     { #         clientOrderId: "fe36aa5e190149bf9985fb673bbb2ea0", #         createdAt: "2018-10-25T16:41:44.780Z", #         cumQuantity: "1", #         id: "66799540063", #         quantity: "1", #         side: "sell", #         status: "filled", #         symbol: "XRPUSDT", #         timeInForce: "FOK", #         tradesReport: [ #             { #                 fee: "0.0004644", #                 id:  386394956, #                 price: "0.4644", #                 quantity: "1", #                 timestamp: "2018-10-25T16:41:44.780Z" #             } #         ], #         type: "market", #         updatedAt: "2018-10-25T16:41:44.780Z" #     } # #     { #         "id": 119499457455, #         "clientOrderId": "87baab109d58401b9202fa0749cb8288", #         "symbol": "ETHUSD", #         "side": "buy", #         "status": "filled", #         "type": "market", #         "timeInForce": "FOK", #         "quantity": "0.0007", #         "price": "181.487", #         "avgPrice": "164.989", #         "cumQuantity": "0.0007", #         "createdAt": "2019-04-17T13:27:38.062Z", #         "updatedAt": "2019-04-17T13:27:38.062Z" #     } # # we use clientOrderId as the order id with self exchange intentionally # because most of their endpoints will require clientOrderId # explained here: https://github.com/ccxt/ccxt/issues/5674 # https://github.com/ccxt/ccxt/issues/5674 # we use clientOrderId as the order id with self exchange intentionally # because most of their endpoints will require clientOrderId # explained here: https://github.com/ccxt/ccxt/issues/5674 # we use clientOrderId as the order id with self exchange intentionally # because most of their endpoints will require clientOrderId # explained here: https://github.com/ccxt/ccxt/issues/5674 # 'symbol': 'BTC/USD',  # optional # 'sort':   'DESC',  # or 'ASC' # 'by':     'timestamp',  # or 'id' String timestamp by default, or id # 'from':   'Datetime or Number',  # ISO 8601 # 'till':   'Datetime or Number', # 'limit':  100, # 'offset': 0, # #     [ #         { #             "id": 9535486, #             "clientOrderId": "f8dbaab336d44d5ba3ff578098a68454", #             "orderId": 816088377, #             "symbol": "ETHBTC", #             "side": "sell", #             "quantity": "0.061", #             "price": "0.045487", #             "fee": "0.000002775", #             "timestamp": "2017-05-17T12:32:57.848Z" #         }, #         { #             "id": 9535437, #             "clientOrderId": "27b9bfc068b44194b1f453c7af511ed6", #             "orderId": 816088021, #             "symbol": "ETHBTC", #             "side": "buy", #             "quantity": "0.038", #             "price": "0.046000", #             "fee": "-0.000000174", #             "timestamp": "2017-05-17T12:30:57.848Z" #         } #     ] # # The id needed here is the exchange's id, and not the clientOrderID, # which is the id that is stored in the unified order id # To get the exchange's id you need to grab it from order['info']['id'] # handle ETH>ERC20 alias # handle ETH>ERC20 alias # self line allows the user to specify either ERC20 or ETH # handle ERC20>ETH alias # when network the currency need to be changed to currency + network # #     { #         "id": "d2ce578f-647d-4fa0-b1aa-4a27e5ee597b" #     } # # {"code":504,"message":"Gateway Timeout","description":""} # fallback to default error handler on rate limit errors # {"code":429,"message":"Too many requests","description":"Too many requests"} # {"error":{"code":20002,"message":"Order not found","description":""}}