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

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

from ccxt.base.exchange import Exchange
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import BadResponse
from ccxt.base.errors import DDoSProtection
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class bytetrade(Exchange):

    def describe(self):
        return self.deep_extend(super(bytetrade, self).describe(), {
            'id': 'bytetrade',
            'name': 'ByteTrade',
            'countries': ['HK'],
            # 10 requests per second =>( 1000ms / 10 ) = 100
            'rateLimit': 100,
            'requiresWeb3': True,
            'certified': False,
            # new metainfo interface
            'has': {
                'CORS': None,
                'spot': True,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'addMargin': False,
                'cancelOrder': True,
                'createOrder': True,
                'createReduceOnlyOrder': False,
                'createStopLimitOrder': False,
                'createStopMarketOrder': False,
                'createStopOrder': False,
                'fetchBalance': True,
                'fetchBidsAsks': True,
                'fetchBorrowRate': False,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchBorrowRates': False,
                'fetchBorrowRatesPerSymbol': False,
                'fetchClosedOrders': True,
                'fetchCurrencies': True,
                'fetchDepositAddress': True,
                'fetchDeposits': True,
                'fetchFundingHistory': False,
                'fetchFundingRate': False,
                'fetchFundingRateHistory': False,
                'fetchFundingRates': False,
                'fetchIndexOHLCV': False,
                'fetchLeverage': False,
                'fetchLeverageTiers': False,
                'fetchMarginMode': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenInterestHistory': False,
                'fetchOpenOrders': True,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrders': True,
                'fetchPosition': False,
                'fetchPositionMode': False,
                'fetchPositions': False,
                'fetchPositionsRisk': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTrades': True,
                'fetchTradingFee': False,
                'fetchTradingFees': True,
                'fetchWithdrawals': True,
                'reduceMargin': False,
                'setLeverage': False,
                'setMarginMode': False,
                'setPositionMode': False,
                'withdraw': None,
            },
            'timeframes': {
                '1m': '1m',
                '5m': '5m',
                '15m': '15m',
                '30m': '30m',
                '1h': '1h',
                '4h': '4h',
                '1d': '1d',
                '5d': '5d',
                '1w': '1w',
                '1M': '1M',
            },
            'urls': {
                'test': {
                    'market': 'https://api-v2-test.byte-trade.com',
                    'public': 'https://api-v2-test.byte-trade.com',
                },
                'logo': 'https://user-images.githubusercontent.com/1294454/67288762-2f04a600-f4e6-11e9-9fd6-c60641919491.jpg',
                'api': {
                    'market': 'https://api-v2.bttcdn.com',
                    'public': 'https://api-v2.bttcdn.com',
                },
                'www': 'https://www.byte-trade.com',
                'doc': 'https://docs.byte-trade.com/#description',
            },
            'api': {
                'market': {
                    'get': {
                        'klines': 1,        # Kline of a symbol
                        'depth': 1,         # Market Depth of a symbol
                        'trades': 1,        # Trade records of a symbol
                        'tickers': 1,
                    },
                },
                'public': {
                    'get': {
                        'symbols': 1,        # Reference information of trading instrument, including base currency, quote precision, etc.
                        'currencies': 1,     # The list of currencies available
                        'balance': 1,        # Get the balance of an account
                        'orders/open': 1,    # Get the open orders of an account
                        'orders/closed': 1,  # Get the closed orders of an account
                        'orders/all': 1,     # Get the open and closed orders of an account
                        'orders': 1,         # Get the details of an order of an account
                        'orders/trades': 1,  # Get detail match results
                        'depositaddress': 1,  # Get deposit address
                        'withdrawals': 1,    # Get withdrawals info
                        'deposits': 1,       # Get deposit info
                        'transfers': 1,      # Get transfer info
                    },
                    'post': {
                        'transaction/createorder': 1,    # Post create order transaction to blockchain
                        'transaction/cancelorder': 1,    # Post cancel order transaction to blockchain
                        'transaction/withdraw': 1,       # Post withdraw transaction to blockchain
                        'transaction/transfer': 1,       # Post transfer transaction to blockchain
                    },
                },
            },
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'taker': 0.0008,
                    'maker': 0.0008,
                },
            },
            'commonCurrencies': {
                '1': 'ByteTrade',
                '44': 'ByteHub',
                '48': 'Blocktonic',
                '133': 'TerraCredit',
            },
            'precisionMode': TICK_SIZE,
            'exceptions': {
                'vertify error': AuthenticationError,  # typo on the exchange side, 'vertify'
                'verify error': AuthenticationError,  # private key signature is incorrect
                'transaction already in network': BadRequest,  # same transaction submited
                'invalid argument': BadRequest,
            },
            'options': {
                'orderExpiration': 31536000000,  # one year
            },
        })

    def fetch_currencies(self, params={}):
        """
        fetches all available currencies on an exchange
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns dict: an associative dictionary of currencies
        """
        currencies = self.publicGetCurrencies(params)
        result = {}
        for i in range(0, len(currencies)):
            currency = currencies[i]
            id = self.safe_string(currency, 'code')
            code = None
            if id in self.commonCurrencies:
                code = self.commonCurrencies[id]
            else:
                code = self.safe_string(currency, 'name')
            name = self.safe_string(currency, 'fullname')
            # in byte-trade.com DEX, request https://api-v2.byte-trade.com/currencies will return currencies,
            # the api doc is https://github.com/Bytetrade/bytetrade-official-api-docs/wiki/rest-api#get-currencies-get-currencys-supported-in-bytetradecom
            # we can see the coin name is none-unique in the result, the coin which code is 18 is the CyberMiles ERC20, and the coin which code is 35 is the CyberMiles main chain, but their name is same.
            # that is because bytetrade is a DEX, supports people create coin with the same name, but the id(code) of coin is unique, so we should use the id or name and id as the identity of coin.
            # For coin name and symbol is same with CCXT, I use name@id as the key of commonCurrencies dict.
            # [{
            #     "name": "CMT",      # currency name, non-unique
            #     "code": "18",       # currency id, unique
            #     "type": "crypto",
            #     "fullname": "CyberMiles",
            #     "active": True,
            #     "chainType": "ethereum",
            #     "basePrecision": 18,
            #     "transferPrecision": 10,
            #     "externalPrecision": 18,
            #     "chainContractAddress": "0xf85feea2fdd81d51177f6b8f35f0e6734ce45f5f",
            #     "limits": {
            #       "deposit": {
            #         "min": "0",
            #         "max": "-1"
            #       },
            #       "withdraw": {
            #         "min": "0",
            #         "max": "-1"
            #       }
            #     }
            #   },
            #   {
            #     "name": "CMT",
            #     "code": "35",
            #     "type": "crypto",
            #     "fullname": "CyberMiles",
            #     "active": True,
            #     "chainType": "cmt",
            #     "basePrecision": 18,
            #     "transferPrecision": 10,
            #     "externalPrecision": 18,
            #     "chainContractAddress": "0x0000000000000000000000000000000000000000",
            #     "limits": {
            #       "deposit": {
            #         "min": "1",
            #         "max": "-1"
            #       },
            #       "withdraw": {
            #         "min": "10",
            #         "max": "-1"
            #       }
            #     }
            #   }
            #   ]
            active = self.safe_value(currency, 'active')
            limits = self.safe_value(currency, 'limits')
            deposit = self.safe_value(limits, 'deposit')
            maxDeposit = self.safe_string(deposit, 'max')
            if Precise.string_equals(maxDeposit, '-1'):
                maxDeposit = None
            withdraw = self.safe_value(limits, 'withdraw')
            maxWithdraw = self.safe_string(withdraw, 'max')
            if Precise.string_equals(maxWithdraw, '-1'):
                maxWithdraw = None
            result[code] = {
                'id': id,
                'code': code,
                'name': name,
                'active': active,
                'deposit': None,
                'withdraw': None,
                'precision': self.parse_number(self.parse_precision(self.safe_string(currency, 'basePrecision'))),
                'fee': None,
                'limits': {
                    'amount': {'min': None, 'max': None},
                    'deposit': {
                        'min': self.safe_number(deposit, 'min'),
                        'max': self.parse_number(maxDeposit),
                    },
                    'withdraw': {
                        'min': self.safe_number(withdraw, 'min'),
                        'max': self.parse_number(maxWithdraw),
                    },
                },
                'info': currency,
            }
        return result

    def fetch_markets(self, params={}):
        """
        retrieves data on all markets for bytetrade
        :param dict params: extra parameters specific to the exchange api endpoint
        :returns [dict]: an array of objects representing market data
        """
        markets = self.publicGetSymbols(params)
        #
        #     [
        #         {
        #             "symbol": "122406567911",
        #             "name": "BTC/USDT",
        #             "base": "32",
        #             "quote": "57",
        #             "marketStatus": 0,
        #             "baseName": "BTC",
        #             "quoteName": "USDT",
        #             "active": True,
        #             "maker": "0.0008",
        #             "taker": "0.0008",
        #             "precision": {
        #                 "amount": 6,
        #                 "price": 2,
        #                 "minPrice":1
        #             },
        #             "limits": {
        #                 "amount": {
        #                     "min": "0.000001",
        #                     "max": "-1"
        #                 },
        #                 "price": {
        #                     "min": "0.01",
        #                     "max": "-1"
        #                 }
        #             }
        #        }
        #    ]
        #
        result = []
        for i in range(0, len(markets)):
            market = markets[i]
            id = self.safe_string(market, 'symbol')
            base = self.safe_string(market, 'baseName', '')
            quote = self.safe_string(market, 'quoteName', '')
            baseId = self.safe_string(market, 'base')
            quoteId = self.safe_string(market, 'quote')
            normalBase = base.split('@' + baseId)[0]
            normalQuote = quote.split('@' + quoteId)[0]
            if quoteId == '126':
                normalQuote = 'ZAR'  # The id 126 coin is a special coin whose name on the chain is actually ZAR, but it is changed to ZCN after creation, so it must be changed to ZAR when placing the transaction in the chain
            normalSymbol = normalBase + '/' + normalQuote
            if baseId in self.commonCurrencies:
                base = self.commonCurrencies[baseId]
            if quoteId in self.commonCurrencies:
                quote = self.commonCurrencies[quoteId]
            limits = self.safe_value(market, 'limits', {})
            amount = self.safe_value(limits, 'amount', {})
            price = self.safe_value(limits, 'price', {})
            precision = self.safe_value(market, 'precision', {})
            maxAmount = self.safe_string(amount, 'max')
            if Precise.string_equals(maxAmount, '-1'):
                maxAmount = None
            maxPrice = self.safe_string(price, 'max')
            if Precise.string_equals(maxPrice, '-1'):
                maxPrice = None
            entry = {
                'id': id,
                'symbol': base + '/' + quote,
                'normalSymbol': normalSymbol,
                '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': self.safe_value(market, 'active'),
                'contract': False,
                'linear': None,
                'inverse': None,
                'taker': self.safe_number(market, 'taker'),
                'maker': self.safe_number(market, 'maker'),
                'contractSize': None,
                'expiry': None,
                'expiryDatetime': None,
                'strike': None,
                'optionType': None,
                'precision': {
                    'amount': self.parse_number(self.parse_precision(self.safe_string(precision, 'amount'))),
                    'price': self.parse_number(self.parse_precision(self.safe_string(precision, 'price'))),
                },
                'limits': {
                    'leverage': {
                        'min': None,
                        'max': None,
                    },
                    'amount': {
                        'min': self.safe_number(amount, 'min'),
                        'max': self.parse_number(maxAmount),
                    },
                    'price': {
                        'min': self.safe_number(price, 'min'),
                        'max': self.parse_number(maxPrice),
                    },
                    'cost': {
                        'min': None,
                        'max': None,
                    },
                },
                'info': market,
            }
            result.append(entry)
        return result

    def parse_balance(self, response):
        result = {'info': response}
        for i in range(0, len(response)):
            balance = response[i]
            currencyId = self.safe_string(balance, 'code')
            code = self.safe_currency_code(currencyId, None)
            account = self.account()
            account['free'] = self.safe_string(balance, 'free')
            account['used'] = self.safe_string(balance, 'used')
            result[code] = account
        return self.safe_balance(result)

    def fetch_balance(self, params={}):
        """
        query for balance and get the amount of funds available for trading or funds locked in orders
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>`
        """
        if not ('userid' in params) and (self.apiKey is None):
            raise ArgumentsRequired(self.id + ' fetchBalance() requires self.apiKey or userid argument')
        self.load_markets()
        request = {
            'userid': self.apiKey,
        }
        response = self.publicGetBalance(self.extend(request, params))
        return self.parse_balance(response)

    def fetch_order_book(self, symbol, limit=None, params={}):
        """
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str symbol: unified symbol of the market to fetch the order book for
        :param int|None limit: the maximum amount of order book entries to return
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbols
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit  # default = maximum = 100
        response = self.marketGetDepth(self.extend(request, params))
        timestamp = self.safe_integer(response, 'timestamp')
        orderbook = self.parse_order_book(response, market['symbol'], timestamp)
        return orderbook

    def parse_ticker(self, ticker, market=None):
        timestamp = self.safe_integer(ticker, 'timestamp')
        #
        #     [
        #         {
        #             "symbol":"68719476706",
        #             "name":"ETH/BTC",
        #             "base":"2",
        #             "quote":"32",
        #             "timestamp":1575905991933,
        #             "datetime":"2019-12-09T15:39:51.933Z",
        #             "high":"0",
        #             "low":"0",
        #             "open":"0",
        #             "close":"0",
        #             "last":"0",
        #             "change":"0",
        #             "percentage":"0",
        #             "baseVolume":"0",
        #             "quoteVolume":"0"
        #         }
        #     ]
        #
        marketId = self.safe_string(ticker, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        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': None,
            'bidVolume': None,
            'ask': None,
            'askVolume': None,
            'vwap': self.safe_string(ticker, 'weightedAvgPrice'),
            'open': self.safe_string(ticker, 'open'),
            'close': self.safe_string(ticker, 'close'),
            'last': self.safe_string(ticker, 'last'),
            'previousClose': None,  # previous day close
            'change': self.safe_string(ticker, 'change'),
            'percentage': self.safe_string(ticker, 'percentage'),
            'average': None,
            'baseVolume': self.safe_string(ticker, 'baseVolume'),
            'quoteVolume': self.safe_string(ticker, 'quoteVolume'),
            'info': ticker,
        }, market)

    def fetch_ticker(self, symbol, params={}):
        """
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = self.marketGetTickers(self.extend(request, params))
        #
        #     [
        #         {
        #             "symbol":"68719476706",
        #             "name":"ETH/BTC",
        #             "base":"2",
        #             "quote":"32",
        #             "timestamp":1575905991933,
        #             "datetime":"2019-12-09T15:39:51.933Z",
        #             "high":"0",
        #             "low":"0",
        #             "open":"0",
        #             "close":"0",
        #             "last":"0",
        #             "change":"0",
        #             "percentage":"0",
        #             "baseVolume":"0",
        #             "quoteVolume":"0"
        #         }
        #     ]
        #
        if isinstance(response, list):
            ticker = self.safe_value(response, 0)
            if ticker is None:
                raise BadResponse(self.id + ' fetchTicker() returned an empty response')
            return self.parse_ticker(ticker, market)
        return self.parse_ticker(response, market)

    def fetch_bids_asks(self, symbols=None, params={}):
        """
        fetches the bid and ask price and volume for multiple markets
        :param [str]|None symbols: unified symbols of the markets to fetch the bids and asks for, all markets are returned if not assigned
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns dict: an array of `ticker structures <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        self.load_markets()
        response = self.marketGetDepth(params)
        return self.parse_tickers(response, symbols)

    def fetch_tickers(self, symbols=None, params={}):
        """
        fetches price tickers for multiple markets, statistical calculations with the information calculated over the past 24 hours each market
        :param [str]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns dict: an array of `ticker structures <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        self.load_markets()
        response = self.marketGetTickers(params)
        return self.parse_tickers(response, symbols)

    def parse_ohlcv(self, ohlcv, market=None):
        #
        #     [
        #         1591505760000,
        #         "242.7",
        #         "242.76",
        #         "242.69",
        #         "242.76",
        #         "0.1892"
        #     ]
        #
        return [
            self.safe_integer(ohlcv, 0),
            self.safe_number(ohlcv, 1),
            self.safe_number(ohlcv, 2),
            self.safe_number(ohlcv, 3),
            self.safe_number(ohlcv, 4),
            self.safe_number(ohlcv, 5),
        ]

    def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
        """
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int|None since: timestamp in ms of the earliest candle to fetch
        :param int|None limit: the maximum amount of candles to fetch
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            'timeframe': self.timeframes[timeframe],
        }
        if since is not None:
            request['since'] = since
        if limit is not None:
            request['limit'] = limit
        response = self.marketGetKlines(self.extend(request, params))
        #
        #     [
        #         [1591505760000,"242.7","242.76","242.69","242.76","0.1892"],
        #         [1591505820000,"242.77","242.83","242.7","242.72","0.6378"],
        #         [1591505880000,"242.72","242.73","242.61","242.72","0.4141"],
        #     ]
        #
        return self.parse_ohlcvs(response, market, timeframe, since, limit)

    def parse_trade(self, trade, market=None):
        #
        # public trades
        #  {
        #      "id":"d38a5bc4b651106f9d6abf9ced671961909be215",
        #      "timestamp":1642522255864,
        #      "symbol":"122406567940",
        #      "side":"sell",
        #      "price":"0.12",
        #      "amount":"0.5747"
        #  }
        #
        # private trades
        #  {
        #      "id":"905b6ff62b6c90eb5b8c0f7ad0f6bccf018d15e4",
        #      "timestamp":1642525375299,
        #      "datetime":"2022-01-18T17:02:55.299Z",
        #      "symbol":"122406567940",
        #      "userid":"slimmjimm@gmail.com",
        #      "otherUserid":"nakamoto@gmail.com",
        #      "takerOrMaker":"maker",
        #      "side":"sell",
        #      "txid":"036a89648352732f26a2b6680331dd7887a5c800",
        #      "type":"market",
        #      "order":"84749f1ca91541d97e400f628d5bb7b1e418a738",
        #      "fee": {
        #          "cost":"0.000611176192",
        #          "rate":"0.0008",
        #          "code":57,"name":"USDT"
        #          },
        #      "cost":"0.76397024",
        #      "price":"0.01216",
        #      "amount":"62.8265",
        #      "average":"0.01216",
        #      "name":"DOGE/USDT"
        #  }
        #
        timestamp = self.safe_integer(trade, 'timestamp')
        priceString = self.safe_string(trade, 'price')
        amountString = self.safe_string(trade, 'amount')
        costString = self.safe_string(trade, 'cost')
        id = self.safe_string(trade, 'id')
        type = self.safe_string(trade, 'type')
        takerOrMaker = self.safe_string(trade, 'takerOrMaker')
        side = self.safe_string(trade, 'side')
        datetime = self.iso8601(timestamp)  # self.safe_string(trade, 'datetime')
        order = self.safe_string(trade, 'order')
        marketId = self.safe_string(trade, 'symbol')
        market = self.safe_market(marketId, market)
        feeData = self.safe_value(trade, 'fee')
        feeCostString = self.safe_string(feeData, 'cost')
        feeRateString = self.safe_string(feeData, 'rate')
        feeCode = self.safe_string(feeData, 'code')
        feeCurrency = self.safe_currency_code(feeCode)
        fee = {
            'currency': feeCurrency,
            'cost': feeCostString,
            'rate': feeRateString,
        }
        return self.safe_trade({
            'info': trade,
            'timestamp': timestamp,
            'datetime': datetime,
            'symbol': market['symbol'],
            'id': id,
            'order': order,
            'type': type,
            'takerOrMaker': takerOrMaker,
            'side': side,
            'price': priceString,
            'amount': amountString,
            'cost': costString,
            'fee': fee,
        }, market)

    def fetch_trades(self, symbol, since=None, limit=None, params={}):
        """
        get the list of most recent trades for a particular symbol
        :param str symbol: unified symbol of the market to fetch trades for
        :param int|None since: timestamp in ms of the earliest trade to fetch
        :param int|None limit: the maximum amount of trades to fetch
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html?#public-trades>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if since is not None:
            request['since'] = since
        if limit is not None:
            request['limit'] = limit  # default = 100, maximum = 500
        response = self.marketGetTrades(self.extend(request, params))
        return self.parse_trades(response, market, since, limit)

    def fetch_trading_fees(self, params={}):
        """
        fetch the trading fees for multiple markets
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/en/latest/manual.html#fee-structure>` indexed by market symbols
        """
        self.load_markets()
        response = self.publicGetSymbols(params)
        #
        #     [
        #         {
        #             "symbol": "122406567911",
        #             "name": "BTC/USDT",
        #             "base": "32",
        #             "quote": "57",
        #             "marketStatus": 0,
        #             "baseName": "BTC",
        #             "quoteName": "USDT",
        #             "active": True,
        #             "maker": "0.0008",
        #             "taker": "0.0008",
        #             "precision": {
        #                 "amount": 6,
        #                 "price": 2,
        #                 "minPrice":1
        #             },
        #             "limits": {
        #                 "amount": {
        #                     "min": "0.000001",
        #                     "max": "-1"
        #                 },
        #                 "price": {
        #                     "min": "0.01",
        #                     "max": "-1"
        #                 }
        #             }
        #        }
        #        ...
        #    ]
        #
        result = {}
        for i in range(0, len(response)):
            symbolInfo = response[i]
            marketId = self.safe_string(symbolInfo, 'name')
            symbol = self.safe_symbol(marketId)
            result[symbol] = {
                'info': symbolInfo,
                'symbol': symbol,
                'maker': self.safe_number(symbolInfo, 'maker'),
                'taker': self.safe_number(symbolInfo, 'taker'),
                'percentage': True,
            }
        return result

    def parse_order(self, order, market=None):
        status = self.safe_string(order, 'status')
        baseId = self.safe_string(order, 'base')
        quoteId = self.safe_string(order, 'quote')
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        symbol = base + '/' + quote
        timestamp = self.safe_integer(order, 'timestamp')
        datetime = self.safe_string(order, 'datetime')
        lastTradeTimestamp = self.safe_integer(order, 'lastTradeTimestamp')
        price = self.safe_string(order, 'price')
        amount = self.safe_string(order, 'amount')
        filled = self.safe_string(order, 'filled')
        remaining = self.safe_string(order, 'remaining')
        cost = self.safe_string(order, 'cost')
        average = self.safe_string(order, 'average')
        id = self.safe_string(order, 'id')
        type = self.safe_string(order, 'type')
        side = self.safe_string(order, 'side')
        feeData = self.safe_value(order, 'fee')
        feeCost = self.safe_number(feeData, 'cost')
        feeRate = self.safe_number(feeData, 'rate')
        feeCode = self.safe_string(feeData, 'code')
        feeCurrency = self.safe_currency_code(feeCode)
        fee = {
            'currency': feeCurrency,
            'cost': feeCost,
            'rate': feeRate,
        }
        return self.safe_order({
            'info': order,
            'id': id,
            'clientOrderId': None,
            'timestamp': timestamp,
            'datetime': datetime,
            'lastTradeTimestamp': lastTradeTimestamp,
            'symbol': symbol,
            'type': type,
            'timeInForce': None,
            'postOnly': None,
            'side': side,
            'price': price,
            'stopPrice': None,
            'amount': amount,
            'cost': cost,
            'average': average,
            'filled': filled,
            'remaining': remaining,
            'status': status,
            'fee': fee,
            'trades': None,
        }, market)

    def create_order(self, symbol, type, side, amount, price=None, params={}):
        """
        create a trade order
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float|None price: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.check_required_dependencies()
        if self.apiKey is None:
            raise ArgumentsRequired('createOrder() requires self.apiKey or userid in params')
        self.load_markets()
        market = self.market(symbol)
        sideNum = None
        typeNum = None
        if side == 'sell':
            sideNum = 1
        else:
            sideNum = 2
        if type == 'limit':
            typeNum = 1
        else:
            typeNum = 2
            price = 0
        normalSymbol = market['normalSymbol']
        baseId = market['baseId']
        baseCurrency = self.currency(market['base'])
        amountTruncated = self.amount_to_precision(symbol, amount)
        amountTruncatedPrecise = Precise(amountTruncated)
        amountTruncatedPrecise.reduce()
        amountTruncatedPrecise.decimals -= self.precision_from_string(self.number_to_string(baseCurrency['precision']))
        amountChain = str(amountTruncatedPrecise)
        amountChainString = self.number_to_string(amountChain)
        quoteId = market['quoteId']
        quoteCurrency = self.currency(market['quote'])
        priceRounded = self.price_to_precision(symbol, price)
        priceRoundedPrecise = Precise(priceRounded)
        priceRoundedPrecise.reduce()
        priceRoundedPrecise.decimals -= self.precision_from_string(self.number_to_string(quoteCurrency['precision']))
        priceChain = str(priceRoundedPrecise)
        priceChainString = self.number_to_string(priceChain)
        now = self.milliseconds()
        expiryDelta = self.safe_integer(self.options, 'orderExpiration', 31536000000)
        expiration = self.milliseconds() + expiryDelta
        datetime = self.iso8601(now)
        datetime = datetime.split('.')[0]
        expirationDatetime = self.iso8601(expiration)
        expirationDatetime = expirationDatetime.split('.')[0]
        defaultDappId = 'Sagittarius'
        dappId = self.safe_string(params, 'dappId', defaultDappId)
        defaultFee = self.safe_string(self.options, 'fee', '300000000000000')
        totalFeeRate = self.safe_string(params, 'totalFeeRate', '8')
        chainFeeRate = self.safe_string(params, 'chainFeeRate', '1')
        fee = self.safe_string(params, 'fee', defaultFee)
        eightBytes = '18446744073709551616'  # 2 ** 64
        allByteStringArray = [
            self.number_to_be(1, 32),
            self.number_to_le(int(math.floor(now / 1000)), 4),
            self.number_to_le(1, 1),
            self.number_to_le(int(math.floor(expiration / 1000)), 4),
            self.number_to_le(1, 1),
            self.number_to_le(32, 1),
            self.number_to_le(0, 8),
            self.number_to_le(fee, 8),  # string for 32 bit php
            self.number_to_le(len(self.apiKey), 1),
            self.encode(self.apiKey),
            self.number_to_le(sideNum, 1),
            self.number_to_le(typeNum, 1),
            self.number_to_le(len(normalSymbol), 1),
            self.encode(normalSymbol),
            self.number_to_le(Precise.string_div(amountChainString, eightBytes, 0), 8),
            self.number_to_le(Precise.string_mod(amountChainString, eightBytes), 8),
            self.number_to_le(Precise.string_div(priceChainString, eightBytes, 0), 8),
            self.number_to_le(Precise.string_mod(priceChainString, eightBytes), 8),
            self.number_to_le(0, 2),
            self.number_to_le(int(math.floor(now / 1000)), 4),
            self.number_to_le(int(math.floor(expiration / 1000)), 4),
            self.number_to_le(1, 1),
            self.number_to_le(int(chainFeeRate), 2),
            self.number_to_le(1, 1),
            self.number_to_le(int(totalFeeRate), 2),
            self.number_to_le(int(quoteId), 4),
            self.number_to_le(int(baseId), 4),
            self.number_to_le(0, 1),
            self.number_to_le(1, 1),
            self.number_to_le(len(dappId), 1),
            self.encode(dappId),
            self.number_to_le(0, 1),
        ]
        txByteStringArray = [
            self.number_to_le(int(math.floor(now / 1000)), 4),
            self.number_to_le(1, 1),
            self.number_to_le(int(math.floor(expiration / 1000)), 4),
            self.number_to_le(1, 1),
            self.number_to_le(32, 1),
            self.number_to_le(0, 8),
            self.number_to_le(fee, 8),  # string for 32 bit php
            self.number_to_le(len(self.apiKey), 1),
            self.encode(self.apiKey),
            self.number_to_le(sideNum, 1),
            self.number_to_le(typeNum, 1),
            self.number_to_le(len(normalSymbol), 1),
            self.encode(normalSymbol),
            self.number_to_le(Precise.string_div(amountChainString, eightBytes, 0), 8),
            self.number_to_le(Precise.string_mod(amountChainString, eightBytes), 8),
            self.number_to_le(Precise.string_div(priceChainString, eightBytes, 0), 8),
            self.number_to_le(Precise.string_mod(priceChainString, eightBytes), 8),
            self.number_to_le(0, 2),
            self.number_to_le(int(math.floor(now / 1000)), 4),
            self.number_to_le(int(math.floor(expiration / 1000)), 4),
            self.number_to_le(1, 1),
            self.number_to_le(int(chainFeeRate), 2),
            self.number_to_le(1, 1),
            self.number_to_le(int(totalFeeRate), 2),
            self.number_to_le(int(quoteId), 4),
            self.number_to_le(int(baseId), 4),
            self.number_to_le(0, 1),
            self.number_to_le(1, 1),
            self.number_to_le(len(dappId), 1),
            self.encode(dappId),
            self.number_to_le(0, 1),
        ]
        txbytestring = self.binary_concat_array(txByteStringArray)
        txidhash = self.hash(txbytestring, 'sha256', 'hex')
        txid = txidhash[0:40]
        orderidByteStringArray = [
            self.number_to_le(len(txid), 1),
            self.encode(txid),
            self.number_to_be(0, 4),
        ]
        orderidbytestring = self.binary_concat_array(orderidByteStringArray)
        orderidhash = self.hash(orderidbytestring, 'sha256', 'hex')
        orderid = orderidhash[0:40]
        bytestring = self.binary_concat_array(allByteStringArray)
        hash = self.hash(bytestring, 'sha256', 'hex')
        signature = self.ecdsa(hash, self.secret, 'secp256k1', None, True)
        recoveryParam = self.binary_to_base16(self.number_to_le(self.sum(signature['v'], 31), 1))
        mySignature = recoveryParam + signature['r'] + signature['s']
        operation = {
            'now': datetime,
            'expiration': expirationDatetime,
            'fee': fee,
            'creator': self.apiKey,
            'side': sideNum,
            'order_type': typeNum,
            'market_name': normalSymbol,
            'amount': amountChain,
            'price': priceChain,
            'use_btt_as_fee': False,
            'money_id': int(quoteId),
            'stock_id': int(baseId),
            'custom_no_btt_fee_rate': int(totalFeeRate),
            'custom_btt_fee_rate': int(chainFeeRate),
        }
        fatty = {
            'timestamp': datetime,
            'expiration': expirationDatetime,
            'operations': [
                [
                    32,
                    operation,
                ],
            ],
            'validate_type': 0,
            'dapp': dappId,
            'signatures': [
                mySignature,
            ],
        }
        request = {
            'trObj': self.json(fatty),
        }
        response = self.publicPostTransactionCreateorder(request)
        timestamp = self.milliseconds()
        statusCode = self.safe_string(response, 'code')
        status = 'open' if (statusCode == '0') else 'failed'
        return {
            'info': response,
            'id': orderid,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'status': status,
            'symbol': None,
            'type': None,
            'side': None,
            'price': None,
            'amount': None,
            'filled': None,
            'remaining': None,
            'cost': None,
            'trades': None,
            'fee': None,
            'clientOrderId': None,
            'average': None,
        }

    def fetch_order(self, id, symbol=None, params={}):
        """
        fetches information on an order made by the user
        :param str|None symbol: unified symbol of the market the order was made in
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        if not ('userid' in params) and (self.apiKey is None):
            raise ArgumentsRequired('fetchOrder() requires self.apiKey or userid argument')
        self.load_markets()
        request = {
            'userid': self.apiKey,
        }
        market = None
        if symbol is not None:
            market = self.markets[symbol]
            request['symbol'] = market['id']
        request['id'] = id
        response = self.publicGetOrders(self.extend(request, params))
        return self.parse_order(response, market)

    def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetch all unfilled currently open orders
        :param str|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch open orders for
        :param int|None limit: the maximum number of  open orders structures to retrieve
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        if not ('userid' in params) and (self.apiKey is None):
            raise ArgumentsRequired('fetchOpenOrders() requires self.apiKey or userid argument')
        self.load_markets()
        request = {
            'userid': self.apiKey,
        }
        market = None
        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['since'] = since
        response = self.publicGetOrdersOpen(self.extend(request, params))
        return self.parse_orders(response, market, since, limit)

    def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches information on multiple closed orders made by the user
        :param str|None symbol: unified market symbol of the market orders were made in
        :param int|None since: the earliest time in ms to fetch orders for
        :param int|None limit: the maximum number of  orde structures to retrieve
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        if not ('userid' in params) and (self.apiKey is None):
            raise ArgumentsRequired('fetchClosedOrders() requires self.apiKey or userid argument')
        self.load_markets()
        market = None
        request = {
            'userid': self.apiKey,
        }
        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['since'] = since
        response = self.publicGetOrdersClosed(self.extend(request, params))
        return self.parse_orders(response, market, since, limit)

    def fetch_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches information on multiple orders made by the user
        :param str|None symbol: unified market symbol of the market orders were made in
        :param int|None since: the earliest time in ms to fetch orders for
        :param int|None limit: the maximum number of  orde structures to retrieve
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        if not ('userid' in params) and (self.apiKey is None):
            raise ArgumentsRequired('fetchOrders() requires self.apiKey or userid argument')
        self.load_markets()
        market = None
        request = {
            'userid': self.apiKey,
        }
        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['since'] = since
        response = self.publicGetOrdersAll(self.extend(request, params))
        return self.parse_orders(response, market, since, limit)

    def cancel_order(self, id, symbol=None, params={}):
        """
        cancels an open order
        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        if self.apiKey is None:
            raise ArgumentsRequired('cancelOrder() requires hasAlreadyAuthenticatedSuccessfully')
        if symbol is None:
            raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        baseId = market['baseId']
        quoteId = market['quoteId']
        normalSymbol = market['normalSymbol']
        feeAmount = '300000000000000'
        now = self.milliseconds()
        expiration = 0
        datetime = self.iso8601(now)
        datetime = datetime.split('.')[0]
        expirationDatetime = self.iso8601(expiration)
        expirationDatetime = expirationDatetime.split('.')[0]
        defaultDappId = 'Sagittarius'
        dappId = self.safe_string(params, 'dappId', defaultDappId)
        byteStringArray = [
            self.number_to_be(1, 32),
            self.number_to_le(int(math.floor(now / 1000)), 4),
            self.number_to_le(1, 1),
            self.number_to_le(expiration, 4),
            self.number_to_le(1, 1),
            self.number_to_le(33, 1),
            self.number_to_le(0, 8),
            self.number_to_le(feeAmount, 8),  # string for 32 bit php
            self.number_to_le(len(self.apiKey), 1),
            self.encode(self.apiKey),
            self.number_to_le(len(normalSymbol), 1),
            self.encode(normalSymbol),
            self.base16_to_binary(id),
            self.number_to_le(int(quoteId), 4),
            self.number_to_le(int(baseId), 4),
            self.number_to_le(0, 1),
            self.number_to_le(1, 1),
            self.number_to_le(len(dappId), 1),
            self.encode(dappId),
            self.number_to_le(0, 1),
        ]
        bytestring = self.binary_concat_array(byteStringArray)
        hash = self.hash(bytestring, 'sha256', 'hex')
        signature = self.ecdsa(hash, self.secret, 'secp256k1', None, True)
        recoveryParam = self.binary_to_base16(self.number_to_le(self.sum(signature['v'], 31), 1))
        mySignature = recoveryParam + signature['r'] + signature['s']
        operation = {
            'fee': feeAmount,
            'creator': self.apiKey,
            'order_id': id,
            'market_name': normalSymbol,
            'money_id': int(quoteId),
            'stock_id': int(baseId),
        }
        fatty = {
            'timestamp': datetime,
            'expiration': expirationDatetime,
            'operations': [
                [
                    33,
                    operation,
                ],
            ],
            'validate_type': 0,
            'dapp': dappId,
            'signatures': [
                mySignature,
            ],
        }
        request = {
            'trObj': self.json(fatty),
        }
        response = self.publicPostTransactionCancelorder(request)
        timestamp = self.milliseconds()
        statusCode = self.safe_string(response, 'code')
        status = 'canceled' if (statusCode == '0') else 'failed'
        return {
            'info': response,
            'id': None,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'status': status,
            'symbol': None,
            'type': None,
            'side': None,
            'price': None,
            'amount': None,
            'filled': None,
            'remaining': None,
            'cost': None,
            'trades': None,
            'fee': None,
            'clientOrderId': None,
            'average': None,
        }

    def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
        """
        fetch all trades made by the user
        :param str|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch trades for
        :param int|None limit: the maximum number of trades structures to retrieve
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
        """
        if not ('userid' in params) and (self.apiKey is None):
            raise ArgumentsRequired('fetchMyTrades() requires self.apiKey or userid argument')
        self.load_markets()
        market = self.market(symbol)
        request = {
            'userid': self.apiKey,
        }
        if symbol is not None:
            request['symbol'] = market['id']
        if limit is not None:
            request['limit'] = limit
        if since is not None:
            request['since'] = since
        response = self.publicGetOrdersTrades(self.extend(request, params))
        return self.parse_trades(response, market, since, limit)

    def fetch_deposits(self, code=None, since=None, limit=None, params={}):
        """
        fetch all deposits made to an account
        :param str|None code: unified currency code
        :param int|None since: the earliest time in ms to fetch deposits for
        :param int|None limit: the maximum number of deposits structures to retrieve
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        self.load_markets()
        if not ('userid' in params) and (self.apiKey is None):
            raise ArgumentsRequired('fetchDeposits() requires self.apiKey or userid argument')
        currency = None
        request = {
            'userid': self.apiKey,
        }
        if code is not None:
            currency = self.currency(code)
            request['currency'] = currency['id']
        if since is not None:
            request['since'] = since
        if limit is not None:
            request['limit'] = limit
        response = self.publicGetDeposits(self.extend(request, params))
        return self.parse_transactions(response, currency, since, limit)

    def fetch_withdrawals(self, code=None, since=None, limit=None, params={}):
        """
        fetch all withdrawals made from an account
        :param str|None code: unified currency code
        :param int|None since: the earliest time in ms to fetch withdrawals for
        :param int|None limit: the maximum number of withdrawals structures to retrieve
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        self.load_markets()
        if not ('userid' in params) and (self.apiKey is None):
            raise ArgumentsRequired('fetchWithdrawals() requires self.apiKey or userid argument')
        currency = None
        request = {
            'userid': self.apiKey,
        }
        if code is not None:
            currency = self.currency(code)
            request['currency'] = currency['id']
        if since is not None:
            request['since'] = since
        if limit is not None:
            request['limit'] = limit
        response = self.publicGetWithdrawals(self.extend(request, params))
        return self.parse_transactions(response, currency, since, limit)

    def parse_transaction_status(self, status):
        statuses = {
            'DEPOSIT_FAILED': 'failed',
            'FEE_SEND_FAILED': 'failed',
            'FEE_FAILED': 'failed',
            'PAY_SEND_FAILED': 'failed',
            'PAY_FAILED': 'failed',
            'BTT_FAILED': 'failed',
            'WITHDDRAW_FAILED': 'failed',
            'USER_FAILED': 'failed',
            'FEE_EXECUED': 'pending',
            'PAY_EXECUED': 'pending',
            'WITHDDRAW_EXECUTED': 'pending',
            'USER_EXECUED': 'pending',
            'BTT_SUCCED': 'ok',
        }
        return self.safe_string(statuses, status, status)

    def parse_transaction(self, transaction, currency=None):
        id = self.safe_string(transaction, 'id')
        address = self.safe_string(transaction, 'address')
        tag = self.safe_string(transaction, 'tag')
        if tag is not None:
            if len(tag) < 1:
                tag = None
        txid = self.safe_value(transaction, 'txid')
        currencyId = self.safe_string(transaction, 'code')
        code = self.safe_currency_code(currencyId, currency)
        timestamp = self.safe_integer(transaction, 'timestamp')
        datetime = self.safe_string(transaction, 'datetime')
        type = self.safe_string(transaction, 'type')
        status = self.parse_transaction_status(self.safe_string(transaction, 'status'))
        amount = self.safe_number(transaction, 'amount')
        feeInfo = self.safe_value(transaction, 'fee')
        feeCost = self.safe_number(feeInfo, 'cost')
        feeCurrencyId = self.safe_string(feeInfo, 'code')
        feeCode = self.safe_currency_code(feeCurrencyId, currency)
        fee = {
            'cost': feeCost,
            'currency': feeCode,
        }
        return {
            'info': transaction,
            'id': id,
            'txid': txid,
            'timestamp': timestamp,
            'datetime': datetime,
            'address': address,
            'tag': tag,
            'type': type,
            'amount': amount,
            'currency': code,
            'status': status,
            'updated': None,
            'fee': fee,
        }

    def fetch_deposit_address(self, code, params={}):
        """
        fetch the deposit address for a currency associated with self account
        :param str code: unified currency code
        :param dict params: extra parameters specific to the bytetrade api endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>`
        """
        self.load_markets()
        if not ('userid' in params) and (self.apiKey is None):
            raise ArgumentsRequired('fetchDepositAddress() requires self.apiKey or userid argument')
        currency = self.currency(code)
        request = {
            'userid': self.apiKey,
            'code': currency['id'],
        }
        response = self.publicGetDepositaddress(request)
        firstAddress = self.safe_value(response, 0)
        address = self.safe_string(firstAddress, 'address')
        tag = self.safe_string(firstAddress, 'tag')
        chainType = self.safe_string_upper(firstAddress, 'chainType')
        self.check_address(address)
        return {
            'currency': code,
            'address': address,
            'tag': tag,
            'network': chainType,
            'info': response,
        }

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = self.urls['api'][api]
        url += '/' + path
        if params:
            url += '?' + self.urlencode(params)
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
        if code == 503:
            raise DDoSProtection(self.id + ' ' + str(code) + ' ' + reason + ' ' + body)
        if response is None:
            return  # fallback to default error handler
        if 'code' in response:
            status = self.safe_string(response, 'code')
            if status == '1':
                message = self.safe_string(response, 'msg')
                feedback = self.id + ' ' + body
                self.throw_exactly_matched_exception(self.exceptions, message, feedback)
                raise ExchangeError(feedback)
