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

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

from ccxt.async_support.base.exchange import Exchange
import hashlib
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.decimal_to_precision import TICK_SIZE
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'],
            'rateLimit': 166.667,
            'version': 'v3.1',
            'hostname': 'bibox.com',
            'has': {
                'CORS': None,
                'spot': True,
                'margin': None,  # has but unimplemented
                'swap': None,  # has but unimplemented
                'future': None,
                'option': None,
                'cancelAllOrders': True,
                '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,
                'fetchLedger': True,
                'fetchMarginMode': False,
                'fetchMarkets': True,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenOrders': True,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrdersByStatus': True,
                'fetchPositionMode': False,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTrades': True,
                'fetchTradingFee': False,
                'fetchTradingFees': False,
                'fetchTransactionFees': True,
                'fetchWithdrawals': True,
                'transfer': True,
                'withdraw': True,
            },
            'timeframes': {
                '1m': '1m',
                '3m': '3m',
                '5m': '5m',
                '15m': '15m',
                '30m': '30m',
                '1h': '1h',
                '2h': '2h',
                '4h': '4h',
                '6h': '6h',
                '12h': '12h',
                '1d': '1d',
                '1w': '1w',
                '1M': '1M',
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/51840849/77257418-3262b000-6c85-11ea-8fb8-20bdf20b3592.jpg',
                'api': {
                    'rest': 'https://api.{hostname}',
                },
                'www': 'https://www.bibox365.com',
                'doc': [
                    'https://biboxcom.github.io/en/',
                    'https://biboxcom.github.io/v3/spot/en/',
                    'https://biboxcom.github.io/api/spot/v4',
                ],
                'fees': 'https://bibox.zendesk.com/hc/en-us/articles/360002336133',
                'referral': 'https://w2.bibox365.com/login/register?invite_code=05Kj3I',
            },
            'api': {
                'v1': {
                    'public': {
                        'get': {
                            'cquery': 1,
                            'mdata': 1,
                            'cdata': 1,
                            'orderpending': 1,
                        },
                        'post': {
                            'mdata': 1,
                        },
                    },
                    'private': {
                        'post': {
                            'credit': 1,
                            'cquery': 1,
                            'ctrade': 1,
                            'user': 1,
                            'orderpending': 1,
                            'transfer': 1,
                        },
                    },
                },
                'v1.1': {
                    'public': {
                        'get': [
                            'cquery',
                        ],
                    },
                    'private': {
                        'post': [
                            'cquery',
                            'ctrade',
                        ],
                    },
                },
                'v2': {
                    'public': {
                        'get': [
                            'mdata/kline',
                            'mdata/depth',
                        ],
                    },
                    'private': {
                        'post': [
                            'assets/transfer/spot',
                        ],
                    },
                },
                'v3': {
                    'public': {
                        'get': [
                            'mdata/ping',
                            'mdata/pairList',
                            'mdata/kline',
                            'mdata/marketAll',
                            'mdata/market',
                            'mdata/depth',
                            'mdata/deals',
                            'mdata/ticker',
                            'cbc/timestamp',
                            'cbu/timestamp',
                        ],
                    },
                    'private': {
                        'post': [
                            'assets/transfer/spot',
                            'assets/transfer/cbc',
                            'cbc/order/open',
                            'cbc/order/close',
                            'cbc/order/closeBatch',
                            'cbc/order/closeAll',
                            'cbc/changeMargin',
                            'cbc/changeMode',
                            'cbc/assets',
                            'cbc/position',
                            'cbc/order/list',
                            'cbc/order/detail',
                            'cbc/order/listBatch',
                            'cbc/order/listBatchByClientOid',
                            'cbuassets/transfer',
                            'cbu/order/open',
                            'cbu/order/close',
                            'cbu/order/closeBatch',
                            'cbu/order/closeAll',
                            'cbu/order/planOpen',
                            'cbu/order/planOrderList',
                            'cbu/order/planClose',
                            'cbu/order/planCloseAll',
                            'cbu/changeMargin',
                            'cbu/changeMode',
                            'cbu/assets',
                            'cbu/position',
                            'cbu/order/list',
                            'bu/order/detail',
                            'cbu/order/listBatch',
                            'cbu/order/listBatchByClientOid',
                        ],
                    },
                },
                'v3.1': {
                    'public': {
                        'get': [
                            'mdata/ping',
                            'cquery/buFundRate',
                            'cquery/buTagPrice',
                            'cquery/buValue',
                            'cquery/buUnit',
                            'cquery/bcFundRate',
                            'cquery/bcTagPrice',
                            'cquery/bcValue',
                            'cquery/bcUnit',
                        ],
                    },
                    'private': {
                        'get': [
                            'orderpending/tradeLimit',
                        ],
                        'post': [
                            'transfer/mainAssets',
                            'spot/account/assets',
                            'transfer/transferIn',
                            'transfer/transferOut',
                            'transfer/transferInList',
                            'transfer/transferOutList',
                            'transfer/coinConfig',
                            'transfer/withdrawInfo',
                            'orderpending/trade',
                            'orderpending/cancelTrade',
                            'orderpending/orderPendingList',
                            'orderpending/pendingHistoryList',
                            'orderpending/orderDetail',
                            'orderpending/order',
                            'orderpending/orderHistoryList',
                            'orderpending/orderDetailsLast',
                            'credit/transferAssets/base2credit',
                            'credit/transferAssets/credit2base',
                            'credit/lendOrder/get',
                            'credit/borrowOrder/get',
                            'credit/lendOrderbook/get',
                            'credit/transferAssets/lendAssets',
                            'credit/transferAssets/borrowAssets',
                            'credit/borrowOrder/autobook',
                            'credit/borrowOrder/refund',
                            'credit/lendOrderbook/publish',
                            'credit/lendOrderbook/cancel',
                            'credit/trade/trade',
                            'credit/trade/cancel',
                            'cquery/base_u/dealLog',
                            'cquery/base_u/orderDetail',
                            'cquery/base_u/orderHistory',
                            'cquery/base_u/orderById',
                            'cquery/base_coin/dealLog',
                            'cquery/base_coin/orderDetail',
                            'cquery/base_coin/orderHistory',
                            'cquery/base_coin/orderById',
                        ],
                    },
                },
                'v4': {
                    'public': {
                        'get': [
                            'marketdata/pairs',
                            'marketdata/order_book',
                            'marketdata/candles',
                            'marketdata/trades',
                            'marketdata/ticker',
                        ],
                    },
                    'private': {
                        'get': [
                            'userdata/accounts',
                            'userdata/ledger',
                            'userdata/order',
                            'userdata/orders',
                            'userdata/fills',
                        ],
                        'post': [
                            'userdata/order',
                        ],
                        'delete': [
                            'userdata/order',
                            'userdata/orders',
                            'userdata/fills',
                        ],
                    },
                },
            },
            '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': {},
                },
            },
            'precisionMode': TICK_SIZE,
            '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
                '-2004': InvalidOrder,  # Invalid parameter 'price': price limit
                '-2102': RateLimitExceeded,  # The usage limit is 10000 in 10000ms, but 10296 have been used.
            },
            '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',
            },
            'options': {
                'typesByAccount': {
                    'base': 'main',
                    'credit': 'margin',
                },
            },
        })

    async 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
        """
        markets = await self.v4PublicGetMarketdataPairs(params)
        #
        #    [
        #        {
        #          symbol: 'STI_USDT',
        #          base: 'STI',
        #          quote: 'USDT',
        #          min_price: '0.000001',
        #          max_price: '100000000',
        #          min_quantity: '0.000001',
        #          max_quantity: '100000000',
        #          price_scale: '6',
        #          quantity_scale: '3',
        #          price_increment: '0.000001',
        #          quantity_increment: '0.001',
        #          min_order_value: '1'
        #        },
        #        ...
        #    ]
        #
        result = []
        for i in range(0, len(markets)):
            market = markets[i]
            id = self.safe_string(market, 'symbol')
            baseId = self.safe_string(market, 'base')
            quoteId = self.safe_string(market, 'quote')
            base = self.safe_currency_code(baseId)
            quote = self.safe_currency_code(quoteId)
            symbol = base + '/' + quote
            type = 'spot'
            spot = True
            amountPrecision = self.safe_string(market, 'quantity_scale')
            pricePrecision = self.safe_string(market, 'price_scale')
            result.append({
                'id': id,
                'symbol': symbol,
                'baseId': baseId,
                'quoteId': quoteId,
                'settleId': None,
                'base': base,
                'quote': quote,
                'settle': 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.parse_number(self.parse_precision(amountPrecision)),
                    'price': self.parse_number(self.parse_precision(pricePrecision)),
                },
                'limits': {
                    'leverage': {
                        'min': None,
                        'max': None,
                    },
                    'amount': {
                        'min': self.safe_number(market, 'min_quantity'),
                        'max': self.safe_number(market, 'max_quantity'),
                    },
                    'price': {
                        'min': self.safe_number(market, 'min_price'),
                        'max': self.safe_number(market, 'max_price'),
                    },
                    'cost': {
                        'min': self.safe_number(market, 'min_order_value'),
                        '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
        #
        # fetchTicker
        #
        #    {
        #        "s": "ADA_USDT",             # trading pair code
        #        "t": 1666143212000,          # 24 hour transaction count
        #        "o": 0.371735,               # opening price
        #        "h": 0.373646,               # highest price
        #        "l": 0.358383,               # lowest price
        #        "p": 0.361708,               # latest price
        #        "q": 8.1,                    # latest volume
        #        "v": 1346397.88,             # 24 hour volume
        #        "a": 494366.08822867,        # 24 hour transaction value
        #        "c": -0.0267,                # 24 hour Change
        #        "n": 244631,
        #        "f": 16641250,               # 24 hour first transaction id
        #        "bp": 0.361565,              # Best current bid price
        #        "bq": 4324.26,               # Best current bid quantity
        #        "ap": 0.361708,              # Best current ask price
        #        "aq": 7726.59                # Best current ask quantity
        #    }
        #
        # fetchTickers
        #
        #    {
        #        is_hide: '0',
        #        high_cny: '0.1094',
        #        amount: '5.34',
        #        coin_symbol: 'BIX',
        #        last: '0.00000080',
        #        currency_symbol: 'BTC',
        #        change: '+0.00000001',
        #        low_cny: '0.1080',
        #        base_last_cny: '0.10935854',
        #        area_id: '7',
        #        percent: '+1.27%',
        #        last_cny: '0.1094',
        #        high: '0.00000080',
        #        low: '0.00000079',
        #        pair_type: '0',
        #        last_usd: '0.0155',
        #        vol24H: '6697325',
        #        id: '1',
        #        high_usd: '0.0155',
        #        low_usd: '0.0153'
        #    }
        #
        timestamp = self.safe_integer_2(ticker, 'timestamp', 't')
        baseId = self.safe_string(ticker, 'coin_symbol')
        quoteId = self.safe_string(ticker, 'currency_symbol')
        marketId = self.safe_string(ticker, 's')
        if (marketId is None) and (baseId is not None) and (quoteId is not None):
            marketId = baseId + '_' + quoteId
        market = self.safe_market(marketId, market)
        last = self.safe_string_2(ticker, 'last', 'p')
        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_2(ticker, 'high', 'h'),
            'low': self.safe_string_2(ticker, 'low', 'l'),
            'bid': self.safe_string(ticker, 'bp'),
            'bidVolume': self.safe_string(ticker, 'bq'),
            'ask': self.safe_string(ticker, 'ap'),
            'askVolume': self.safe_string(ticker, 'aq'),
            'vwap': None,
            'open': self.safe_string(ticker, 'o'),
            'close': last,
            'last': last,
            'previousClose': None,
            'change': self.safe_string(ticker, 'change'),
            'percentage': percentage,
            'average': None,
            'baseVolume': self.safe_string_2(ticker, 'a', 'vol24H'),
            'quoteVolume': self.safe_string_2(ticker, 'v', 'amount'),
            'info': ticker,
        }, market)

    async 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
        see https://biboxcom.github.io/api/spot/v4/en/#get-tickers
        :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>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.v4PublicGetMarketdataTicker(self.extend(request, params))
        #
        #    [
        #        {
        #            "s": "ADA_USDT",             # trading pair code
        #            "t": 1666143212000,          # 24 hour transaction count
        #            "o": 0.371735,               # opening price
        #            "h": 0.373646,               # highest price
        #            "l": 0.358383,               # lowest price
        #            "p": 0.361708,               # latest price
        #            "q": 8.1,                    # latest volume
        #            "v": 1346397.88,             # 24 hour volume
        #            "a": 494366.08822867,        # 24 hour transaction value
        #            "c": -0.0267,                # 24 hour Change
        #            "n": 244631,
        #            "f": 16641250,               # 24 hour first transaction id
        #            "bp": 0.361565,              # Best current bid price
        #            "bq": 4324.26,               # Best current bid quantity
        #            "ap": 0.361708,              # Best current ask price
        #            "aq": 7726.59                # Best current ask quantity
        #        }
        #    ]
        #
        ticker = self.safe_value(response, 0)
        return self.parse_ticker(ticker, market)

    async def fetch_tickers(self, symbols=None, params={}):
        """
        v1, 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>`
        """
        await self.load_markets()
        symbols = self.market_symbols(symbols)
        request = {
            'cmd': 'marketAll',
        }
        response = await self.v1PublicGetMdata(self.extend(request, params))
        #
        #    {
        #        result: [
        #            {
        #                is_hide: '0',
        #                high_cny: '0.1094',
        #                amount: '5.34',
        #                coin_symbol: 'BIX',
        #                last: '0.00000080',
        #                currency_symbol: 'BTC',
        #                change: '+0.00000001',
        #                low_cny: '0.1080',
        #                base_last_cny: '0.10935854',
        #                area_id: '7',
        #                percent: '+1.27%',
        #                last_cny: '0.1094',
        #                high: '0.00000080',
        #                low: '0.00000079',
        #                pair_type: '0',
        #                last_usd: '0.0155',
        #                vol24H: '6697325',
        #                id: '1',
        #                high_usd: '0.0155',
        #                low_usd: '0.0153'
        #            },
        #            ...
        #        ],
        #        cmd: 'marketAll',
        #        ver: '1.1'
        #    }
        #
        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)

    async 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>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'cmd': 'deals',
            'pair': market['id'],
        }
        if limit is not None:
            request['size'] = limit  # default = 200
        response = await self.v1PublicGetMdata(self.extend(request, params))
        return self.parse_trades(response['result'], market, since, limit)

    async def fetch_order_book(self, symbol, limit=None, params={}):
        """
        see https://biboxcom.github.io/api/spot/v4/en/#get-order-book
        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: *default=100* valid values include 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000
        :param dict params: extra parameters specific to the bibox api endpoint
         *
         * EXCHANGE SPECIFIC PARAMETERS
        :param int|None price_scale: *default=0* depth of consolidation by price, valid values include 0, 1, 2, 3, 4, 5
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbols
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            allowedValues = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000]
            if not self.in_array(limit, allowedValues):
                raise BadRequest(self.id + ' fetchOrderBook limit argument by only be one of 1, 2, 5, 10, 20, 50, 100, 200, 500 or 1000')
            request['level'] = limit
        response = await self.v4PublicGetMarketdataOrderBook(self.extend(request, params))
        #
        #    {
        #        i: '1917961902',                  # update id
        #        t: '1666221729812',               # update time
        #        b: [                             # buy orders
        #            [
        #                '0.350983',               # order price
        #                '8760.69'                 # order amount
        #            ],
        #            ...
        #        ],
        #        a: [                             # sell orders
        #            [
        #                '0.351084',
        #                '14241.62'
        #            ],
        #            ...
        #        ]
        #    }
        #
        return self.parse_order_book(response, market['symbol'], self.safe_integer(response, 't'), 'b', 'a')

    def parse_ohlcv(self, ohlcv, market=None):
        #
        #    [
        #        '1656702000000',      # start time
        #        '19449.4',            # opening price
        #        '19451.7',            # maximum price
        #        '19290.6',            # minimum price
        #        '19401.5',            # closing price
        #        '73.328833',          # transaction volume
        #        '1419466.3805812',    # transaction value
        #        '45740585',           # first transaction id
        #        2899                  # The total number of transactions in the range
        #    ]
        #
        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),
        ]

    async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
        """
        see https://biboxcom.github.io/v3/spotv4/en/#get-candles
        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
        :param int|None params['until']: timestamp in ms of the latest candle to fetch
        :returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume
        """
        await self.load_markets()
        market = self.market(symbol)
        until = self.safe_integer(params, 'until')
        request = {
            'symbol': market['id'],
            'time_frame': self.timeframes[timeframe],
        }
        if limit is not None:
            request['limit'] = limit
        if since is not None and until is not None:
            raise BadRequest(self.id + ' fetchOHLCV cannot take both a since parameter and params["until"]')
        elif since is not None:
            request['after'] = since
        elif until is not None:
            request['before'] = until
        response = await self.v4PublicGetMarketdataCandles(self.extend(request, params))
        #
        #    {
        #        t: '3600000',
        #        e: [
        #            [
        #                '1656702000000',      # start time
        #                '19449.4',            # opening price
        #                '19451.7',            # maximum price
        #                '19290.6',            # minimum price
        #                '19401.5',            # closing price
        #                '73.328833',          # transaction volume
        #                '1419466.3805812',    # transaction value
        #                '45740585',           # first transaction id
        #                2899                  # The total number of transactions in the range
        #            ],
        #            ...
        #    }
        #
        result = self.safe_value(response, 'e')
        if result is None:
            result = response or []
        return self.parse_ohlcvs(result, market, timeframe, since, limit)

    async 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 await self.fetch_currencies_private(params)
        else:
            return await self.fetch_currencies_public(params)

    async def fetch_currencies_public(self, params={}):
        request = {
            'cmd': 'currencies',
        }
        response = await self.v1PublicGetCdata(self.extend(request, params))
        #
        # v1PublicGetCdata
        #
        #     {
        #         "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 Satoshi Nakamoto 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.parse_number(self.parse_precision(self.safe_string(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': precision,
                        'max': None,
                    },
                    'withdraw': {
                        'min': self.safe_number(currency, 'withdraw_min'),
                        'max': None,
                    },
                },
            }
        return result

    async 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 = await self.v1PrivatePostTransfer(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 = self.parse_number('0.00000001')
            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': precision,
                        'max': None,
                    },
                    'withdraw': {
                        'min': None,
                        'max': None,
                    },
                },
            }
        return result

    def parse_balance(self, response):
        #
        #    [
        #        {
        #            "s": "USDT",              # asset code
        #            "a": 2.6617573979,        # available amount
        #            "h": 0                    # frozen amount
        #        },
        #        ...
        #    ]
        #
        result = {'info': response}
        for i in range(0, len(response)):
            balance = response[i]
            currencyId = self.safe_string(balance, 's')
            code = self.safe_currency_code(currencyId)
            account = self.account()
            account['free'] = self.safe_string(balance, 'a')
            account['used'] = self.safe_string(balance, 'h')
            result[code] = account
        return self.safe_balance(result)

    async def fetch_balance(self, params={}):
        """
        query for balance and get the amount of funds available for trading or funds locked in orders
        see https://biboxcom.github.io/api/spot/v4/en/#get-accounts
        :param dict params: extra parameters specific to the bibox api endpoint
        :param str params['code']: unified currency code
        :returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>`
        """
        await self.load_markets()
        code = self.safe_string(params, 'code')
        params = self.omit(params, 'code')
        request = {}
        if code is not None:
            currency = self.currency(code)
            request['asset'] = currency['id']
        response = await self.v4PrivateGetUserdataAccounts(self.extend(request, params))
        #
        #    [
        #        {
        #            "s": "USDT",              # asset code
        #            "a": 2.6617573979,        # available amount
        #            "h": 0                    # frozen amount
        #        },
        #        ...
        #    ]
        #
        return self.parse_balance(response)

    def parse_ledger_entry(self, item, currency=None):
        #
        #    {
        #        "i": 1125899918063693495,     # entry id
        #        "s": "USDT",                  # asset symbol
        #        "T": "transfer_in",           # entry type: transfer, trade, fee
        #        "a": 14.71,                   # amount
        #        "b": 14.7100000044,           # balance
        #        "t": 1663367640374            # time
        #    }
        #
        ledgerTypes = {
            'transfer_in': 'transfer',
            'transfer_out': 'transfer',
            'trade_finish_ask': 'trade',
            'trade_finish_bid': 'trade',
        }
        id = self.safe_string(item, 'i')
        currencyId = self.safe_string(item, 's')
        type = self.safe_string(item, 'T')
        timestamp = self.safe_integer(item, 't')
        amount = self.safe_string(item, 'a')
        direction = 'in'
        if Precise.string_lt(amount, '0'):
            direction = 'out'
        return {
            'id': id,
            'direction': direction,
            'account': None,
            'referenceId': id,
            'referenceAccount': None,
            'type': self.safe_string(ledgerTypes, type, type),
            'currency': self.safe_currency_code(currencyId, currency),
            'amount': self.parse_number(amount),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'before': None,
            'after': self.safe_number(item, 'b'),
            'status': None,
            'fee': None,
            'info': item,
        }

    async def fetch_ledger(self, code=None, since=None, limit=None, params={}):
        """
        fetch the history of changes, actions done by the user or operations that altered balance of the user
        see https://biboxcom.github.io/api/spot/v4/en/#get-an-account-39-s-ledger
        :param str|None code: unified currency code, default is None
        :param int|None since: timestamp in ms of the earliest ledger entry, default is None
        :param int|None limit: *default = 100* max number of ledger entrys to return
        :param dict params: extra parameters specific to the bitfinex2 api endpoint
        :param int params['until']: timestamp in ms of the latest ledger entry, default is None
         *
         * EXCHANGE SPECIFIC PARAMETERS
        :param int before: bill record id. limited to return the maximum id value of the bill records
        :param int after: bill record id, limited to return the minimum id value of the bill records
        :returns dict: a `ledger structure <https://docs.ccxt.com/en/latest/manual.html#ledger-structure>`
        """
        await self.load_markets()
        currency = None
        until = self.safe_integer(params, 'until')
        params = self.omit(params, 'until')
        request = {}
        if code is not None:
            currency = self.currency(code)
            request['asset'] = currency['id']
        if since is not None:
            request['start_time'] = since
        if limit is not None:
            request['limit'] = limit
        if until is not None:
            request['end_time'] = until
        response = await self.v4PrivateGetUserdataLedger(self.extend(request, params))
        #
        #    [
        #        {
        #            "i": 1125899918063693495,     # entry id
        #            "s": "USDT",                  # asset symbol
        #            "T": "transfer_in",           # entry type: transfer, trade, fee
        #            "a": 14.71,                   # amount
        #            "b": 14.7100000044,           # balance
        #            "t": 1663367640374            # time
        #        }
        #    ]
        #
        return self.parse_ledger(response, currency, since, limit)

    async 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: not used by bibox
        :param int|None limit: the maximum number of deposits structures to retrieve, max=50, default=50
        :param dict params: extra parameters specific to the bibox api endpoint
         *
         * EXCHANGE SPECIFIC PARAMETERS
        :param int params['page']: page number, default=1
        :param str|None params['filter_type']: deposit record filter, 0-all, 1-deposit in progress, 2-deposit received, 3-deposit failed
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        await self.load_markets()
        if limit is None:
            limit = 50
        page = self.safe_integer(params, 'page', 1)
        request = {
            'page': page,
            'size': limit,
        }
        currency = None
        if code is not None:
            currency = self.currency(code)
            request['coin_symbol'] = currency['id']
        method = 'v3.1PrivatePostTransferTransferInList'
        response = await getattr(self, method)(self.extend(request, params))
        #
        #    {
        #        result: {
        #            count: '5',
        #            page: '1',
        #            items: [
        #                {
        #                    id: '3553023',
        #                    coin_symbol: 'bUSDT',
        #                    chain_type: 'BEP20(BSC)',
        #                    to_address: '0xf1458ba28073b056e9666c4b2bbbc60451cda0fd',
        #                    tx_id: '0x2f2319c4ae804893369aeeeef06dd429abf2833b61290ea2bd63ec0e363ebce6',
        #                    amount: '14.71000000',
        #                    confirmCount: '14',
        #                    createdAt: '1663367581000',
        #                    status: '2'
        #                },
        #                ...
        #            ]
        #        },
        #        cmd: 'transferInList',
        #        state: '0'
        #    }
        #
        result = self.safe_value(response, 'result')
        items = self.safe_value(result, 'items')
        for i in range(0, len(items)):
            items[i]['type'] = 'deposit'
        return self.parse_transactions(items, currency, since, limit)

    async 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 bibox api endpoint
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        await 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 = await self.v1PrivatePostTransfer({
            '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_integer(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)

    async def create_order(self, symbol, type, side, amount, price=None, params={}):
        """
        create a trade order
        see https://biboxcom.github.io/api/spot/v4/en/#create-an-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 bibox api endpoint
        :param bool|None params['postOnly']: True or False
        :param str|None params['timeInForce']: gtc or ioc
        :param str|None params['clientOrderId']: client order id
        :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        type = type.lower()
        if type == 'market':
            raise BadRequest(self.id + ' createOrder() does not support market orders, only limit orders are allowed')
        elif price is None:
            raise ArgumentsRequired(self.id + ' createOrder() requires a price argument for limit orders')
        request = {
            'symbol': market['id'],
            'side': side,
            'type': type,
            'quantity': self.amount_to_precision(symbol, amount),
            'price': self.price_to_precision(symbol, price),
        }
        timeInForce = self.safe_string_lower(params, 'timeInForce')
        if timeInForce is not None:
            request['time_in_force'] = timeInForce
        postOnly = self.is_post_only(False, None, params)
        if postOnly:
            request['post_only'] = postOnly
        clientOrderId = self.safe_string(params, 'clientOrderId')
        if clientOrderId is not None:
            request['client_order_id'] = clientOrderId
        params = self.omit(params, ['postOnly', 'timeInForce', 'clientOrderId'])
        response = await self.v4PrivatePostUserdataOrder(self.deep_extend(request, params))
        #
        #     {
        #         "i": 14580623695947906,
        #         "I": "0",
        #         "m": "LUNC_USDT",
        #         "T": "limit",
        #         "s": "sell",
        #         "Q": -1015236.00000,
        #         "P": 0.0002900000,
        #         "t": "gtc",
        #         "o": False,
        #         "S": "accepted",
        #         "E": 0,
        #         "e": 0,
        #         "C": 1665670398046,
        #         "U": 1665670398046,
        #         "V": 582952205212,
        #         "n": 0,
        #         "F": [],
        #         "f": []
        #     }
        #
        return self.parse_order(response, market)

    async def cancel_all_orders(self, symbol=None, params={}):
        """
        cancels all open orders
        :param str symbol: unified market symbol
        :param dict params: extra parameters specific to the bibox api endpoint
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        if symbol is None:
            raise ArgumentsRequired(self.id + ' cancelAllOrders requires a symbol argument')
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.v4PrivateDeleteUserdataOrders(self.extend(request, params))
        #
        # []
        #
        return self.parse_orders(response, market)

    async def cancel_order(self, id, symbol=None, params={}):
        """
        cancels an open order
        :param str id: order id
        :param str|None symbol: not used by bibox cancelOrder()
        :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>`
        """
        request = {
            'id': id,
        }
        response = await self.v4PrivateDeleteUserdataOrder(self.extend(request, params))
        #
        #    {
        #        "i": 4611688217450643477,  # The order id assigned by the exchange
        #        "I": "",  # User specified order id
        #        "m": "BTC_USDT",  # trading pair code
        #        "T": "limit",  # order type
        #        "s": "sell",  # order direction
        #        "Q": -0.0100,  # Order amount
        #        "P": 10043.8500,  # order price
        #        "t": "gtc",  # Time In Force
        #        "o": False,  # Post Only
        #        "S": "filled",  # order status
        #        "E": -0.0100,  # transaction volume
        #        "e": -100.43850000,  # transaction value
        #        "C": 1643193746043,  # creation time
        #        "U": 1643193746464,  # update time
        #        "n": 2,  # number of transactions
        #        "F": [
        #            {
        #                "i": 13,  # deal id
        #                "t": 1643193746464,  # transaction time
        #                "p": 10043.85,  # transaction price
        #                "q": -0.009,  # transaction volume
        #                "l": "maker",  # Maker / Taker transaction
        #                "f": {
        #                    "a": "USDT",  # This transaction is used to pay the transaction fee
        #                    "m": 0.09039465000  # The handling fee for self transaction
        #                }
        #            },
        #            {
        #                "i": 12,
        #                "t": 1643193746266,
        #                "p": 10043.85,
        #                "q": -0.001,
        #                "l": "maker",
        #                "f": {
        #                        "a": "USDT",
        #                        "m": 0.01004385000
        #                    }
        #                }
        #        ],
        #        "f": [
        #            {
        #                "a": "USDT",  # Assets used to pay fees
        #                "m": 0.10043850000  # Total handling fee
        #            }
        #        ]
        #    }
        #
        return self.parse_order(response)

    async def fetch_order(self, id, symbol=None, params={}):
        """
        fetches information on an order made by the user
        :param str|None symbol: not used by bibox fetchOrder
        :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>`
        """
        await self.load_markets()
        request = {
            'id': id,
        }
        response = await self.v4PrivateGetUserdataOrder(self.extend(request, params))
        #
        #    {
        #        i: '14580623696203099',       # the order id assigned by the exchange
        #        I: '0',                       # user specified order id
        #        m: 'ADA_USDT',                # trading pair code
        #        T: 'limit',                   # order type
        #        s: 'buy',                     # order direction
        #        Q: '4.000000',                # order amount
        #        P: '0.300000',                # order price
        #        t: 'gtc',                     # time in force
        #        o: False,                     # post only
        #        S: 'accepted',                # order status
        #        E: '0',                       # transaction volume
        #        e: '0',                       # transaction value
        #        C: '1666235804233',           # creation time
        #        U: '1666235804233',           # update time
        #        V: '586925436933',
        #        n: '0',                       # number of transactions
        #        F: [
        #            {
        #                i: 13,                # transaction id
        #                t: 1643193746464,     # transaction time
        #                p: 10043.85,          # transaction price
        #                q: -0.009,            # transaction volume
        #                l: "maker",           # maker / taker transaction
        #                f: {
        #                    a: "USDT",        # the asset used for the transaction to pay the handling fee
        #                    m: 0.09039465000  # the transaction fee
        #                }
        #            },
        #            ...
        #        ],
        #        f: [
        #            {
        #                a: "USDT",            # Assets used to pay fees
        #                m: 0.10043850000      # Total handling fee
        #            }
        #        ]
        #    }
        #
        return self.parse_order(response)

    def parse_order(self, order, market=None):
        #
        #    {
        #        i: '14580623696203099',       # the order id assigned by the exchange
        #        I: '0',                       # user specified order id
        #        m: 'ADA_USDT',                # trading pair code
        #        T: 'limit',                   # order type
        #        s: 'buy',                     # order direction
        #        Q: '4.000000',                # order amount
        #        P: '0.300000',                # order price
        #        t: 'gtc',                     # time in force
        #        o: False,                     # post only
        #        S: 'accepted',                # order status
        #        E: '0',                       # transaction volume
        #        e: '0',                       # transaction value
        #        C: '1666235804233',           # creation time
        #        U: '1666235804233',           # update time
        #        V: '586925436933',
        #        n: '0',                       # number of transactions
        #        F: [
        #            {
        #                i: 13,                # transaction id
        #                t: 1643193746464,     # transaction time
        #                p: 10043.85,          # transaction price
        #                q: -0.009,            # transaction volume
        #                l: "maker",           # maker / taker transaction
        #                f: {
        #                    a: "USDT",        # the asset used for the transaction to pay the handling fee
        #                    m: 0.09039465000  # the transaction fee
        #                }
        #            },
        #            ...
        #        ],
        #        f: [
        #            {
        #                a: "USDT",            # Assets used to pay fees
        #                m: 0.10043850000      # Total handling fee
        #            }
        #        ]
        #    }
        #
        marketId = self.safe_string(order, 'm')
        market = self.safe_market(marketId, market)
        timestamp = self.safe_integer(order, 'C')
        amount = self.safe_string(order, 'Q')
        amount = Precise.string_abs(amount)
        side = self.safe_string(order, 's')
        fees = []
        orderFees = self.safe_value(order, 'f', [])
        for i in range(0, len(orderFees)):
            fees.append({
                'currency': self.safe_currency_code(self.safe_string(orderFees[i], 'a')),
                'cost': self.safe_string(orderFees[i], 'm'),
            })
        transactions = self.safe_value(order, 'F')
        trades = []
        for i in range(0, len(transactions)):
            trade = self.parse_trade(transactions[i])
            trades.append(trade)
        return self.safe_order({
            'info': order,
            'id': self.safe_string(order, 'i'),
            'clientOrderId': self.omit_zero(self.safe_string(order, 'I')),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'symbol': market['symbol'],
            'type': self.safe_string(order, 'T'),
            'timeInForce': self.safe_string_upper(order, 't'),
            'postOnly': self.safe_value(order, 'o'),
            'side': side,
            'price': self.safe_string(order, 'P'),
            'stopPrice': None,
            'amount': amount,
            'cost': self.safe_string(order, 'e'),
            'average': None,
            'filled': self.safe_string(order, 'E'),
            'remaining': None,
            'status': self.parse_order_status(self.safe_string(order, 'S')),
            'fee': self.safe_value(fees, 0),
            'fees': fees,
            'trades': trades,
        }, market)

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

    async def fetch_orders_by_status(self, status, symbol=None, since=None, limit=None, params={}):
        """
        fetch all unfilled currently open orders
         * @param status open or closed
        :param str|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch orders for
        :param int|None limit: the maximum number of  open orders structures to retrieve
        :param dict params: extra parameters specific to the bibox api endpoint
        :param int params['until']: the latest time in ms to fetch orders for
         *
         * EXCHANGE SPECIFIC PARMETERS
        :param str params['before']: order update id limited to return the maximum update id of the order
        :param str params['after']: delegate update id limited to return the minimum update id of the order
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        request = {}
        market = None
        until = self.safe_integer(params, 'until')
        open = (status == 'open')
        unsettled = (status == 'unsettled')
        params = self.omit(params, 'until')
        if until is not None:              # The order of request parameters must go end_time -> limit -> start_time -> status -> symbol
            request['end_time'] = until
        if limit is not None:
            request['limit'] = limit
        if since is not None:
            request['start_time'] = since
        request['status'] = 'unsettled' if (open or unsettled) else 'settled'
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        response = await self.v4PrivateGetUserdataOrders(self.extend(request, params))
        #
        #    [
        #        {
        #            "i": 14589419788970785,
        #            "I": "0",
        #            "m": "ADA_USDT",
        #            "T": "limit",
        #            "s": "buy",
        #            "Q": 4.000000,
        #            "P": 0.300000,
        #            "t": "gtc",
        #            "o": False,
        #            "S": "accepted",
        #            "E": 0,
        #            "e": 0,
        #            "C": 1666373682656,
        #            "U": 1666373682656,
        #            "V": 587932155076,
        #            "n": 0,
        #            "F": [],
        #            "f": []
        #        }
        #    ]
        #
        return self.parse_orders(response, market, since, limit)

    async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches information on multiple closed orders made by the user
        :param str 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 order structures to retrieve
        :param dict params: extra parameters specific to the bibox api endpoint
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        return await self.fetch_orders_by_status('open', symbol, since, limit, params)

    async def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches information on multiple closed orders made by the user
        :param str 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 bibox api endpoint
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchClosedOrders requires a symbol argument')
        return await self.fetch_orders_by_status('closed', symbol, since, limit, params)

    async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
        """
        fetch all trades made by the user
        :param str 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 bibox api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchMyTrades() requires a `symbol` argument')
        await 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 = await self.v1PrivatePostOrderpending(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)

    async 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 bibox api endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>`
        """
        await self.load_markets()
        currency = self.currency(code)
        request = {
            'cmd': 'transfer/transferIn',
            'body': self.extend({
                'coin_symbol': currency['id'],
            }, params),
        }
        response = await self.v1PrivatePostTransfer(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,
        }

    async def withdraw(self, code, amount, address, tag=None, params={}):
        """
        make a withdrawal
        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str|None tag:
        :param dict params: extra parameters specific to the bibox api endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        tag, params = self.handle_withdraw_tag_and_params(tag, params)
        self.check_address(address)
        await 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': self.password,
            'coin_symbol': currency['id'],
            'amount': amount,
            'addr': address,
        }
        if tag is not None:
            request['address_remark'] = tag
        response = await self.v1PrivatePostTransfer({
            '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)

    async def fetch_transaction_fees(self, codes=None, params={}):
        """
        fetch transaction fees
        :param [str]|None codes: list of unified currency codes
        :param dict params: extra parameters specific to the bibox api endpoint
        :returns [dict]: a list of `fee structures <https://docs.ccxt.com/en/latest/manual.html#fee-structure>`
        """
        # 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
        await 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 = await self.v1PrivatePostTransfer(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': {},
        }

    async def transfer(self, code, amount, fromAccount, toAccount, params={}):
        """
        transfer currency internally between wallets on the same account, transfers must be made to/from account "main"
        see https://biboxcom.github.io/api/spot/v3/en/#wallet-to-spot
        see https://biboxcom.github.io/api/spot/v3/en/#wallet-to-leverage
        see https://biboxcom.github.io/api/spot/v3/en/#leverage-to-wallet
        see https://biboxcom.github.io/api/futures/v3/en/#2-fund-transfer
        see https://biboxcom.github.io/api/futures-coin/v3/en/#2-fund-transfer
        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: main, spot, cross, swap or an isolated margin market symbol(ex: XRP/USDT)
        :param str toAccount: main, spot, cross, swap or an isolated margin market symbol(ex: XRP/USDT)
        :param dict params: extra parameters specific to the bibox api endpoint
        :returns dict: a `transfer structure <https://docs.ccxt.com/en/latest/manual.html#transfer-structure>`
        """
        await self.load_markets()
        currency = self.currency(code)
        fromMain = fromAccount == 'main' or fromAccount == 'wallet' or fromAccount == 'funding'
        fromSpot = fromAccount == 'spot'
        toMain = toAccount == 'main' or toAccount == 'wallet' or toAccount == 'funding'
        toSpot = toAccount == 'spot'
        toCross = toAccount == 'cross'
        fromCross = fromAccount == 'cross'
        toIsolated = self.in_array(toAccount, self.symbols)
        fromIsolated = self.in_array(fromAccount, self.symbols)
        toSwap = toAccount == 'swap'
        fromSwap = fromAccount == 'swap'
        method = 'v3PrivatePostAssetsTransferSpot'
        request = {
            'amount': amount,
        }
        if toSpot or fromSpot:
            request['symbol'] = currency['id']
            if fromMain:
                request['type'] = 0
            elif toMain:
                request['type'] = 1
            else:
                raise BadRequest(self.id + ' cannot transfer from ' + fromAccount + ' to ' + toAccount)
        elif (fromCross or fromIsolated) and toMain:
            method = 'v3.1PrivatePostCreditTransferAssetsCredit2base'
            request['coin_symbol'] = currency['id']
            request['pair'] = self.market_id(fromAccount) if fromIsolated else '*_USDT'
        elif (toCross or toIsolated) and fromMain:
            method = 'v3.1PrivatePostCreditTransferAssetsBase2credit'
            request['coin_symbol'] = currency['id']
            request['pair'] = self.market_id(toAccount) if toIsolated else '*_USDT'
        elif toSwap or fromSwap:
            if code == 'USDT':
                method = 'v3PrivatePostCbuassetsTransfer'
            else:
                method = 'v3PrivatePostAssetsTransferCbc'
            if toMain:
                request['type'] = 1
            elif fromMain:
                request['type'] = 0
            else:
                raise BadRequest(self.id + ' cannot transfer from ' + fromAccount + ' to ' + toAccount)
            request['symbol'] = currency['id']
        else:
            raise BadRequest(self.id + ' cannot transfer from ' + fromAccount + ' to ' + toAccount)
        response = await getattr(self, method)(self.extend(request, params))
        #
        # spot <-> main
        #
        #    {
        #        state: '0',
        #        id: '936177661049344000'
        #    }
        #
        # main <-> leverage
        #
        #    {
        #        result: '1620000000049',
        #        cmd: 'transferAssets/base2credit',
        #        state: '0'
        #    }
        #
        # main <-> swap
        #
        #    {
        #        state: '0',
        #        result: '936190233517527040'
        #    }
        #
        return self.parse_transfer(response, currency)

    def parse_transfer(self, transfer, currency=None):
        #
        # spot <-> main
        #
        #    {
        #        state: '0',
        #        id: '936177661049344000'
        #    }
        #
        # main <-> leverage
        #
        #    {
        #        result: '1620000000049',
        #        cmd: 'transferAssets/base2credit',
        #        state: '0'
        #    }
        #
        # main <-> swap
        #
        #    {
        #        state: '0',
        #        result: '936190233517527040'
        #    }
        #
        cmd = self.safe_string(transfer, 'cmd')
        fromAccount = None
        toAccount = None
        if cmd is not None:
            accounts = self.safe_string(cmd.split('/'), 1)
            parts = accounts.split('2')
            fromAccount = self.safe_string(parts, 0)
            toAccount = self.safe_string(parts, 1)
            fromAccount = self.safe_string(self.options['typesByAccount'], fromAccount, fromAccount)
            toAccount = self.safe_string(self.options['typesByAccount'], toAccount, toAccount)
        return {
            'info': transfer,
            'id': self.safe_string_2(transfer, 'id', 'result'),
            'timestamp': None,
            'datetime': None,
            'currency': self.safe_string(currency, 'code'),
            'amount': None,
            'fromAccount': fromAccount,
            'toAccount': toAccount,
            'status': None,
        }

    def sign(self, path, api='v1Public', method='GET', params={}, headers=None, body=None):
        version, access = api
        v1 = (version == 'v1')
        v4 = (version == 'v4')
        prefix = '/api' if v4 else ''
        url = self.implode_hostname(self.urls['api']['rest']) + prefix + '/' + version + '/' + path
        jsonParams = self.json([params]) if v1 else self.json(params)
        headers = {'content-type': 'application/json'}
        if access == 'public':
            if method != 'GET':
                if v1:
                    body = {'cmds': jsonParams}
                else:
                    body = {'body': jsonParams}
            elif params:
                url += '?' + self.urlencode(params)
        else:
            self.check_required_credentials()
            if version == 'v3' or version == 'v3.1':
                timestamp = self.number_to_string(self.milliseconds())
                strToSign = timestamp
                if jsonParams != '{}':
                    strToSign += jsonParams
                sign = self.hmac(self.encode(strToSign), self.encode(self.secret), hashlib.md5)
                headers['bibox-api-key'] = self.apiKey
                headers['bibox-api-sign'] = sign
                headers['bibox-timestamp'] = timestamp
                if method == 'GET':
                    url += '?' + self.urlencode(params)
                else:
                    if jsonParams != '{}':
                        body = params
            elif v4:
                strToSign = ''
                sortedParams = self.keysort(params)
                if method == 'GET':
                    url += '?' + self.urlencode(sortedParams)
                    strToSign = self.urlencode(sortedParams)
                else:
                    if jsonParams != '{}':
                        body = sortedParams
                    strToSign = self.json(body, {'convertArraysToObjects': True})
                sign = self.hmac(self.encode(strToSign), self.encode(self.secret), hashlib.sha256)
                headers['Bibox-Api-Key'] = self.apiKey
                headers['Bibox-Api-Sign'] = sign
            else:
                sign = self.hmac(self.encode(jsonParams), self.encode(self.secret), hashlib.md5)
                body = {
                    'apikey': self.apiKey,
                    'sign': sign,
                }
                if v1:
                    body['cmds'] = jsonParams
                else:
                    body['body'] = jsonParams
        if body is not None:
            body = self.json(body, {'convertArraysToObjects': True})
        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 'state' in response:
            if self.safe_number(response, 'state') == 0:
                return
            raise ExchangeError(self.id + ' ' + body)
        if 'error' in response:
            if isinstance(response['error'], dict):
                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)
            else:
                code = self.safe_string(response, 'error')
                feedback = self.id + ' ' + body
                self.throw_exactly_matched_exception(self.exceptions, code, feedback)
                raise ExchangeError(feedback)
