<reponame>Wicker25/ccxt
# -*- 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 hashlib
import math
import json
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import AccountSuspended
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
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 DDoSProtection
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.precise import Precise


class bibox(Exchange):

    def describe(self):
        return self.deep_extend(super(bibox, self).describe(), {
            'id': 'bibox',
            'name': 'Bibox',
            'countries': ['CN', 'US', 'KR'],
            'version': 'v1',
            # 30 requests per 5 seconds => 6 requests per second => rateLimit = 166.667 ms(166.6666...)
            'rateLimit': 166.667,
            'hostname': 'bibox.com',
            'has': {
                'CORS': None,
                'spot': True,
                'margin': None,  # has but unimplemented
                'swap': None,  # has but unimplemented
                'future': None,
                'option': None,
                'cancelOrder': True,
                'createMarketOrder': None,  # or they will return https://github.com/ccxt/ccxt/issues/2338
                'createOrder': True,
                'createStopLimitOrder': False,  # True for contract
                'createStopMarketOrder': False,  # True for contract
                'createStopOrder': False,  # True for contract
                'fetchBalance': True,
                'fetchBorrowRate': False,
                'fetchBorrowRates': False,
                'fetchClosedOrders': True,
                'fetchCurrencies': True,
                'fetchDepositAddress': True,
                'fetchDeposits': True,
                'fetchMarkets': True,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenOrders': True,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTrades': True,
                'fetchTradingFee': False,
                'fetchTradingFees': False,
                'fetchTransactionFees': True,
                'fetchWithdrawals': True,
                'withdraw': True,
            },
            'timeframes': {
                '1m': '1min',
                '5m': '5min',
                '15m': '15min',
                '30m': '30min',
                '1h': '1hour',
                '2h': '2hour',
                '4h': '4hour',
                '6h': '6hour',
                '12h': '12hour',
                '1d': 'day',
                '1w': 'week',
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/51840849/77257418-3262b000-6c85-11ea-8fb8-20bdf20b3592.jpg',
                'api': 'https://api.{hostname}',
                'www': 'https://www.bibox365.com',
                'doc': [
                    'https://biboxcom.github.io/en/',
                ],
                'fees': 'https://bibox.zendesk.com/hc/en-us/articles/360002336133',
                'referral': 'https://w2.bibox365.com/login/register?invite_code=05Kj3I',
            },
            'api': {
                'public': {
                    'post': {
                        # TODO: rework for full endpoint/cmd paths here
                        'mdata': 1,
                    },
                    'get': {
                        'cquery': 1,
                        'mdata': 1,
                        'cdata': 1,
                        'orderpending': 1,
                    },
                },
                'private': {
                    'post': {
                        'cquery': 1,
                        'ctrade': 1,
                        'user': 1,
                        'orderpending': 1,
                        'transfer': 1,
                    },
                },
                'v2private': {
                    'post': {
                        'assets/transfer/spot': 1,
                    },
                },
            },
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'taker': self.parse_number('0.002'),
                    'maker': self.parse_number('0.001'),
                },
                'funding': {
                    'tierBased': False,
                    'percentage': False,
                    'withdraw': {},
                    'deposit': {},
                },
            },
            'exceptions': {
                '2011': AccountSuspended,  # Account is locked
                '2015': AuthenticationError,  # Google authenticator is wrong
                '2021': InsufficientFunds,  # Insufficient balance available for withdrawal
                '2027': InsufficientFunds,  # Insufficient balance available(for trade)
                '2033': OrderNotFound,  # operation failed! Orders have been completed or revoked
                '2065': InvalidOrder,  # Precatory price is exorbitant, please reset
                '2066': InvalidOrder,  # Precatory price is low, please reset
                '2067': InvalidOrder,  # Does not support market orders
                '2068': InvalidOrder,  # The number of orders can not be less than
                '2078': InvalidOrder,  # unvalid order price
                '2085': InvalidOrder,  # Order quantity is too small
                '2091': RateLimitExceeded,  # request is too frequency, please try again later
                '2092': InvalidOrder,  # Minimum amount not met
                '2131': InvalidOrder,  # The order quantity cannot be greater than
                '3000': BadRequest,  # Requested parameter incorrect
                '3002': BadRequest,  # Parameter cannot be null
                '3012': AuthenticationError,  # invalid apiKey
                '3016': BadSymbol,  # Trading pair error
                '3024': PermissionDenied,  # wrong apikey permissions
                '3025': AuthenticationError,  # signature failed
                '4000': ExchangeNotAvailable,  # current network is unstable
                '4003': DDoSProtection,  # server busy please try again later
            },
            'commonCurrencies': {
                'APENFT(NFT)': 'NFT',
                'BOX': 'DefiBox',
                'BPT': 'BlockPool Token',
                'GMT': 'GMT Token',
                'KEY': 'Bihu',
                'MTC': 'MTC Mesh Network',  # conflict with MTC Docademic doc.com Token https://github.com/ccxt/ccxt/issues/6081 https://github.com/ccxt/ccxt/issues/3025
                'NFT': 'NFT Protocol',
                'PAI': 'PCHAIN',
                'REVO': 'Revo Network',
                'STAR': 'Starbase',
                'TERN': 'Ternio-ERC20',
            },
        })

    def fetch_markets(self, params={}):
        """
        retrieves data on all markets for bibox
        :param dict params: extra parameters specific to the exchange api endpoint
        :returns [dict]: an array of objects representing market data
        """
        request = {
            'cmd': 'pairList',
        }
        response = self.publicGetMdata(self.extend(request, params))
        #
        #     {
        #         "result": [
        #             {
        #                 "id":1,
        #                 "pair":"BIX_BTC",
        #                 "pair_type":0,
        #                 "area_id":7,
        #                 "is_hide":0,
        #                 "decimal":8,
        #                 "amount_scale":4
        #             }
        #         ],
        #         "cmd":"pairList",
        #         "ver":"1.1"
        #     }
        #
        markets = self.safe_value(response, 'result', [])
        request2 = {
            'cmd': 'tradeLimit',
        }
        response2 = self.publicGetOrderpending(self.extend(request2, params))
        #
        #    {
        #         result: {
        #             min_trade_price: {default: '0.00000001', USDT: '0.0001', DAI: '0.0001'},
        #             min_trade_amount: {default: '0.0001'},
        #             min_trade_money: {
        #                 USDT: '1',
        #                 USDC: '1',
        #                 DAI: '1',
        #                 GUSD: '1',
        #                 BIX: '3',
        #                 BTC: '0.0002',
        #                 ETH: '0.005'
        #             }
        #         },
        #         cmd: 'tradeLimit'
        #     }
        #
        result2 = self.safe_value(response2, 'result', {})
        minCosts = self.safe_value(result2, 'min_trade_money', {})
        result = []
        for i in range(0, len(markets)):
            market = markets[i]
            numericId = self.safe_integer(market, 'id')
            id = self.safe_string(market, 'pair')
            baseId = None
            quoteId = None
            if id is not None:
                parts = id.split('_')
                baseId = self.safe_string(parts, 0)
                quoteId = self.safe_string(parts, 1)
            base = self.safe_currency_code(baseId)
            quote = self.safe_currency_code(quoteId)
            symbol = base + '/' + quote
            type = 'spot'
            spot = True
            areaId = self.safe_integer(market, 'area_id')
            if areaId == 16:
                # TODO: update to v3 api
                continue
            result.append({
                'id': id,
                'numericId': numericId,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'settle': None,
                'baseId': baseId,
                'quoteId': quoteId,
                'settleId': None,
                'type': type,
                'spot': spot,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'active': None,
                'contract': False,
                'linear': None,
                'inverse': None,
                'contractSize': None,
                'expiry': None,
                'expiryDatetime': None,
                'strike': None,
                'optionType': None,
                'precision': {
                    'amount': self.safe_integer(market, 'amount_scale'),
                    'price': self.safe_integer(market, 'decimal'),
                },
                'limits': {
                    'leverage': {
                        'min': None,
                        'max': None,
                    },
                    'amount': {
                        'min': None,
                        'max': None,
                    },
                    'price': {
                        'min': None,
                        'max': None,
                    },
                    'cost': {
                        'min': self.safe_number(minCosts, quoteId),
                        'max': None,
                    },
                },
                'info': market,
            })
        return result

    def parse_ticker(self, ticker, market=None):
        # we don't set values that are not defined by the exchange
        timestamp = self.safe_integer(ticker, 'timestamp')
        marketId = None
        baseId = self.safe_string(ticker, 'coin_symbol')
        quoteId = self.safe_string(ticker, 'currency_symbol')
        if (baseId is not None) and (quoteId is not None):
            marketId = baseId + '_' + quoteId
        market = self.safe_market(marketId, market)
        last = self.safe_string(ticker, 'last')
        change = self.safe_string(ticker, 'change')
        baseVolume = self.safe_string_2(ticker, 'vol', 'vol24H')
        percentage = self.safe_string(ticker, 'percent')
        if percentage is not None:
            percentage = percentage.replace('%', '')
        return self.safe_ticker({
            'symbol': market['symbol'],
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': self.safe_string(ticker, 'high'),
            'low': self.safe_string(ticker, 'low'),
            'bid': self.safe_string(ticker, 'buy'),
            'bidVolume': self.safe_string(ticker, 'buy_amount'),
            'ask': self.safe_string(ticker, 'sell'),
            'askVolume': self.safe_string(ticker, 'sell_amount'),
            'vwap': None,
            'open': None,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': change,
            'percentage': percentage,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': self.safe_string(ticker, 'amount'),
            '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 bibox 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 = {
            'cmd': 'ticker',
            'pair': market['id'],
        }
        response = self.publicGetMdata(self.extend(request, params))
        return self.parse_ticker(response['result'], market)

    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 bibox api endpoint
        :returns dict: an array of `ticker structures <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        request = {
            'cmd': 'marketAll',
        }
        response = self.publicGetMdata(self.extend(request, params))
        tickers = self.parse_tickers(response['result'], symbols)
        result = self.index_by(tickers, 'symbol')
        return self.filter_by_array(result, 'symbol', symbols)

    def parse_trade(self, trade, market=None):
        timestamp = self.safe_integer_2(trade, 'time', 'createdAt')
        side = self.safe_integer_2(trade, 'side', 'order_side')
        side = 'buy' if (side == 1) else 'sell'
        marketId = self.safe_string(trade, 'pair')
        if marketId is None:
            baseId = self.safe_string(trade, 'coin_symbol')
            quoteId = self.safe_string(trade, 'currency_symbol')
            if (baseId is not None) and (quoteId is not None):
                marketId = baseId + '_' + quoteId
        market = self.safe_market(marketId, market)
        priceString = self.safe_string(trade, 'price')
        amountString = self.safe_string(trade, 'amount')
        fee = None
        feeCostString = self.safe_string(trade, 'fee')
        if feeCostString is not None:
            feeCurrencyId = self.safe_string(trade, 'fee_symbol')
            feeCurrencyCode = self.safe_currency_code(feeCurrencyId)
            fee = {
                'cost': Precise.string_neg(feeCostString),
                'currency': feeCurrencyCode,
            }
        id = self.safe_string(trade, 'id')
        return self.safe_trade({
            'info': trade,
            'id': id,
            'order': None,  # Bibox does not have it(documented) yet
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': market['symbol'],
            'type': 'limit',
            'takerOrMaker': None,
            'side': side,
            'price': priceString,
            'amount': amountString,
            'cost': None,
            '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 bibox 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 = {
            'cmd': 'deals',
            'pair': market['id'],
        }
        if limit is not None:
            request['size'] = limit  # default = 200
        response = self.publicGetMdata(self.extend(request, params))
        return self.parse_trades(response['result'], market, since, limit)

    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 bibox 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 = {
            'cmd': 'depth',
            'pair': market['id'],
        }
        if limit is not None:
            request['size'] = limit  # default = 200
        response = self.publicGetMdata(self.extend(request, params))
        return self.parse_order_book(response['result'], symbol, self.safe_number(response['result'], 'update_time'), 'bids', 'asks', 'price', 'volume')

    def parse_ohlcv(self, ohlcv, market=None):
        #
        #     {
        #         "time":1591448220000,
        #         "open":"0.02507029",
        #         "high":"0.02507029",
        #         "low":"0.02506349",
        #         "close":"0.02506349",
        #         "vol":"5.92000000"
        #     }
        #
        return [
            self.safe_integer(ohlcv, 'time'),
            self.safe_number(ohlcv, 'open'),
            self.safe_number(ohlcv, 'high'),
            self.safe_number(ohlcv, 'low'),
            self.safe_number(ohlcv, 'close'),
            self.safe_number(ohlcv, 'vol'),
        ]

    def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=1000, 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 bibox api endpoint
        :returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'cmd': 'kline',
            'pair': market['id'],
            'period': self.timeframes[timeframe],
            'size': limit,
        }
        response = self.publicGetMdata(self.extend(request, params))
        #
        #     {
        #         "result":[
        #             {"time":1591448220000,"open":"0.02507029","high":"0.02507029","low":"0.02506349","close":"0.02506349","vol":"5.92000000"},
        #             {"time":1591448280000,"open":"0.02506449","high":"0.02506975","low":"0.02506108","close":"0.02506843","vol":"5.72000000"},
        #             {"time":1591448340000,"open":"0.02506698","high":"0.02506698","low":"0.02506452","close":"0.02506519","vol":"4.86000000"},
        #         ],
        #         "cmd":"kline",
        #         "ver":"1.1"
        #     }
        #
        result = self.safe_value(response, 'result', [])
        return self.parse_ohlcvs(result, market, timeframe, since, limit)

    def fetch_currencies(self, params={}):
        """
        fetches all available currencies on an exchange
        :param dict params: extra parameters specific to the bibox api endpoint
        :returns dict: an associative dictionary of currencies
        """
        if self.check_required_credentials(False):
            return self.fetch_currencies_private(params)
        else:
            return self.fetch_currencies_public(params)

    def fetch_currencies_public(self, params={}):
        request = {
            'cmd': 'currencies',
        }
        response = self.publicGetCdata(self.extend(request, params))
        #
        # publicGetCdata
        #
        #     {
        #         "result":[
        #             {
        #                 "symbol":"BTC",
        #                 "name":"BTC",
        #                 "valid_decimals":8,
        #                 "original_decimals":8,
        #                 "is_erc20":0,
        #                 "enable_withdraw":1,
        #                 "enable_deposit":1,
        #                 "withdraw_min":0.005,
        #                 "describe_summary":"[{\"lang\":\"zh-cn\",\"text\":\"Bitcoin 比特币的概念最初由中本聪在2009年提出，是点对点的基于 SHA-256 算法的一种P2P形式的数字货币，点对点的传输意味着一个去中心化的支付系统。\"},{\"lang\":\"en-ww\",\"text\":\"Bitcoin is a digital asset and a payment system invented by <NAME> who published a related paper in 2008 and released it as open-source software in 2009. The system featured as peer-to-peer; users can transact directly without an intermediary.\"}]"
        #             }
        #         ],
        #         "cmd":"currencies"
        #     }
        #
        currencies = self.safe_value(response, 'result', [])
        result = {}
        for i in range(0, len(currencies)):
            currency = currencies[i]
            id = self.safe_string(currency, 'symbol')
            name = self.safe_string(currency, 'name')  # contains hieroglyphs causing python ASCII bug
            code = self.safe_currency_code(id)
            precision = self.safe_integer(currency, 'valid_decimals')
            deposit = self.safe_value(currency, 'enable_deposit')
            withdraw = self.safe_value(currency, 'enable_withdraw')
            active = (deposit and withdraw)
            result[code] = {
                'id': id,
                'code': code,
                'info': currency,
                'name': name,
                'active': active,
                'deposit': deposit,
                'withdraw': withdraw,
                'fee': None,
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': math.pow(10, -precision),
                        'max': None,
                    },
                    'withdraw': {
                        'min': self.safe_number(currency, 'withdraw_min'),
                        'max': None,
                    },
                },
            }
        return result

    def fetch_currencies_private(self, params={}):
        if not self.check_required_credentials(False):
            raise AuthenticationError(self.id + " fetchCurrencies is an authenticated endpoint, therefore it requires 'apiKey' and 'secret' credentials. If you don't need currency details, set exchange.has['fetchCurrencies'] = False before calling its methods.")
        request = {
            'cmd': 'transfer/coinList',
            'body': {},
        }
        response = self.privatePostTransfer(self.extend(request, params))
        #
        #     {
        #         "result":[
        #             {
        #                 "result":[
        #                     {
        #                         "totalBalance":"14.60987476",
        #                         "balance":"14.60987476",
        #                         "freeze":"0.00000000",
        #                         "id":60,
        #                         "symbol":"USDT",
        #                         "icon_url":"/appimg/USDT_icon.png",
        #                         "describe_url":"[{\"lang\":\"zh-cn\",\"link\":\"https://bibox.zendesk.com/hc/zh-cn/articles/115004798234\"},{\"lang\":\"en-ww\",\"link\":\"https://bibox.zendesk.com/hc/en-us/articles/115004798234\"}]",
        #                         "name":"USDT",
        #                         "enable_withdraw":1,
        #                         "enable_deposit":1,
        #                         "enable_transfer":1,
        #                         "confirm_count":2,
        #                         "is_erc20":1,
        #                         "forbid_info":null,
        #                         "describe_summary":"[{\"lang\":\"zh-cn\",\"text\":\"USDT 是 Tether 公司推出的基于稳定价值货币美元（USD）的代币 Tether USD（简称USDT），1USDT=1美元，用户可以随时使用 USDT 与 USD 进行1:1的兑换。\"},{\"lang\":\"en-ww\",\"text\":\"USDT is a cryptocurrency asset issued on the Bitcoin blockchain via the Omni Layer Protocol. Each USDT unit is backed by a U.S Dollar held in the reserves of the Tether Limited and can be redeemed through the Tether Platform.\"}]",
        #                         "total_amount":4776930644,
        #                         "supply_amount":4642367414,
        #                         "price":"--",
        #                         "contract_father":"OMNI",
        #                         "supply_time":"--",
        #                         "comment":null,
        #                         "chain_type":"OMNI",
        #                         "general_name":"USDT",
        #                         "contract":"31",
        #                         "original_decimals":8,
        #                         "deposit_type":0,
        #                         "hasCobo":0,
        #                         "BTCValue":"0.00027116",
        #                         "CNYValue":"90.36087919",
        #                         "USDValue":"14.61090236",
        #                         "children":[
        #                             {"type":"ERC20","symbol":"eUSDT","enable_deposit":1,"enable_withdraw":1,"confirm_count":13},
        #                             {"type":"TRC20","symbol":"tUSDT","enable_deposit":1,"enable_withdraw":1,"confirm_count":20},
        #                             {"type":"OMNI","symbol":"USDT","enable_deposit":1,"enable_withdraw":1,"confirm_count":2},
        #                             {"type":"HECO","symbol":"hUSDT","enable_deposit":1,"enable_withdraw":1,"confirm_count":12},
        #                             {"type":"BSC(BEP20)","symbol":"bUSDT","enable_deposit":1,"enable_withdraw":1,"confirm_count":5},
        #                             {"type":"HPB","symbol":"pUSDT","enable_deposit":1,"enable_withdraw":1,"confirm_count":20}
        #                         ]
        #                     }
        #                 ],
        #                 "cmd":"transfer/coinList"
        #             }
        #         ]
        #     }
        #
        outerResults = self.safe_value(response, 'result')
        firstResult = self.safe_value(outerResults, 0, {})
        currencies = self.safe_value(firstResult, 'result', [])
        result = {}
        for i in range(0, len(currencies)):
            currency = currencies[i]
            id = self.safe_string(currency, 'symbol')
            name = currency['name']  # contains hieroglyphs causing python ASCII bug
            code = self.safe_currency_code(id)
            precision = 8
            deposit = self.safe_value(currency, 'enable_deposit')
            withdraw = self.safe_value(currency, 'enable_withdraw')
            active = (deposit and withdraw)
            result[code] = {
                'id': id,
                'code': code,
                'info': currency,
                'name': name,
                'active': active,
                'fee': None,
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': math.pow(10, -precision),
                        'max': math.pow(10, precision),
                    },
                    'withdraw': {
                        'min': None,
                        'max': math.pow(10, precision),
                    },
                },
            }
        return result

    def parse_balance(self, response):
        outerResult = self.safe_value(response, 'result')
        firstResult = self.safe_value(outerResult, 0, {})
        innerResult = self.safe_value(firstResult, 'result')
        result = {'info': response}
        assetsList = self.safe_value(innerResult, 'assets_list', [])
        for i in range(0, len(assetsList)):
            balance = assetsList[i]
            currencyId = self.safe_string(balance, 'coin_symbol')
            code = self.safe_currency_code(currencyId)
            account = self.account()
            account['free'] = self.safe_string(balance, 'balance')
            account['used'] = self.safe_string(balance, 'freeze')
            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 bibox api endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>`
        """
        self.load_markets()
        type = self.safe_string(params, 'type', 'assets')
        params = self.omit(params, 'type')
        request = {
            'cmd': 'transfer/' + type,  # assets, mainAssets
            'body': self.extend({
                'select': 1,  # return full info
            }, params),
        }
        response = self.privatePostTransfer(request)
        #
        #     {
        #         "result":[
        #             {
        #                 "result":{
        #                     "total_btc":"0.00000298",
        #                     "total_cny":"0.99",
        #                     "total_usd":"0.16",
        #                     "assets_list":[
        #                         {"coin_symbol":"BTC","BTCValue":"0.00000252","CNYValue":"0.84","USDValue":"0.14","balance":"0.00000252","freeze":"0.00000000"},
        #                         {"coin_symbol":"LTC","BTCValue":"0.00000023","CNYValue":"0.07","USDValue":"0.01","balance":"0.00006765","freeze":"0.00000000"},
        #                         {"coin_symbol":"USDT","BTCValue":"0.00000023","CNYValue":"0.08","USDValue":"0.01","balance":"0.01252100","freeze":"0.00000000"}
        #                     ]
        #                 },
        #                 "cmd":"transfer/assets"
        #             }
        #         ]
        #     }
        #
        return self.parse_balance(response)

    def fetch_deposits(self, code=None, since=None, limit=None, params={}):
        self.load_markets()
        if limit is None:
            limit = 100
        request = {
            'page': 1,
            'size': limit,
        }
        currency = None
        if code is not None:
            currency = self.currency(code)
            request['symbol'] = currency['id']
        response = self.privatePostTransfer({
            'cmd': 'transfer/transferInList',
            'body': self.extend(request, params),
        })
        #
        #     {
        #         "result":[
        #             {
        #                 "result":{
        #                     "count":2,
        #                     "page":1,
        #                     "items":[
        #                         {
        #                             "coin_symbol":"ETH",                        # token
        #                             "to_address":"xxxxxxxxxxxxxxxxxxxxxxxxxx",  # address
        #                             "amount":"1.00000000",                      # amount
        #                             "confirmCount":"15",                        # the acknowledgment number
        #                             "createdAt":1540641511000,
        #                             "status":2                                 # status,  1-deposit is in process，2-deposit finished，3-deposit failed
        #                         },
        #                         {
        #                             "coin_symbol":"BIX",
        #                             "to_address":"xxxxxxxxxxxxxxxxxxxxxxxxxx",
        #                             "amount":"1.00000000",
        #                             "confirmCount":"15",
        #                             "createdAt":1540622460000,
        #                             "status":2
        #                         }
        #                     ]
        #                 },
        #                 "cmd":"transfer/transferInList"
        #             }
        #         ]
        #     }
        #
        outerResults = self.safe_value(response, 'result')
        firstResult = self.safe_value(outerResults, 0, {})
        innerResult = self.safe_value(firstResult, 'result', {})
        deposits = self.safe_value(innerResult, 'items', [])
        for i in range(0, len(deposits)):
            deposits[i]['type'] = 'deposit'
        return self.parse_transactions(deposits, currency, since, limit)

    def fetch_withdrawals(self, code=None, since=None, limit=None, params={}):
        self.load_markets()
        if limit is None:
            limit = 100
        request = {
            'page': 1,
            'size': limit,
        }
        currency = None
        if code is not None:
            currency = self.currency(code)
            request['symbol'] = currency['id']
        response = self.privatePostTransfer({
            'cmd': 'transfer/transferOutList',
            'body': self.extend(request, params),
        })
        #
        #     {
        #         "result":[
        #             {
        #                 "result":{
        #                     "count":1,
        #                     "page":1,
        #                     "items":[
        #                         {
        #                             "id":612867,
        #                             "coin_symbol":"ETH",
        #                             "chain_type":"ETH",
        #                             "to_address":"0xd41de7a88ab5fc59edc6669f54873576be95bff1",
        #                             "tx_id":"0xc60950596227af3f27c3a1b5911ea1c79bae53bdce67274e48a0ce87a5ef2df8",
        #                             "addr_remark":"binance",
        #                             "amount":"2.34550946",
        #                             "fee":"0.00600000",
        #                             "createdAt":1561339330000,
        #                             "memo":"",
        #                             "status":3
        #                         }
        #                     ]
        #                 },
        #                 "cmd":"transfer/transferOutList"
        #             }
        #         ]
        #     }
        #
        outerResults = self.safe_value(response, 'result')
        firstResult = self.safe_value(outerResults, 0, {})
        innerResult = self.safe_value(firstResult, 'result', {})
        withdrawals = self.safe_value(innerResult, 'items', [])
        for i in range(0, len(withdrawals)):
            withdrawals[i]['type'] = 'withdrawal'
        return self.parse_transactions(withdrawals, currency, since, limit)

    def parse_transaction(self, transaction, currency=None):
        #
        # fetchDeposits
        #
        #     {
        #         'id': 1023291,
        #         'coin_symbol': 'ETH',
        #         'to_address': '0x7263....',
        #         'amount': '0.49170000',
        #         'confirmCount': '16',
        #         'createdAt': 1553123867000,
        #         'status': 2
        #     }
        #
        # fetchWithdrawals
        #
        #     {
        #         'id': 521844,
        #         'coin_symbol': 'ETH',
        #         'to_address': '0xfd4e....',
        #         'addr_remark': '',
        #         'amount': '0.39452750',
        #         'fee': '0.00600000',
        #         'createdAt': 1553226906000,
        #         'memo': '',
        #         'status': 3
        #     }
        #
        # withdraw
        #
        #     {
        #         "result": 228,  # withdrawal id
        #         "cmd":"transfer/transferOut"
        #     }
        #
        id = self.safe_string_2(transaction, 'id', 'result')
        address = self.safe_string(transaction, 'to_address')
        currencyId = self.safe_string(transaction, 'coin_symbol')
        code = self.safe_currency_code(currencyId, currency)
        timestamp = self.safe_string(transaction, 'createdAt')
        tag = self.safe_string(transaction, 'addr_remark')
        type = self.safe_string(transaction, 'type')
        status = self.parse_transaction_status_by_type(self.safe_string(transaction, 'status'), type)
        amount = self.safe_number(transaction, 'amount')
        feeCost = self.safe_number(transaction, 'fee')
        if type == 'deposit':
            feeCost = 0
            tag = None
        fee = {
            'cost': feeCost,
            'currency': code,
        }
        return {
            'info': transaction,
            'id': id,
            'txid': None,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'network': None,
            'address': address,
            'addressTo': None,
            'addressFrom': None,
            'tag': tag,
            'tagTo': None,
            'tagFrom': None,
            'type': type,
            'amount': amount,
            'currency': code,
            'status': status,
            'updated': None,
            'fee': fee,
        }

    def parse_transaction_status_by_type(self, status, type=None):
        statuses = {
            'deposit': {
                '1': 'pending',
                '2': 'ok',
            },
            'withdrawal': {
                '0': 'pending',
                '3': 'ok',
            },
        }
        return self.safe_string(self.safe_value(statuses, type, {}), status, status)

    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 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 bibox api endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        orderType = 2 if (type == 'limit') else 1
        orderSide = 1 if (side == 'buy') else 2
        request = {
            'cmd': 'orderpending/trade',
            'body': self.extend({
                'pair': market['id'],
                'account_type': 0,
                'order_type': orderType,
                'order_side': orderSide,
                'pay_bix': 0,
                'amount': amount,
                'price': price,
            }, params),
        }
        response = self.privatePostOrderpending(request)
        #
        #     {
        #         "result":[
        #             {
        #                 "result": "100055558128036",  # order id
        #                 "index": 12345,  # random index, specific one in a batch
        #                 "cmd":"orderpending/trade"
        #             }
        #         ]
        #     }
        #
        outerResults = self.safe_value(response, 'result')
        firstResult = self.safe_value(outerResults, 0, {})
        id = self.safe_value(firstResult, 'result')
        return {
            'info': response,
            'id': id,
        }

    def cancel_order(self, id, symbol=None, params={}):
        request = {
            'cmd': 'orderpending/cancelTrade',
            'body': self.extend({
                'orders_id': id,
            }, params),
        }
        response = self.privatePostOrderpending(request)
        #
        #     {
        #         "result":[
        #             {
        #                 "result":"OK",  # only indicates if the server received the cancelling request, and the cancelling result can be obtained from the order record
        #                 "index": 12345,  # random index, specific one in a batch
        #                 "cmd":"orderpending/cancelTrade"
        #             }
        #         ]
        #     }
        #
        outerResults = self.safe_value(response, 'result')
        firstResult = self.safe_value(outerResults, 0, {})
        return firstResult

    def fetch_order(self, id, symbol=None, params={}):
        self.load_markets()
        request = {
            'cmd': 'orderpending/order',
            'body': self.extend({
                'id': str(id),
                'account_type': 0,  # 0 = spot account
            }, params),
        }
        response = self.privatePostOrderpending(request)
        #
        #     {
        #         "result":[
        #             {
        #                 "result":{
        #                     "id":"100055558128036",
        #                     "createdAt": 1512756997000,
        #                     "account_type":0,
        #                     "coin_symbol":"LTC",        # Trading Token
        #                     "currency_symbol":"BTC",    # Pricing Token
        #                     "order_side":2,             # Trading side 1-Buy, 2-Sell
        #                     "order_type":2,             # 2-limit order
        #                     "price":"0.00900000",       # order price
        #                     "amount":"1.00000000",      # order amount
        #                     "money":"0.00900000",       # currency amount(price * amount)
        #                     "deal_amount":"0.00000000",  # deal amount
        #                     "deal_percent":"0.00%",     # deal percentage
        #                     "unexecuted":"0.00000000",  # unexecuted amount
        #                     "status":3                  # Status, -1-fail, 0,1-to be dealt, 2-dealt partly, 3-dealt totally, 4- cancelled partly, 5-cancelled totally, 6-to be cancelled
        #                 },
        #                 "cmd":"orderpending/order"
        #             }
        #         ]
        #     }
        #
        outerResults = self.safe_value(response, 'result')
        firstResult = self.safe_value(outerResults, 0, {})
        order = self.safe_value(firstResult, 'result')
        if self.is_empty(order):
            raise OrderNotFound(self.id + ' order ' + id + ' not found')
        return self.parse_order(order)

    def parse_order(self, order, market=None):
        marketId = None
        baseId = self.safe_string(order, 'coin_symbol')
        quoteId = self.safe_string(order, 'currency_symbol')
        if (baseId is not None) and (quoteId is not None):
            marketId = baseId + '_' + quoteId
        market = self.safe_market(marketId, market)
        rawType = self.safe_string(order, 'order_type')
        type = 'market' if (rawType == '1') else 'limit'
        timestamp = self.safe_integer(order, 'createdAt')
        price = self.safe_string(order, 'price')
        average = self.safe_string(order, 'deal_price')
        filled = self.safe_string(order, 'deal_amount')
        amount = self.safe_string(order, 'amount')
        cost = self.safe_string_2(order, 'deal_money', 'money')
        rawSide = self.safe_string(order, 'order_side')
        side = 'buy' if (rawSide == '1') else 'sell'
        status = self.parse_order_status(self.safe_string(order, 'status'))
        id = self.safe_string(order, 'id')
        feeCost = self.safe_string(order, 'fee')
        fee = None
        if feeCost is not None:
            fee = {
                'cost': feeCost,
                'currency': None,
            }
        return self.safe_order({
            'info': order,
            'id': id,
            'clientOrderId': None,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'symbol': market['symbol'],
            'type': type,
            'timeInForce': None,
            'postOnly': None,
            'side': side,
            'price': price,
            'stopPrice': None,
            'amount': amount,
            'cost': cost,
            'average': average,
            'filled': filled,
            'remaining': None,
            'status': status,
            'fee': fee,
            'trades': None,
        }, market)

    def parse_order_status(self, status):
        statuses = {
            # original comments from bibox:
            '1': 'open',  # pending
            '2': 'open',  # part completed
            '3': 'closed',  # completed
            '4': 'canceled',  # part canceled
            '5': 'canceled',  # canceled
            '6': 'canceled',  # canceling
        }
        return self.safe_string(statuses, status, status)

    def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
        self.load_markets()
        market = None
        pair = None
        if symbol is not None:
            market = self.market(symbol)
            pair = market['id']
        size = limit if limit else 200
        request = {
            'cmd': 'orderpending/orderPendingList',
            'body': self.extend({
                'pair': pair,
                'account_type': 0,  # 0 - regular, 1 - margin
                'page': 1,
                'size': size,
            }, params),
        }
        response = self.privatePostOrderpending(request)
        #
        #     {
        #         "result":[
        #             {
        #                 "result":{
        #                     "count":1,
        #                     "page":1,
        #                     "items":[
        #                         {
        #                             "id":"100055558128036",
        #                             "createdAt": 1512756997000,
        #                             "account_type":0,
        #                             "coin_symbol":"LTC",        # Trading Token
        #                             "currency_symbol":"BTC",    # Pricing Token
        #                             "order_side":2,             # Trading side 1-Buy, 2-Sell
        #                             "order_type":2,             # 2-limit order
        #                             "price":"0.00900000",       # order price
        #                             "amount":"1.00000000",      # order amount
        #                             "money":"0.00900000",       # currency amount(price * amount)
        #                             "deal_amount":"0.00000000",  # deal amount
        #                             "deal_percent":"0.00%",     # deal percentage
        #                             "unexecuted":"0.00000000",  # unexecuted amount
        #                             "status":1                  # Status,-1-fail, 0,1-to be dealt, 2-dealt partly, 3-dealt totally, 4- cancelled partly, 5-cancelled totally, 6-to be cancelled
        #                         }
        #                     ]
        #                 },
        #                 "cmd":"orderpending/orderPendingList"
        #             }
        #         ]
        #     }
        #
        outerResults = self.safe_value(response, 'result')
        firstResult = self.safe_value(outerResults, 0, {})
        innerResult = self.safe_value(firstResult, 'result', {})
        orders = self.safe_value(innerResult, 'items', [])
        return self.parse_orders(orders, market, since, limit)

    def fetch_closed_orders(self, symbol=None, since=None, limit=200, params={}):
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchClosedOrders() requires a `symbol` argument')
        self.load_markets()
        market = self.market(symbol)
        request = {
            'cmd': 'orderpending/pendingHistoryList',
            'body': self.extend({
                'pair': market['id'],
                'account_type': 0,  # 0 - regular, 1 - margin
                'page': 1,
                'size': limit,
            }, params),
        }
        response = self.privatePostOrderpending(request)
        #
        #     {
        #         "result":[
        #             {
        #                 "result":{
        #                     "count":1,
        #                     "page":1,
        #                     "items":[
        #                         {
        #                             "id":"100055558128036",
        #                             "createdAt": 1512756997000,
        #                             "account_type":0,
        #                             "coin_symbol":"LTC",        # Trading Token
        #                             "currency_symbol":"BTC",    # Pricing Token
        #                             "order_side":2,             # Trading side 1-Buy, 2-Sell
        #                             "order_type":2,             # 2-limit order
        #                             "price":"0.00900000",       # order price
        #                             "amount":"1.00000000",      # order amount
        #                             "money":"0.00900000",       # currency amount(price * amount)
        #                             "deal_amount":"0.00000000",  # deal amount
        #                             "deal_percent":"0.00%",     # deal percentage
        #                             "unexecuted":"0.00000000",  # unexecuted amount
        #                             "status":3                  # Status,-1-fail, 0,1-to be dealt, 2-dealt partly, 3-dealt totally, 4- cancelled partly, 5-cancelled totally, 6-to be cancelled
        #                         }
        #                     ]
        #                 },
        #                 "cmd":"orderpending/pendingHistoryList"
        #             }
        #         ]
        #     }
        #
        outerResults = self.safe_value(response, 'result')
        firstResult = self.safe_value(outerResults, 0, {})
        innerResult = self.safe_value(firstResult, 'result', {})
        orders = self.safe_value(innerResult, 'items', [])
        return self.parse_orders(orders, market, since, limit)

    def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchMyTrades() requires a `symbol` argument')
        self.load_markets()
        market = self.market(symbol)
        size = limit if limit else 200
        request = {
            'cmd': 'orderpending/orderHistoryList',
            'body': self.extend({
                'pair': market['id'],
                'account_type': 0,  # 0 - regular, 1 - margin
                'page': 1,
                'size': size,
                'coin_symbol': market['baseId'],
                'currency_symbol': market['quoteId'],
            }, params),
        }
        response = self.privatePostOrderpending(request)
        #
        #     {
        #         "result":[
        #             {
        #                 "result":{
        #                     "count":1,
        #                     "page":1,
        #                     "items":[
        #                         {
        #                             "id":"100055558128033",
        #                             "createdAt": 1512756997000,
        #                             "account_type":0,
        #                             "coin_symbol":"LTC",
        #                             "currency_symbol":"BTC",
        #                             "order_side":2,
        #                             "order_type":2,
        #                             "price":"0.00886500",
        #                             "amount":"1.00000000",
        #                             "money":"0.00886500",
        #                             "fee":0
        #                         }
        #                     ]
        #                 },
        #                 "cmd":"orderpending/orderHistoryList"
        #             }
        #         ]
        #     }
        #
        outerResults = self.safe_value(response, 'result')
        firstResult = self.safe_value(outerResults, 0, {})
        innerResult = self.safe_value(firstResult, 'result', {})
        trades = self.safe_value(innerResult, 'items', [])
        return self.parse_trades(trades, market, since, limit)

    def fetch_deposit_address(self, code, params={}):
        self.load_markets()
        currency = self.currency(code)
        request = {
            'cmd': 'transfer/transferIn',
            'body': self.extend({
                'coin_symbol': currency['id'],
            }, params),
        }
        response = self.privatePostTransfer(request)
        #
        #     {
        #         "result":[
        #             {
        #                 "result":"3Jx6RZ9TNMsAoy9NUzBwZf68QBppDruSKW",
        #                 "cmd":"transfer/transferIn"
        #             }
        #         ]
        #     }
        #
        #     {
        #         "result":[
        #             {
        #                 "result":"{\"account\":\"PERSONALLY OMITTED\",\"memo\":\"PERSONALLY OMITTED\"}",
        #                 "cmd":"transfer/transferIn"
        #             }
        #         ]
        #     }
        #
        outerResults = self.safe_value(response, 'result')
        firstResult = self.safe_value(outerResults, 0, {})
        innerResult = self.safe_value(firstResult, 'result')
        address = innerResult
        tag = None
        if self.is_json_encoded_object(innerResult):
            parsed = json.loads(innerResult)
            address = self.safe_string(parsed, 'account')
            tag = self.safe_string(parsed, 'memo')
        return {
            'currency': code,
            'address': address,
            'tag': tag,
            'network': None,
            'info': response,
        }

    def withdraw(self, code, amount, address, tag=None, params={}):
        tag, params = self.handle_withdraw_tag_and_params(tag, params)
        self.check_address(address)
        self.load_markets()
        currency = self.currency(code)
        if self.password is None:
            if not ('trade_pwd' in params):
                raise ExchangeError(self.id + ' withdraw() requires self.password set on the exchange instance or a trade_pwd parameter')
        if not ('totp_code' in params):
            raise ExchangeError(self.id + ' withdraw() requires a totp_code parameter for 2FA authentication')
        request = {
            'trade_pwd': <PASSWORD>,
            'coin_symbol': currency['id'],
            'amount': amount,
            'addr': address,
        }
        if tag is not None:
            request['address_remark'] = tag
        response = self.privatePostTransfer({
            'cmd': 'transfer/transferOut',
            'body': self.extend(request, params),
        })
        #
        #     {
        #         "result":[
        #             {
        #                 "result": 228,  # withdrawal id
        #                 "cmd":"transfer/transferOut"
        #             }
        #         ]
        #     }
        #
        outerResults = self.safe_value(response, 'result')
        firstResult = self.safe_value(outerResults, 0, {})
        return self.parse_transaction(firstResult, currency)

    def fetch_transaction_fees(self, codes=None, params={}):
        # by default it will try load withdrawal fees of all currencies(with separate requests)
        # however if you define codes = ['ETH', 'BTC'] in args it will only load those
        self.load_markets()
        withdrawFees = {}
        info = {}
        if codes is None:
            codes = list(self.currencies.keys())
        for i in range(0, len(codes)):
            code = codes[i]
            currency = self.currency(code)
            request = {
                'cmd': 'transfer/coinConfig',
                'body': self.extend({
                    'coin_symbol': currency['id'],
                }, params),
            }
            response = self.privatePostTransfer(request)
            #     {
            #         "result":[
            #             {
            #                 "result":[
            #                     {
            #                         "coin_symbol":"ETH",
            #                         "is_active":1,
            #                         "original_decimals":18,
            #                         "enable_deposit":1,
            #                         "enable_withdraw":1,
            #                         "withdraw_fee":0.008,
            #                         "withdraw_min":0.05,
            #                         "deposit_avg_spent":173700,
            #                         "withdraw_avg_spent":322600
            #                     }
            #                 ],
            #                 "cmd":"transfer/coinConfig"
            #             }
            #         ]
            #     }
            #
            outerResults = self.safe_value(response, 'result', [])
            firstOuterResult = self.safe_value(outerResults, 0, {})
            innerResults = self.safe_value(firstOuterResult, 'result', [])
            firstInnerResult = self.safe_value(innerResults, 0, {})
            info[code] = firstInnerResult
            withdrawFees[code] = self.safe_number(firstInnerResult, 'withdraw_fee')
        return {
            'info': info,
            'withdraw': withdrawFees,
            'deposit': {},
        }

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = self.implode_hostname(self.urls['api']) + '/' + self.version + '/' + path
        cmds = self.json([params])
        if api == 'public':
            if method != 'GET':
                body = {'cmds': cmds}
            elif params:
                url += '?' + self.urlencode(params)
        elif api == 'v2private':
            self.check_required_credentials()
            url = self.implode_hostname(self.urls['api']) + '/v2/' + path
            json_params = self.json(params)
            body = {
                'body': json_params,
                'apikey': self.apiKey,
                'sign': self.hmac(self.encode(json_params), self.encode(self.secret), hashlib.md5),
            }
        else:
            self.check_required_credentials()
            body = {
                'cmds': cmds,
                'apikey': self.apiKey,
                'sign': self.hmac(self.encode(cmds), self.encode(self.secret), hashlib.md5),
            }
        if body is not None:
            body = self.json(body, {'convertArraysToObjects': True})
        headers = {'Content-Type': 'application/json'}
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
        if response is None:
            return
        if 'error' in response:
            if 'code' in response['error']:
                code = self.safe_string(response['error'], 'code')
                feedback = self.id + ' ' + body
                self.throw_exactly_matched_exception(self.exceptions, code, feedback)
                raise ExchangeError(feedback)
            raise ExchangeError(self.id + ' ' + body)
        if not ('result' in response):
            raise ExchangeError(self.id + ' ' + body)
