<?php

namespace ccxt\async;

// 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

use Exception; // a common import
use ccxt\async\abstract\bitopro as Exchange;
use ccxt\ExchangeError;
use ccxt\ArgumentsRequired;
use ccxt\InvalidOrder;
use ccxt\Precise;
use \React\Async;
use \React\Promise\PromiseInterface;

class bitopro extends Exchange {

    public function describe(): mixed {
        return $this->deep_extend(parent::describe(), array(
            'id' => 'bitopro',
            'name' => 'BitoPro',
            'countries' => array( 'TW' ), // Taiwan
            'version' => 'v3',
            'rateLimit' => 100,
            'pro' => true,
            'has' => array(
                'CORS' => null,
                'spot' => true,
                'margin' => false,
                'swap' => false,
                'future' => false,
                'option' => false,
                'addMargin' => false,
                'borrowCrossMargin' => false,
                'borrowIsolatedMargin' => false,
                'borrowMargin' => false,
                'cancelAllOrders' => true,
                'cancelOrder' => true,
                'cancelOrders' => true,
                'closeAllPositions' => false,
                'closePosition' => false,
                'createOrder' => true,
                'createOrderWithTakeProfitAndStopLoss' => false,
                'createOrderWithTakeProfitAndStopLossWs' => false,
                'createReduceOnlyOrder' => false,
                'createStopOrder' => true,
                'createTriggerOrder' => true,
                'editOrder' => false,
                'fetchBalance' => true,
                'fetchBorrowInterest' => false,
                'fetchBorrowRate' => false,
                'fetchBorrowRateHistories' => false,
                'fetchBorrowRateHistory' => false,
                'fetchBorrowRates' => false,
                'fetchBorrowRatesPerSymbol' => false,
                'fetchClosedOrders' => true,
                'fetchCrossBorrowRate' => false,
                'fetchCrossBorrowRates' => false,
                'fetchCurrencies' => true,
                'fetchDepositAddress' => false,
                'fetchDeposits' => true,
                'fetchDepositsWithdrawals' => false,
                'fetchDepositWithdrawFee' => 'emulated',
                'fetchDepositWithdrawFees' => true,
                'fetchFundingHistory' => false,
                'fetchFundingInterval' => false,
                'fetchFundingIntervals' => false,
                'fetchFundingRate' => false,
                'fetchFundingRateHistory' => false,
                'fetchFundingRates' => false,
                'fetchGreeks' => false,
                'fetchIndexOHLCV' => false,
                'fetchIsolatedBorrowRate' => false,
                'fetchIsolatedBorrowRates' => false,
                'fetchIsolatedPositions' => false,
                'fetchLeverage' => false,
                'fetchLeverages' => false,
                'fetchLeverageTiers' => false,
                'fetchLiquidations' => false,
                'fetchLongShortRatio' => false,
                'fetchLongShortRatioHistory' => false,
                'fetchMarginAdjustmentHistory' => false,
                'fetchMarginMode' => false,
                'fetchMarginModes' => false,
                'fetchMarketLeverageTiers' => false,
                'fetchMarkets' => true,
                'fetchMarkOHLCV' => false,
                'fetchMarkPrices' => false,
                'fetchMyLiquidations' => false,
                'fetchMySettlementHistory' => false,
                'fetchMyTrades' => true,
                'fetchOHLCV' => true,
                'fetchOpenInterest' => false,
                'fetchOpenInterestHistory' => false,
                'fetchOpenInterests' => false,
                'fetchOpenOrders' => true,
                'fetchOption' => false,
                'fetchOptionChain' => false,
                'fetchOrder' => true,
                'fetchOrderBook' => true,
                'fetchOrders' => false,
                'fetchOrderTrades' => false,
                'fetchPosition' => false,
                'fetchPositionHistory' => false,
                'fetchPositionMode' => false,
                'fetchPositions' => false,
                'fetchPositionsForSymbol' => false,
                'fetchPositionsHistory' => false,
                'fetchPositionsRisk' => false,
                'fetchPremiumIndexOHLCV' => false,
                'fetchSettlementHistory' => false,
                'fetchTicker' => true,
                'fetchTickers' => true,
                'fetchTime' => false,
                'fetchTrades' => true,
                'fetchTradingFee' => false,
                'fetchTradingFees' => true,
                'fetchTransactionFees' => false,
                'fetchTransactions' => false,
                'fetchTransfer' => false,
                'fetchTransfers' => false,
                'fetchVolatilityHistory' => false,
                'fetchWithdrawal' => true,
                'fetchWithdrawals' => true,
                'reduceMargin' => false,
                'repayCrossMargin' => false,
                'repayIsolatedMargin' => false,
                'setLeverage' => false,
                'setMargin' => false,
                'setMarginMode' => false,
                'setPositionMode' => false,
                'transfer' => false,
                'withdraw' => true,
            ),
            'timeframes' => array(
                '1m' => '1m',
                '5m' => '5m',
                '15m' => '15m',
                '30m' => '30m',
                '1h' => '1h',
                '3h' => '3h',
                '6h' => '6h',
                '12h' => '12h',
                '1d' => '1d',
                '1w' => '1w',
                '1M' => '1M',
            ),
            'urls' => array(
                'logo' => 'https://github.com/user-attachments/assets/affc6337-b95a-44bf-aacd-04f9722364f6',
                'api' => array(
                    'rest' => 'https://api.bitopro.com/v3',
                ),
                'www' => 'https://www.bitopro.com',
                'doc' => array(
                    'https://github.com/bitoex/bitopro-offical-api-docs/blob/master/v3-1/rest-1/rest.md',
                ),
                'fees' => 'https://www.bitopro.com/fees',
            ),
            'requiredCredentials' => array(
                'apiKey' => true,
                'secret' => true,
            ),
            'api' => array(
                'public' => array(
                    'get' => array(
                        'order-book/{pair}' => 1,
                        'tickers' => 1,
                        'tickers/{pair}' => 1,
                        'trades/{pair}' => 1,
                        'provisioning/currencies' => 1,
                        'provisioning/trading-pairs' => 1,
                        'provisioning/limitations-and-fees' => 1,
                        'trading-history/{pair}' => 1,
                        'price/otc/{currency}' => 1,
                    ),
                ),
                'private' => array(
                    'get' => array(
                        'accounts/balance' => 1,
                        'orders/history' => 1,
                        'orders/all/{pair}' => 1,
                        'orders/trades/{pair}' => 1,
                        'orders/{pair}/{orderId}' => 1,
                        'wallet/withdraw/{currency}/{serial}' => 1,
                        'wallet/withdraw/{currency}/id/{id}' => 1,
                        'wallet/depositHistory/{currency}' => 1,
                        'wallet/withdrawHistory/{currency}' => 1,
                        'orders/open' => 1,
                    ),
                    'post' => array(
                        'orders/{pair}' => 1 / 2, // 1200/m => 20/s => 10/20 = 1/2
                        'orders/batch' => 20 / 3, // 90/m => 1.5/s => 10/1.5 = 20/3
                        'wallet/withdraw/{currency}' => 10, // 60/m => 1/s => 10/1 = 10
                    ),
                    'put' => array(
                        'orders' => 5, // 2/s => 10/2 = 5
                    ),
                    'delete' => array(
                        'orders/{pair}/{id}' => 2 / 3, // 900/m => 15/s => 10/15 = 2/3
                        'orders/all' => 5, // 2/s => 10/2 = 5
                        'orders/{pair}' => 5, // 2/s => 10/2 = 5
                    ),
                ),
            ),
            'fees' => array(
                'trading' => array(
                    'tierBased' => true,
                    'percentage' => true,
                    'maker' => $this->parse_number('0.001'),
                    'taker' => $this->parse_number('0.002'),
                    'tiers' => array(
                        'taker' => array(
                            array( $this->parse_number('0'), $this->parse_number('0.002') ),
                            array( $this->parse_number('3000000'), $this->parse_number('0.00194') ),
                            array( $this->parse_number('5000000'), $this->parse_number('0.0015') ),
                            array( $this->parse_number('30000000'), $this->parse_number('0.0014') ),
                            array( $this->parse_number('300000000'), $this->parse_number('0.0013') ),
                            array( $this->parse_number('550000000'), $this->parse_number('0.0012') ),
                            array( $this->parse_number('1300000000'), $this->parse_number('0.0011') ),
                        ),
                        'maker' => array(
                            array( $this->parse_number('0'), $this->parse_number('0.001') ),
                            array( $this->parse_number('3000000'), $this->parse_number('0.00097') ),
                            array( $this->parse_number('5000000'), $this->parse_number('0.0007') ),
                            array( $this->parse_number('30000000'), $this->parse_number('0.0006') ),
                            array( $this->parse_number('300000000'), $this->parse_number('0.0005') ),
                            array( $this->parse_number('550000000'), $this->parse_number('0.0004') ),
                            array( $this->parse_number('1300000000'), $this->parse_number('0.0003') ),
                        ),
                    ),
                ),
            ),
            'options' => array(
                'networks' => array(
                    'ERC20' => 'ERC20',
                    'ETH' => 'ERC20',
                    'TRX' => 'TRX',
                    'TRC20' => 'TRX',
                    'BEP20' => 'BSC',
                    'BSC' => 'BSC',
                ),
                'fiatCurrencies' => array( 'TWD' ), // the only fiat currency for exchange
            ),
            'features' => array(
                'spot' => array(
                    'sandbox' => false,
                    'createOrder' => array(
                        'marginMode' => false,
                        'triggerPrice' => true,
                        'triggerPriceType' => null,
                        'triggerDirection' => true, // todo implement
                        'stopLossPrice' => false,
                        'takeProfitPrice' => false,
                        'attachedStopLossTakeProfit' => null,
                        'timeInForce' => array(
                            'IOC' => false,
                            'FOK' => false,
                            'PO' => true,
                            'GTD' => false,
                        ),
                        'hedged' => false,
                        'trailing' => false,
                        'leverage' => false,
                        'marketBuyRequiresPrice' => false,
                        'marketBuyByCost' => false,
                        'selfTradePrevention' => false,
                        'iceberg' => false,
                    ),
                    'createOrders' => null,
                    'fetchMyTrades' => array(
                        'marginMode' => false,
                        'limit' => 1000,
                        'daysBack' => 100000,
                        'untilDays' => 100000,
                        'symbolRequired' => true,
                    ),
                    'fetchOrder' => array(
                        'marginMode' => false,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => true,
                    ),
                    // todo => implement through fetchOrders
                    'fetchOpenOrders' => array(
                        'marginMode' => false,
                        'limit' => null,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => false,
                    ),
                    'fetchOrders' => array(
                        'marginMode' => false,
                        'limit' => 1000,
                        'daysBack' => 100000,
                        'untilDays' => 100000,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => true,
                    ),
                    'fetchClosedOrders' => array(
                        'marginMode' => false,
                        'limit' => 1000,
                        'daysBack' => 100000,
                        'daysBackCanceled' => 1,
                        'untilDays' => 10000,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => true,
                    ),
                    'fetchOHLCV' => array(
                        'limit' => 1000,
                    ),
                ),
                'swap' => array(
                    'linear' => null,
                    'inverse' => null,
                ),
                'future' => array(
                    'linear' => null,
                    'inverse' => null,
                ),
            ),
            'precisionMode' => TICK_SIZE,
            'exceptions' => array(
                'exact' => array(
                    'Unsupported currency.' => '\\ccxt\\BadRequest', // array("error":"Unsupported currency.")
                    'Unsupported order type' => '\\ccxt\\BadRequest', // array("error":"Unsupported order type")
                    'Invalid body' => '\\ccxt\\BadRequest', // array("error":"Invalid body")
                    'Invalid Signature' => '\\ccxt\\AuthenticationError', // array("error":"Invalid Signature")
                    'Address not in whitelist.' => '\\ccxt\\BadRequest',
                ),
                'broad' => array(
                    'Invalid amount' => '\\ccxt\\InvalidOrder', // array("error":"Invalid amount 0.0000000001, decimal limit is 8.")
                    'Balance for ' => '\\ccxt\\InsufficientFunds', // array("error":"Balance for eth not enough, only has 0, but ordered 0.01.")
                    'Invalid ' => '\\ccxt\\BadRequest', // array("error":"Invalid price -1.")
                    'Wrong parameter' => '\\ccxt\\BadRequest', // array("error":"Wrong parameter => from")
                ),
            ),
            'commonCurrencies' => array(
            ),
        ));
    }

    public function fetch_currencies($params = array ()): PromiseInterface {
        return Async\async(function () use ($params) {
            /**
             * fetches all available $currencies on an exchange
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/public/get_currency_info.md
             *
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} an associative dictionary of $currencies
             */
            $response = Async\await($this->publicGetProvisioningCurrencies ($params));
            $currencies = $this->safe_list($response, 'data', array());
            //
            //     {
            //         "data":array(
            //             {
            //                 "currency":"eth",
            //                 "withdrawFee":"0.007",
            //                 "minWithdraw":"0.001",
            //                 "maxWithdraw":"1000",
            //                 "maxDailyWithdraw":"2000",
            //                 "withdraw":true,
            //                 "deposit":true,
            //                 "depositConfirmation":"12"
            //             }
            //         )
            //     }
            //
            $result = array();
            $fiatCurrencies = $this->safe_list($this->options, 'fiatCurrencies', array());
            for ($i = 0; $i < count($currencies); $i++) {
                $currency = $currencies[$i];
                $currencyId = $this->safe_string($currency, 'currency');
                $code = $this->safe_currency_code($currencyId);
                $deposit = $this->safe_bool($currency, 'deposit');
                $withdraw = $this->safe_bool($currency, 'withdraw');
                $fee = $this->safe_number($currency, 'withdrawFee');
                $withdrawMin = $this->safe_number($currency, 'minWithdraw');
                $withdrawMax = $this->safe_number($currency, 'maxWithdraw');
                $limits = array(
                    'withdraw' => array(
                        'min' => $withdrawMin,
                        'max' => $withdrawMax,
                    ),
                    'amount' => array(
                        'min' => null,
                        'max' => null,
                    ),
                );
                $isFiat = $this->in_array($code, $fiatCurrencies);
                $result[$code] = array(
                    'id' => $currencyId,
                    'code' => $code,
                    'info' => $currency,
                    'type' => $isFiat ? 'fiat' : 'crypto',
                    'name' => null,
                    'active' => $deposit && $withdraw,
                    'deposit' => $deposit,
                    'withdraw' => $withdraw,
                    'fee' => $fee,
                    'precision' => null,
                    'limits' => $limits,
                    'networks' => null,
                );
            }
            return $result;
        }) ();
    }

    public function fetch_markets($params = array ()): PromiseInterface {
        return Async\async(function () use ($params) {
            /**
             * retrieves data on all $markets for bitopro
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/public/get_trading_pair_info.md
             *
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array[]} an array of objects representing market data
             */
            $response = Async\await($this->publicGetProvisioningTradingPairs ());
            $markets = $this->safe_list($response, 'data', array());
            //
            //     {
            //         "data":array(
            //             {
            //                 "pair":"shib_twd",
            //                 "base":"shib",
            //                 "quote":"twd",
            //                 "basePrecision":"8",
            //                 "quotePrecision":"6",
            //                 "minLimitBaseAmount":"100000",
            //                 "maxLimitBaseAmount":"5500000000",
            //                 "minMarketBuyQuoteAmount":"1000",
            //                 "orderOpenLimit":"200",
            //                 "maintain":false,
            //                 "orderBookQuotePrecision":"6",
            //                 "orderBookQuoteScaleLevel":"5"
            //             }
            //         )
            //     }
            //
            return $this->parse_markets($markets);
        }) ();
    }

    public function parse_market(array $market): array {
        $active = !$this->safe_bool($market, 'maintain');
        $id = $this->safe_string($market, 'pair');
        $uppercaseId = strtoupper($id);
        $baseId = $this->safe_string($market, 'base');
        $quoteId = $this->safe_string($market, 'quote');
        $base = $this->safe_currency_code($baseId);
        $quote = $this->safe_currency_code($quoteId);
        $symbol = $base . '/' . $quote;
        $limits = array(
            'amount' => array(
                'min' => $this->safe_number($market, 'minLimitBaseAmount'),
                'max' => $this->safe_number($market, 'maxLimitBaseAmount'),
            ),
            'price' => array(
                'min' => null,
                'max' => null,
            ),
            'cost' => array(
                'min' => null,
                'max' => null,
            ),
            'leverage' => array(
                'min' => null,
                'max' => null,
            ),
        );
        return array(
            'id' => $id,
            'uppercaseId' => $uppercaseId,
            'symbol' => $symbol,
            'base' => $base,
            'quote' => $quote,
            'baseId' => $base,
            'quoteId' => $quote,
            'settle' => null,
            'settleId' => null,
            'type' => 'spot',
            'spot' => true,
            'margin' => false,
            'swap' => false,
            'future' => false,
            'option' => false,
            'contract' => false,
            'linear' => null,
            'inverse' => null,
            'contractSize' => null,
            'expiry' => null,
            'expiryDatetime' => null,
            'strike' => null,
            'optionType' => null,
            'limits' => $limits,
            'precision' => array(
                'price' => $this->parse_number($this->parse_precision($this->safe_string($market, 'quotePrecision'))),
                'amount' => $this->parse_number($this->parse_precision($this->safe_string($market, 'basePrecision'))),
            ),
            'active' => $active,
            'created' => null,
            'info' => $market,
        );
    }

    public function parse_ticker(array $ticker, ?array $market = null): array {
        //
        //     {
        //         "pair":"btc_twd",
        //         "lastPrice":"1182449.00000000",
        //         "isBuyer":false,
        //         "priceChange24hr":"-1.99",
        //         "volume24hr":"9.13089740",
        //         "high24hr":"1226097.00000000",
        //         "low24hr":"1181000.00000000"
        //     }
        //
        $marketId = $this->safe_string($ticker, 'pair');
        $market = $this->safe_market($marketId, $market);
        $symbol = $this->safe_string($market, 'symbol');
        return $this->safe_ticker(array(
            'symbol' => $symbol,
            'timestamp' => null,
            'datetime' => null,
            'high' => $this->safe_string($ticker, 'high24hr'),
            'low' => $this->safe_string($ticker, 'low24hr'),
            'bid' => null,
            'bidVolume' => null,
            'ask' => null,
            'askVolume' => null,
            'vwap' => null,
            'open' => null,
            'close' => $this->safe_string($ticker, 'lastPrice'),
            'last' => $this->safe_string($ticker, 'lastPrice'),
            'previousClose' => null,
            'change' => null,
            'percentage' => $this->safe_string($ticker, 'priceChange24hr'),
            'average' => null,
            'baseVolume' => $this->safe_string($ticker, 'volume24hr'),
            'quoteVolume' => null,
            'info' => $ticker,
        ), $market);
    }

    public function fetch_ticker(string $symbol, $params = array ()): PromiseInterface {
        return Async\async(function () use ($symbol, $params) {
            /**
             * fetches a price $ticker, a statistical calculation with the information calculated over the past 24 hours for a specific $market
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/public/get_ticker_data.md
             *
             * @param {string} $symbol unified $symbol of the $market to fetch the $ticker for
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} a ~@link https://docs.ccxt.com/#/?id=$ticker-structure $ticker structure~
             */
            Async\await($this->load_markets());
            $market = $this->market($symbol);
            $request = array(
                'pair' => $market['id'],
            );
            $response = Async\await($this->publicGetTickersPair ($this->extend($request, $params)));
            $ticker = $this->safe_dict($response, 'data', array());
            //
            //     {
            //         "data":{
            //             "pair":"btc_twd",
            //             "lastPrice":"1182449.00000000",
            //             "isBuyer":false,
            //             "priceChange24hr":"-1.99",
            //             "volume24hr":"9.13089740",
            //             "high24hr":"1226097.00000000",
            //             "low24hr":"1181000.00000000"
            //         }
            //     }
            //
            return $this->parse_ticker($ticker, $market);
        }) ();
    }

    public function fetch_tickers(?array $symbols = null, $params = array ()): PromiseInterface {
        return Async\async(function () use ($symbols, $params) {
            /**
             * fetches price $tickers for multiple markets, statistical information calculated over the past 24 hours for each market
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/public/get_ticker_data.md
             *
             * @param {string[]|null} $symbols unified $symbols of the markets to fetch the ticker for, all market $tickers are returned if not assigned
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} a dictionary of ~@link https://docs.ccxt.com/#/?id=ticker-structure ticker structures~
             */
            Async\await($this->load_markets());
            $response = Async\await($this->publicGetTickers ());
            $tickers = $this->safe_list($response, 'data', array());
            //
            //     {
            //         "data":array(
            //             {
            //                 "pair":"xrp_twd",
            //                 "lastPrice":"21.26110000",
            //                 "isBuyer":false,
            //                 "priceChange24hr":"-6.53",
            //                 "volume24hr":"102846.47084802",
            //                 "high24hr":"23.24460000",
            //                 "low24hr":"21.13730000"
            //             }
            //         )
            //     }
            //
            return $this->parse_tickers($tickers, $symbols);
        }) ();
    }

    public function fetch_order_book(string $symbol, ?int $limit = null, $params = array ()): PromiseInterface {
        return Async\async(function () use ($symbol, $limit, $params) {
            /**
             * fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/public/get_orderbook_data.md
             *
             * @param {string} $symbol unified $symbol of the $market to fetch the order book for
             * @param {int} [$limit] the maximum amount of order book entries to return
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} A dictionary of ~@link https://docs.ccxt.com/#/?id=order-book-structure order book structures~ indexed by $market symbols
             */
            Async\await($this->load_markets());
            $market = $this->market($symbol);
            $request = array(
                'pair' => $market['id'],
            );
            if ($limit !== null) {
                $request['limit'] = $limit;
            }
            $response = Async\await($this->publicGetOrderBookPair ($this->extend($request, $params)));
            //
            //     {
            //         "bids":array(
            //             {
            //                 "price":"1175271",
            //                 "amount":"0.00022804",
            //                 "count":1,
            //                 "total":"0.00022804"
            //             }
            //         ),
            //         "asks":array(
            //             {
            //                 "price":"1176906",
            //                 "amount":"0.0496",
            //                 "count":1,
            //                 "total":"0.0496"
            //             }
            //         )
            //     }
            //
            return $this->parse_order_book($response, $market['symbol'], null, 'bids', 'asks', 'price', 'amount');
        }) ();
    }

    public function parse_trade(array $trade, ?array $market = null): array {
        //
        // fetchTrades
        //         {
        //                 "timestamp":1644651458,
        //                 "price":"1180785.00000000",
        //                 "amount":"0.00020000",
        //                 "isBuyer":false
        //         }
        //
        // fetchMyTrades
        //         {
        //                 "tradeId":"5685030251",
        //                 "orderId":"9669168142",
        //                 "price":"11821.8",
        //                 "action":"SELL",
        //                 "baseAmount":"0.01",
        //                 "quoteAmount":"118.218",
        //                 "fee":"0.236436",
        //                 "feeSymbol":"BNB",
        //                 "isTaker":true,
        //                 "timestamp":1644905714862,
        //                 "createdTimestamp":1644905714862
        //         }
        //
        $id = $this->safe_string($trade, 'tradeId');
        $orderId = $this->safe_string($trade, 'orderId');
        $timestamp = null;
        if ($id === null) {
            $timestamp = $this->safe_timestamp($trade, 'timestamp');
        } else {
            $timestamp = $this->safe_integer($trade, 'timestamp');
        }
        $marketId = $this->safe_string($trade, 'pair');
        $market = $this->safe_market($marketId, $market);
        $symbol = $this->safe_string($market, 'symbol');
        $price = $this->safe_string($trade, 'price');
        $type = $this->safe_string_lower($trade, 'type');
        $side = $this->safe_string_lower($trade, 'action');
        if ($side === null) {
            $isBuyer = $this->safe_bool($trade, 'isBuyer');
            if ($isBuyer) {
                $side = 'buy';
            } else {
                $side = 'sell';
            }
        }
        $amount = $this->safe_string($trade, 'amount');
        if ($amount === null) {
            $amount = $this->safe_string($trade, 'baseAmount');
        }
        $fee = null;
        $feeAmount = $this->safe_string($trade, 'fee');
        $feeSymbol = $this->safe_currency_code($this->safe_string($trade, 'feeSymbol'));
        if ($feeAmount !== null) {
            $fee = array(
                'cost' => $feeAmount,
                'currency' => $feeSymbol,
                'rate' => null,
            );
        }
        $isTaker = $this->safe_bool($trade, 'isTaker');
        $takerOrMaker = null;
        if ($isTaker !== null) {
            if ($isTaker) {
                $takerOrMaker = 'taker';
            } else {
                $takerOrMaker = 'maker';
            }
        }
        return $this->safe_trade(array(
            'id' => $id,
            'info' => $trade,
            'order' => $orderId,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'symbol' => $symbol,
            'takerOrMaker' => $takerOrMaker,
            'type' => $type,
            'side' => $side,
            'price' => $price,
            'amount' => $amount,
            'cost' => null,
            'fee' => $fee,
        ), $market);
    }

    public function fetch_trades(string $symbol, ?int $since = null, ?int $limit = null, $params = array ()): PromiseInterface {
        return Async\async(function () use ($symbol, $since, $limit, $params) {
            /**
             * get the list of most recent $trades for a particular $symbol
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/public/get_trades_data.md
             *
             * @param {string} $symbol unified $symbol of the $market to fetch $trades for
             * @param {int} [$since] timestamp in ms of the earliest trade to fetch
             * @param {int} [$limit] the maximum amount of $trades to fetch
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {Trade[]} a list of ~@link https://docs.ccxt.com/#/?id=public-$trades trade structures~
             */
            Async\await($this->load_markets());
            $market = $this->market($symbol);
            $request = array(
                'pair' => $market['id'],
            );
            $response = Async\await($this->publicGetTradesPair ($this->extend($request, $params)));
            $trades = $this->safe_list($response, 'data', array());
            //
            //     {
            //         "data":array(
            //             {
            //                 "timestamp":1644651458,
            //                 "price":"1180785.00000000",
            //                 "amount":"0.00020000",
            //                 "isBuyer":false
            //             }
            //         )
            //     }
            //
            return $this->parse_trades($trades, $market, $since, $limit);
        }) ();
    }

    public function fetch_trading_fees($params = array ()): PromiseInterface {
        return Async\async(function () use ($params) {
            /**
             * fetch the trading fees for multiple markets
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/public/get_limitations_and_fees.md
             *
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} a dictionary of ~@link https://docs.ccxt.com/#/?id=fee-structure fee structures~ indexed by market symbols
             */
            Async\await($this->load_markets());
            $response = Async\await($this->publicGetProvisioningLimitationsAndFees ($params));
            $tradingFeeRate = $this->safe_dict($response, 'tradingFeeRate', array());
            $first = $this->safe_value($tradingFeeRate, 0);
            //
            //     {
            //         "tradingFeeRate":array(
            //             {
            //                 "rank":0,
            //                 "twdVolumeSymbol":"\u003c",
            //                 "twdVolume":"3000000",
            //                 "bitoAmountSymbol":"\u003c",
            //                 "bitoAmount":"7500",
            //                 "makerFee":"0.001",
            //                 "takerFee":"0.002",
            //                 "makerBitoFee":"0.0008",
            //                 "takerBitoFee":"0.0016"
            //             }
            //         ),
            //         "orderFeesAndLimitations":array(
            //             {
            //                 "pair":"BTC/TWD",
            //                 "minimumOrderAmount":"0.0001",
            //                 "minimumOrderAmountBase":"BTC",
            //                 "minimumOrderNumberOfDigits":"0"
            //             }
            //         ),
            //         "restrictionsOfWithdrawalFees":array(
            //             {
            //                 "currency":"TWD",
            //                 "fee":"15",
            //                 "minimumTradingAmount":"100",
            //                 "maximumTradingAmount":"1000000",
            //                 "dailyCumulativeMaximumAmount":"2000000",
            //                 "remarks":"",
            //                 "protocol":""
            //             }
            //         ),
            //         "cryptocurrencyDepositFeeAndConfirmation":array(
            //             {
            //                 "currency":"TWD",
            //                 "generalDepositFees":"0",
            //                 "blockchainConfirmationRequired":""
            //             }
            //         ),
            //         "ttCheckFeesAndLimitationsLevel1":array(
            //             {
            //                 "currency":"TWD",
            //                 "redeemDailyCumulativeMaximumAmount":"",
            //                 "generateMinimumTradingAmount":"",
            //                 "generateMaximumTradingAmount":"",
            //                 "generateDailyCumulativeMaximumAmount":""
            //             }
            //         ),
            //         "ttCheckFeesAndLimitationsLevel2":array(
            //             {
            //                 "currency":"TWD",
            //                 "redeemDailyCumulativeMaximumAmount":"20000000",
            //                 "generateMinimumTradingAmount":"30",
            //                 "generateMaximumTradingAmount":"10000000",
            //                 "generateDailyCumulativeMaximumAmount":"10000000"
            //             }
            //         )
            //     }
            //
            $result = array();
            $maker = $this->safe_number($first, 'makerFee');
            $taker = $this->safe_number($first, 'takerFee');
            for ($i = 0; $i < count($this->symbols); $i++) {
                $symbol = $this->symbols[$i];
                $result[$symbol] = array(
                    'info' => $first,
                    'symbol' => $symbol,
                    'maker' => $maker,
                    'taker' => $taker,
                    'percentage' => true,
                    'tierBased' => true,
                );
            }
            return $result;
        }) ();
    }

    public function parse_ohlcv($ohlcv, ?array $market = null): array {
        return array(
            $this->safe_integer($ohlcv, 'timestamp'),
            $this->safe_number($ohlcv, 'open'),
            $this->safe_number($ohlcv, 'high'),
            $this->safe_number($ohlcv, 'low'),
            $this->safe_number($ohlcv, 'close'),
            $this->safe_number($ohlcv, 'volume'),
        );
    }

    public function fetch_ohlcv(string $symbol, $timeframe = '1m', ?int $since = null, ?int $limit = null, $params = array ()): PromiseInterface {
        return Async\async(function () use ($symbol, $timeframe, $since, $limit, $params) {
            /**
             * fetches historical candlestick $data containing the open, high, low, and close price, and the volume of a $market
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/public/get_ohlc_data.md
             *
             * @param {string} $symbol unified $symbol of the $market to fetch OHLCV $data for
             * @param {string} $timeframe the length of time each candle represents
             * @param {int} [$since] timestamp in ms of the earliest candle to fetch
             * @param {int} [$limit] the maximum amount of candles to fetch
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {int[][]} A list of candles ordered, open, high, low, close, volume
             */
            Async\await($this->load_markets());
            $market = $this->market($symbol);
            $resolution = $this->safe_string($this->timeframes, $timeframe, $timeframe);
            $request = array(
                'pair' => $market['id'],
                'resolution' => $resolution,
            );
            // we need to have a $limit argument because "to" and "from" are required
            if ($limit === null) {
                $limit = 500;
            } else {
                $limit = min ($limit, 75000); // supports slightly more than 75k candles atm, but $limit here to avoid errors
            }
            $timeframeInSeconds = $this->parse_timeframe($timeframe);
            $alignedSince = null;
            if ($since === null) {
                $request['to'] = $this->seconds();
                $request['from'] = $request['to'] - ($limit * $timeframeInSeconds);
            } else {
                $timeframeInMilliseconds = $timeframeInSeconds * 1000;
                $alignedSince = (int) floor($since / $timeframeInMilliseconds) * $timeframeInMilliseconds;
                $request['from'] = (int) floor($since / 1000);
                $request['to'] = $this->sum($request['from'], $limit * $timeframeInSeconds);
            }
            $response = Async\await($this->publicGetTradingHistoryPair ($this->extend($request, $params)));
            $data = $this->safe_list($response, 'data', array());
            //
            //     {
            //         "data":array(
            //             {
            //                 "timestamp":1644581100000,
            //                 "open":"1214737",
            //                 "high":"1215110",
            //                 "low":"1214737",
            //                 "close":"1215110",
            //                 "volume":"0.08423959"
            //             }
            //         )
            //     }
            //
            $sparse = $this->parse_ohlcvs($data, $market, $timeframe, $since, $limit);
            return $this->insert_missing_candles($sparse, $timeframeInSeconds, $alignedSince, $limit);
        }) ();
    }

    public function insert_missing_candles($candles, $distance, $since, $limit) {
        // the exchange doesn't send zero volume $candles so we emulate them instead
        // otherwise sending a $limit arg leads to unexpected results
        $length = count($candles);
        if ($length === 0) {
            return $candles;
        }
        $result = array();
        $copyFrom = $candles[0];
        $timestamp = null;
        if ($since === null) {
            $timestamp = $copyFrom[0];
        } else {
            $timestamp = $since;
        }
        $i = 0;
        $candleLength = count($candles);
        $resultLength = 0;
        while (($resultLength < $limit) && ($i < $candleLength)) {
            $candle = $candles[$i];
            if ($candle[0] === $timestamp) {
                $result[] = $candle;
                $i = $this->sum($i, 1);
            } else {
                $copy = $this->array_concat(array(), $copyFrom);
                $copy[0] = $timestamp;
                // set open, high, low to close
                $copy[1] = $copy[4];
                $copy[2] = $copy[4];
                $copy[3] = $copy[4];
                $copy[5] = $this->parse_number('0');
                $result[] = $copy;
            }
            $timestamp = $this->sum($timestamp, $distance * 1000);
            $resultLength = count($result);
            $copyFrom = $result[$resultLength - 1];
        }
        return $result;
    }

    public function parse_balance($response): array {
        //
        //     [array(
        //         "currency":"twd",
        //         "amount":"0",
        //         "available":"0",
        //         "stake":"0",
        //         "tradable":true
        //     )]
        //
        $result = array(
            'info' => $response,
        );
        for ($i = 0; $i < count($response); $i++) {
            $balance = $response[$i];
            $currencyId = $this->safe_string($balance, 'currency');
            $code = $this->safe_currency_code($currencyId);
            $amount = $this->safe_string($balance, 'amount');
            $available = $this->safe_string($balance, 'available');
            $account = array(
                'free' => $available,
                'total' => $amount,
            );
            $result[$code] = $account;
        }
        return $this->safe_balance($result);
    }

    public function fetch_balance($params = array ()): PromiseInterface {
        return Async\async(function () use ($params) {
            /**
             * query for balance and get the amount of funds available for trading or funds locked in orders
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/private/get_account_balance.md
             *
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} a ~@link https://docs.ccxt.com/#/?id=balance-structure balance structure~
             */
            Async\await($this->load_markets());
            $response = Async\await($this->privateGetAccountsBalance ($params));
            $balances = $this->safe_list($response, 'data', array());
            //
            //     {
            //         "data":array(
            //             {
            //                 "currency":"twd",
            //                 "amount":"0",
            //                 "available":"0",
            //                 "stake":"0",
            //                 "tradable":true
            //             }
            //         )
            //     }
            //
            return $this->parse_balance($balances);
        }) ();
    }

    public function parse_order_status(?string $status) {
        $statuses = array(
            '-1' => 'open',
            '0' => 'open',
            '1' => 'open',
            '2' => 'closed',
            '3' => 'closed',
            '4' => 'canceled',
            '6' => 'canceled',
        );
        return $this->safe_string($statuses, $status, null);
    }

    public function parse_order(array $order, ?array $market = null): array {
        //
        // createOrder
        //         {
        //             "orderId" => "2220595581",
        //             "timestamp" => "1644896744886",
        //             "action" => "SELL",
        //             "amount" => "0.01",
        //             "price" => "15000",
        //             "timeInForce" => "GTC"
        //         }
        //
        // fetchOrder
        //         {
        //             "id":"8777138788",
        //             "pair":"bnb_twd",
        //             "price":"16000",
        //             "avgExecutionPrice":"0",
        //             "action":"SELL",
        //             "type":"LIMIT",
        //             "timestamp":1644899002598,
        //             "status":4,
        //             "originalAmount":"0.01",
        //             "remainingAmount":"0.01",
        //             "executedAmount":"0",
        //             "fee":"0",
        //             "feeSymbol":"twd",
        //             "bitoFee":"0",
        //             "total":"0",
        //             "seq":"BNBTWD548774666",
        //             "timeInForce":"GTC",
        //             "createdTimestamp":1644898944074,
        //             "updatedTimestamp":1644899002598
        //         }
        //
        $id = $this->safe_string_2($order, 'id', 'orderId');
        $timestamp = $this->safe_integer_2($order, 'timestamp', 'createdTimestamp');
        $side = $this->safe_string($order, 'action');
        $side = strtolower($side);
        $amount = $this->safe_string_2($order, 'amount', 'originalAmount');
        $price = $this->safe_string($order, 'price');
        $marketId = $this->safe_string($order, 'pair');
        $market = $this->safe_market($marketId, $market, '_');
        $symbol = $this->safe_string($market, 'symbol');
        $orderStatus = $this->safe_string($order, 'status');
        $status = $this->parse_order_status($orderStatus);
        $type = $this->safe_string_lower($order, 'type');
        $average = $this->safe_string($order, 'avgExecutionPrice');
        $filled = $this->safe_string($order, 'executedAmount');
        $remaining = $this->safe_string($order, 'remainingAmount');
        $timeInForce = $this->safe_string($order, 'timeInForce');
        $postOnly = null;
        if ($timeInForce === 'POST_ONLY') {
            $postOnly = true;
        }
        $fee = null;
        $feeAmount = $this->safe_string($order, 'fee');
        $feeSymbol = $this->safe_currency_code($this->safe_string($order, 'feeSymbol'));
        if (Precise::string_gt($feeAmount, '0')) {
            $fee = array(
                'currency' => $feeSymbol,
                'cost' => $feeAmount,
            );
        }
        return $this->safe_order(array(
            'id' => $id,
            'clientOrderId' => null,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'lastTradeTimestamp' => $this->safe_integer($order, 'updatedTimestamp'),
            'symbol' => $symbol,
            'type' => $type,
            'timeInForce' => $timeInForce,
            'postOnly' => $postOnly,
            'side' => $side,
            'price' => $price,
            'triggerPrice' => null,
            'amount' => $amount,
            'cost' => null,
            'average' => $average,
            'filled' => $filled,
            'remaining' => $remaining,
            'status' => $status,
            'fee' => $fee,
            'trades' => null,
            'info' => $order,
        ), $market);
    }

    public function create_order(string $symbol, string $type, string $side, float $amount, ?float $price = null, $params = array ()) {
        return Async\async(function () use ($symbol, $type, $side, $amount, $price, $params) {
            /**
             * create a trade order
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/private/create_an_order.md
             *
             * @param {string} $symbol unified $symbol of the $market to create an order in
             * @param {string} $type 'market' or 'limit'
             * @param {string} $side 'buy' or 'sell'
             * @param {float} $amount how much of currency you want to trade in units of base currency
             * @param {float} [$price] the $price at which the order is to be fulfilled, in units of the quote currency, ignored in $market orders
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @param {array} [$params->triggerPrice] the $price at which a trigger order is triggered at
             * @return {array} an ~@link https://docs.ccxt.com/#/?id=order-structure order structure~
             */
            Async\await($this->load_markets());
            $market = $this->market($symbol);
            $request = array(
                'type' => $type,
                'pair' => $market['id'],
                'action' => $side,
                'amount' => $this->amount_to_precision($symbol, $amount),
                'timestamp' => $this->milliseconds(),
            );
            $orderType = strtoupper($type);
            if ($orderType === 'LIMIT') {
                $request['price'] = $this->price_to_precision($symbol, $price);
            }
            if ($orderType === 'STOP_LIMIT') {
                $request['price'] = $this->price_to_precision($symbol, $price);
                $triggerPrice = $this->safe_value_2($params, 'triggerPrice', 'stopPrice');
                $params = $this->omit($params, array( 'triggerPrice', 'stopPrice' ));
                if ($triggerPrice === null) {
                    throw new InvalidOrder($this->id . ' createOrder() requires a $triggerPrice parameter for ' . $orderType . ' orders');
                } else {
                    $request['stopPrice'] = $this->price_to_precision($symbol, $triggerPrice);
                }
                $condition = $this->safe_string($params, 'condition');
                if ($condition === null) {
                    throw new InvalidOrder($this->id . ' createOrder() requires a $condition parameter for ' . $orderType . ' orders');
                } else {
                    $request['condition'] = $condition;
                }
            }
            $postOnly = $this->is_post_only($orderType === 'MARKET', null, $params);
            if ($postOnly) {
                $request['timeInForce'] = 'POST_ONLY';
            }
            $response = Async\await($this->privatePostOrdersPair ($this->extend($request, $params)));
            //
            //     {
            //         "orderId" => "2220595581",
            //         "timestamp" => "1644896744886",
            //         "action" => "SELL",
            //         "amount" => "0.01",
            //         "price" => "15000",
            //         "timeInForce" => "GTC"
            //     }
            //
            return $this->parse_order($response, $market);
        }) ();
    }

    public function cancel_order(string $id, ?string $symbol = null, $params = array ()) {
        return Async\async(function () use ($id, $symbol, $params) {
            /**
             * cancels an open order
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/private/cancel_an_order.md
             *
             * @param {string} $id order $id
             * @param {string} $symbol unified $symbol of the $market the order was made in
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} An ~@link https://docs.ccxt.com/#/?$id=order-structure order structure~
             */
            if ($symbol === null) {
                throw new ArgumentsRequired($this->id . ' cancelOrder() requires a $symbol argument');
            }
            Async\await($this->load_markets());
            $market = $this->market($symbol);
            $request = array(
                'id' => $id,
                'pair' => $market['id'],
            );
            $response = Async\await($this->privateDeleteOrdersPairId ($this->extend($request, $params)));
            //
            //     {
            //         "orderId":"8777138788",
            //         "action":"SELL",
            //         "timestamp":1644899002465,
            //         "price":"16000",
            //         "amount":"0.01"
            //     }
            //
            return $this->parse_order($response, $market);
        }) ();
    }

    public function parse_cancel_orders($data) {
        $dataKeys = is_array($data) ? array_keys($data) : array();
        $orders = array();
        for ($i = 0; $i < count($dataKeys); $i++) {
            $marketId = $dataKeys[$i];
            $orderIds = $data[$marketId];
            for ($j = 0; $j < count($orderIds); $j++) {
                $orders[] = $this->safe_order(array(
                    'info' => $orderIds[$j],
                    'id' => $orderIds[$j],
                    'symbol' => $this->safe_symbol($marketId),
                ));
            }
        }
        return $orders;
    }

    public function cancel_orders($ids, ?string $symbol = null, $params = array ()): PromiseInterface {
        return Async\async(function () use ($ids, $symbol, $params) {
            /**
             * cancel multiple orders
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/private/cancel_batch_orders.md
             *
             * @param {string[]} $ids order $ids
             * @param {string} $symbol unified $market $symbol
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} an list of ~@link https://docs.ccxt.com/#/?$id=order-structure order structures~
             */
            if ($symbol === null) {
                throw new ArgumentsRequired($this->id . ' cancelOrders() requires a $symbol argument');
            }
            Async\await($this->load_markets());
            $market = $this->market($symbol);
            $id = $market['uppercaseId'];
            $request = array();
            $request[$id] = $ids;
            $response = Async\await($this->privatePutOrders ($this->extend($request, $params)));
            //
            //     {
            //         "data":{
            //             "BNB_TWD":array(
            //                 "5236347105",
            //                 "359488711"
            //             )
            //         }
            //     }
            //
            $data = $this->safe_dict($response, 'data');
            return $this->parse_cancel_orders($data);
        }) ();
    }

    public function cancel_all_orders(?string $symbol = null, $params = array ()): PromiseInterface {
        return Async\async(function () use ($symbol, $params) {
            /**
             * cancel all open orders
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/private/cancel_all_orders.md
             *
             * @param {string} $symbol unified $market $symbol, only orders in the $market of this $symbol are cancelled when $symbol is not null
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array[]} a list of ~@link https://docs.ccxt.com/#/?id=order-structure order structures~
             */
            Async\await($this->load_markets());
            $request = array(
                // 'pair' => $market['id'], // optional
            );
            $response = null;
            if ($symbol !== null) {
                $market = $this->market($symbol);
                $request['pair'] = $market['id'];
                $response = Async\await($this->privateDeleteOrdersPair ($this->extend($request, $params)));
            } else {
                $response = Async\await($this->privateDeleteOrdersAll ($this->extend($request, $params)));
            }
            $data = $this->safe_dict($response, 'data', array());
            //
            //     {
            //         "data":{
            //             "BNB_TWD":array(
            //                 "9515988421",
            //                 "4639130027"
            //             )
            //         }
            //     }
            //
            return $this->parse_cancel_orders($data);
        }) ();
    }

    public function fetch_order(string $id, ?string $symbol = null, $params = array ()) {
        return Async\async(function () use ($id, $symbol, $params) {
            /**
             * fetches information on an order made by the user
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/private/get_an_order_data.md
             *
             * @param {string} $id the order $id
             * @param {string} $symbol unified $symbol of the $market the order was made in
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} An ~@link https://docs.ccxt.com/#/?$id=order-structure order structure~
             */
            if ($symbol === null) {
                throw new ArgumentsRequired($this->id . ' fetchOrder() requires a $symbol argument');
            }
            Async\await($this->load_markets());
            $market = $this->market($symbol);
            $request = array(
                'orderId' => $id,
                'pair' => $market['id'],
            );
            $response = Async\await($this->privateGetOrdersPairOrderId ($this->extend($request, $params)));
            //
            //     {
            //         "id":"8777138788",
            //         "pair":"bnb_twd",
            //         "price":"16000",
            //         "avgExecutionPrice":"0",
            //         "action":"SELL",
            //         "type":"LIMIT",
            //         "timestamp":1644899002598,
            //         "status":4,
            //         "originalAmount":"0.01",
            //         "remainingAmount":"0.01",
            //         "executedAmount":"0",
            //         "fee":"0",
            //         "feeSymbol":"twd",
            //         "bitoFee":"0",
            //         "total":"0",
            //         "seq":"BNBTWD548774666",
            //         "timeInForce":"GTC",
            //         "createdTimestamp":1644898944074,
            //         "updatedTimestamp":1644899002598
            //     }
            //
            return $this->parse_order($response, $market);
        }) ();
    }

    public function fetch_orders(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()): PromiseInterface {
        return Async\async(function () use ($symbol, $since, $limit, $params) {
            /**
             * fetches information on multiple $orders made by the user
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/private/get_orders_data.md
             *
             * @param {string} $symbol unified $market $symbol of the $market $orders were made in
             * @param {int} [$since] the earliest time in ms to fetch $orders for
             * @param {int} [$limit] the maximum number of order structures to retrieve
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {Order[]} a list of ~@link https://docs.ccxt.com/#/?id=order-structure order structures~
             */
            if ($symbol === null) {
                throw new ArgumentsRequired($this->id . ' fetchOrders() requires a $symbol argument');
            }
            Async\await($this->load_markets());
            $market = $this->market($symbol);
            $request = array(
                'pair' => $market['id'],
                // 'startTimestamp' => 0,
                // 'endTimestamp' => 0,
                // 'statusKind' => '',
                // 'orderId' => '',
            );
            if ($since !== null) {
                $request['startTimestamp'] = $since;
            }
            if ($limit !== null) {
                $request['limit'] = $limit;
            }
            $response = Async\await($this->privateGetOrdersAllPair ($this->extend($request, $params)));
            $orders = $this->safe_list($response, 'data', array());
            if ($orders === null) {
                $orders = array();
            }
            //
            //     {
            //         "data":array(
            //             {
            //                 "id":"2220595581",
            //                 "pair":"bnb_twd",
            //                 "price":"15000",
            //                 "avgExecutionPrice":"0",
            //                 "action":"SELL",
            //                 "type":"LIMIT",
            //                 "createdTimestamp":1644896744886,
            //                 "updatedTimestamp":1644898706236,
            //                 "status":4,
            //                 "originalAmount":"0.01",
            //                 "remainingAmount":"0.01",
            //                 "executedAmount":"0",
            //                 "fee":"0",
            //                 "feeSymbol":"twd",
            //                 "bitoFee":"0",
            //                 "total":"0",
            //                 "seq":"BNBTWD8540871774",
            //                 "timeInForce":"GTC"
            //             }
            //         )
            //     }
            //
            return $this->parse_orders($orders, $market, $since, $limit);
        }) ();
    }

    public function fetch_open_orders(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()) {
        return Async\async(function () use ($symbol, $since, $limit, $params) {
            /**
             * fetch all unfilled currently open $orders
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/private/get_open_orders_data.md
             *
             * @param {string} $symbol unified $market $symbol
             * @param {int} [$since] the earliest time in ms to fetch open $orders for
             * @param {int} [$limit] the maximum number of open $orders structures to retrieve
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {Order[]} a list of ~@link https://docs.ccxt.com/#/?id=order-structure order structures~
             */
            Async\await($this->load_markets());
            $request = array();
            $market = null;
            if ($symbol !== null) {
                $market = $this->market($symbol);
                $request['pair'] = $market['id'];
            }
            $response = Async\await($this->privateGetOrdersOpen ($this->extend($request, $params)));
            $orders = $this->safe_list($response, 'data', array());
            return $this->parse_orders($orders, $market, $since, $limit);
        }) ();
    }

    public function fetch_closed_orders(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()): PromiseInterface {
        /**
         * fetches information on multiple closed orders made by the user
         *
         * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/private/get_orders_data.md
         *
         * @param {string} $symbol unified market $symbol of the market orders were made in
         * @param {int} [$since] the earliest time in ms to fetch orders for
         * @param {int} [$limit] the maximum number of order structures to retrieve
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {Order[]} a list of ~@link https://docs.ccxt.com/#/?id=order-structure order structures~
         */
        $request = array(
            'statusKind' => 'DONE',
        );
        return $this->fetch_orders($symbol, $since, $limit, $this->extend($request, $params));
    }

    public function fetch_my_trades(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()) {
        return Async\async(function () use ($symbol, $since, $limit, $params) {
            /**
             * fetch all $trades made by the user
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/private/get_trades_data.md
             *
             * @param {string} $symbol unified $market $symbol
             * @param {int} [$since] the earliest time in ms to fetch $trades for
             * @param {int} [$limit] the maximum number of $trades structures to retrieve
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {Trade[]} a list of ~@link https://docs.ccxt.com/#/?id=trade-structure trade structures~
             */
            if ($symbol === null) {
                throw new ArgumentsRequired($this->id . ' fetchMyTrades() requires a $symbol argument');
            }
            Async\await($this->load_markets());
            $market = $this->market($symbol);
            $request = array(
                'pair' => $market['id'],
            );
            $response = Async\await($this->privateGetOrdersTradesPair ($this->extend($request, $params)));
            $trades = $this->safe_list($response, 'data', array());
            //
            //     {
            //         "data":array(
            //             {
            //                 "tradeId":"5685030251",
            //                 "orderId":"9669168142",
            //                 "price":"11821.8",
            //                 "action":"SELL",
            //                 "baseAmount":"0.01",
            //                 "quoteAmount":"118.218",
            //                 "fee":"0.236436",
            //                 "feeSymbol":"BNB",
            //                 "isTaker":true,
            //                 "timestamp":1644905714862,
            //                 "createdTimestamp":1644905714862
            //             }
            //         )
            //     }
            //
            return $this->parse_trades($trades, $market, $since, $limit);
        }) ();
    }

    public function parse_transaction_status(?string $status) {
        $states = array(
            'COMPLETE' => 'ok',
            'INVALID' => 'failed',
            'PROCESSING' => 'pending',
            'WAIT_PROCESS' => 'pending',
            'FAILED' => 'failed',
            'EXPIRED' => 'failed',
            'CANCELLED' => 'failed',
            'EMAIL_VERIFICATION' => 'pending',
            'WAIT_CONFIRMATION' => 'pending',
        );
        return $this->safe_string($states, $status, $status);
    }

    public function parse_transaction(array $transaction, ?array $currency = null): array {
        //
        // fetchDeposits
        //
        //    {
        //        "serial" => "20220214X766799",
        //        "timestamp" => "1644833015053",
        //        "address" => "bnb1xml62k5a9dcewgc542fha75fyxdcp0zv8eqfsh",
        //        "amount" => "0.20000000",
        //        "fee" => "0.00000000",
        //        "total" => "0.20000000",
        //        "status" => "COMPLETE",
        //        "txid" => "A3CC4F6828CC752B9F3737F48B5826B9EC2857040CB5141D0CC955F7E53DB6D9",
        //        "message" => "778553959",
        //        "protocol" => "MAIN",
        //        "id" => "2905906537"
        //    }
        //
        // fetchWithdrawals || fetchWithdraw
        //
        //    {
        //        "serial" => "20220215BW14069838",
        //        "timestamp" => "1644907716044",
        //        "address" => "TKrwMaZaGiAvtXCFT41xHuusNcs4LPWS7w",
        //        "amount" => "8.00000000",
        //        "fee" => "2.00000000",
        //        "total" => "10.00000000",
        //        "status" => "COMPLETE",
        //        "txid" => "50bf250c71a582f40cf699fb58bab978437ea9bdf7259ff8072e669aab30c32b",
        //        "protocol" => "TRX",
        //        "id" => "9925310345"
        //    }
        //
        // withdraw
        //
        //    {
        //        "serial" => "20220215BW14069838",
        //        "currency" => "USDT",
        //        "protocol" => "TRX",
        //        "address" => "TKrwMaZaGiAvtXCFT41xHuusNcs4LPWS7w",
        //        "amount" => "8",
        //        "fee" => "2",
        //        "total" => "10"
        //    }
        //
        $currencyId = $this->safe_string($transaction, 'coin');
        $code = $this->safe_currency_code($currencyId, $currency);
        $timestamp = $this->safe_integer($transaction, 'timestamp');
        $address = $this->safe_string($transaction, 'address');
        $tag = $this->safe_string($transaction, 'message');
        $status = $this->safe_string($transaction, 'status');
        $networkId = $this->safe_string($transaction, 'protocol');
        if ($networkId === 'MAIN') {
            $networkId = $code;
        }
        return array(
            'info' => $transaction,
            'id' => $this->safe_string($transaction, 'serial'),
            'txid' => $this->safe_string($transaction, 'txid'),
            'type' => null,
            'currency' => $code,
            'network' => $this->network_id_to_code($networkId),
            'amount' => $this->safe_number($transaction, 'total'),
            'status' => $this->parse_transaction_status($status),
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'address' => $address,
            'addressFrom' => null,
            'addressTo' => $address,
            'tag' => $tag,
            'tagFrom' => null,
            'tagTo' => $tag,
            'updated' => null,
            'comment' => null,
            'internal' => null,
            'fee' => array(
                'currency' => $code,
                'cost' => $this->safe_number($transaction, 'fee'),
                'rate' => null,
            ),
        );
    }

    public function fetch_deposits(?string $code = null, ?int $since = null, ?int $limit = null, $params = array ()): PromiseInterface {
        return Async\async(function () use ($code, $since, $limit, $params) {
            /**
             * fetch all deposits made to an account
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/private/get_deposit_invoices_data.md
             *
             * @param {string} $code unified $currency $code
             * @param {int} [$since] the earliest time in ms to fetch deposits for
             * @param {int} [$limit] the maximum number of deposits structures to retrieve
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array[]} a list of ~@link https://docs.ccxt.com/#/?id=transaction-structure transaction structures~
             */
            if ($code === null) {
                throw new ArgumentsRequired($this->id . ' fetchDeposits() requires the $code argument');
            }
            Async\await($this->load_markets());
            $currency = $this->safe_currency($code);
            $request = array(
                'currency' => $currency['id'],
                // 'endTimestamp' => 0,
                // 'id' => '',
                // 'statuses' => '', // 'ROCESSING,COMPLETE,INVALID,WAIT_PROCESS,CANCELLED,FAILED'
            );
            if ($since !== null) {
                $request['startTimestamp'] = $since;
            }
            if ($limit !== null) {
                $request['limit'] = $limit;
            }
            $response = Async\await($this->privateGetWalletDepositHistoryCurrency ($this->extend($request, $params)));
            $result = $this->safe_list($response, 'data', array());
            //
            //     {
            //         "data":array(
            //             {
            //                 "serial":"20220214X766799",
            //                 "timestamp":"1644833015053",
            //                 "address":"bnb1xml62k5a9dcewgc542fha75fyxdcp0zv8eqfsh",
            //                 "amount":"0.20000000",
            //                 "fee":"0.00000000",
            //                 "total":"0.20000000",
            //                 "status":"COMPLETE",
            //                 "txid":"A3CC4F6828CC752B9F3737F48B5826B9EC2857040CB5141D0CC955F7E53DB6D9",
            //                 "message":"778553959",
            //                 "protocol":"MAIN",
            //                 "id":"2905906537"
            //             }
            //         )
            //     }
            //
            return $this->parse_transactions($result, $currency, $since, $limit, array( 'type' => 'deposit' ));
        }) ();
    }

    public function fetch_withdrawals(?string $code = null, ?int $since = null, ?int $limit = null, $params = array ()): PromiseInterface {
        return Async\async(function () use ($code, $since, $limit, $params) {
            /**
             * fetch all withdrawals made from an account
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/private/get_withdraw_invoices_data.md
             *
             * @param {string} $code unified $currency $code
             * @param {int} [$since] the earliest time in ms to fetch withdrawals for
             * @param {int} [$limit] the maximum number of withdrawals structures to retrieve
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array[]} a list of ~@link https://docs.ccxt.com/#/?id=transaction-structure transaction structures~
             */
            if ($code === null) {
                throw new ArgumentsRequired($this->id . ' fetchWithdrawals() requires the $code argument');
            }
            Async\await($this->load_markets());
            $currency = $this->safe_currency($code);
            $request = array(
                'currency' => $currency['id'],
                // 'endTimestamp' => 0,
                // 'id' => '',
                // 'statuses' => '', // 'PROCESSING,COMPLETE,EXPIRED,INVALID,WAIT_PROCESS,WAIT_CONFIRMATION,EMAIL_VERIFICATION,CANCELLED'
            );
            if ($since !== null) {
                $request['startTimestamp'] = $since;
            }
            if ($limit !== null) {
                $request['limit'] = $limit;
            }
            $response = Async\await($this->privateGetWalletWithdrawHistoryCurrency ($this->extend($request, $params)));
            $result = $this->safe_list($response, 'data', array());
            //
            //     {
            //         "data":array(
            //             {
            //                 "serial":"20220215BW14069838",
            //                 "timestamp":"1644907716044",
            //                 "address":"TKrwMaZaGiAvtXCFT41xHuusNcs4LPWS7w",
            //                 "amount":"8.00000000",
            //                 "fee":"2.00000000",
            //                 "total":"10.00000000",
            //                 "status":"COMPLETE",
            //                 "txid":"50bf250c71a582f40cf699fb58bab978437ea9bdf7259ff8072e669aab30c32b",
            //                 "protocol":"TRX",
            //                 "id":"9925310345"
            //             }
            //         )
            //     }
            //
            return $this->parse_transactions($result, $currency, $since, $limit, array( 'type' => 'withdrawal' ));
        }) ();
    }

    public function fetch_withdrawal(string $id, ?string $code = null, $params = array ()) {
        return Async\async(function () use ($id, $code, $params) {
            /**
             * fetch data on a $currency withdrawal via the withdrawal $id
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/private/get_an_withdraw_invoice_data.md
             *
             * @param {string} $id withdrawal $id
             * @param {string} $code unified $currency $code of the $currency withdrawn, default is null
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} a ~@link https://docs.ccxt.com/#/?$id=transaction-structure transaction structure~
             */
            if ($code === null) {
                throw new ArgumentsRequired($this->id . ' fetchWithdrawal() requires the $code argument');
            }
            Async\await($this->load_markets());
            $currency = $this->safe_currency($code);
            $request = array(
                'serial' => $id,
                'currency' => $currency['id'],
            );
            $response = Async\await($this->privateGetWalletWithdrawCurrencySerial ($this->extend($request, $params)));
            $result = $this->safe_dict($response, 'data', array());
            //
            //     {
            //         "data":{
            //             "serial":"20220215BW14069838",
            //             "address":"TKrwMaZaGiAvtXCFT41xHuusNcs4LPWS7w",
            //             "amount":"8.00000000",
            //             "fee":"2.00000000",
            //             "total":"10.00000000",
            //             "status":"COMPLETE",
            //             "txid":"50bf250c71a582f40cf699fb58bab978437ea9bdf7259ff8072e669aab30c32b",
            //             "protocol":"TRX",
            //             "id":"9925310345",
            //             "timestamp":"1644907716044"
            //         }
            //     }
            //
            return $this->parse_transaction($result, $currency);
        }) ();
    }

    public function withdraw(string $code, float $amount, string $address, ?string $tag = null, $params = array ()): PromiseInterface {
        return Async\async(function () use ($code, $amount, $address, $tag, $params) {
            /**
             * make a withdrawal
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/private/create_an_withdraw_invoice.md
             *
             * @param {string} $code unified $currency $code
             * @param {float} $amount the $amount to withdraw
             * @param {string} $address the $address to withdraw to
             * @param {string} $tag
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} a ~@link https://docs.ccxt.com/#/?id=transaction-structure transaction structure~
             */
            list($tag, $params) = $this->handle_withdraw_tag_and_params($tag, $params);
            Async\await($this->load_markets());
            $this->check_address($address);
            $currency = $this->currency($code);
            $request = array(
                'currency' => $currency['id'],
                'amount' => $this->number_to_string($amount),
                'address' => $address,
            );
            if (is_array($params) && array_key_exists('network', $params)) {
                $networks = $this->safe_dict($this->options, 'networks', array());
                $requestedNetwork = $this->safe_string_upper($params, 'network');
                $params = $this->omit($params, array( 'network' ));
                $networkId = $this->safe_string($networks, $requestedNetwork);
                if ($networkId === null) {
                    throw new ExchangeError($this->id . ' invalid network ' . $requestedNetwork);
                }
                $request['protocol'] = $networkId;
            }
            if ($tag !== null) {
                $request['message'] = $tag;
            }
            $response = Async\await($this->privatePostWalletWithdrawCurrency ($this->extend($request, $params)));
            $result = $this->safe_dict($response, 'data', array());
            //
            //     {
            //         "data":{
            //             "serial":"20220215BW14069838",
            //             "currency":"USDT",
            //             "protocol":"TRX",
            //             "address":"TKrwMaZaGiAvtXCFT41xHuusNcs4LPWS7w",
            //             "amount":"8",
            //             "fee":"2",
            //             "total":"10"
            //         }
            //     }
            //
            return $this->parse_transaction($result, $currency);
        }) ();
    }

    public function parse_deposit_withdraw_fee($fee, ?array $currency = null) {
        //    {
        //        "currency":"eth",
        //        "withdrawFee":"0.007",
        //        "minWithdraw":"0.001",
        //        "maxWithdraw":"1000",
        //        "maxDailyWithdraw":"2000",
        //        "withdraw":true,
        //        "deposit":true,
        //        "depositConfirmation":"12"
        //    }
        return array(
            'info' => $fee,
            'withdraw' => array(
                'fee' => $this->safe_number($fee, 'withdrawFee'),
                'percentage' => false,
            ),
            'deposit' => array(
                'fee' => null,
                'percentage' => null,
            ),
            'networks' => array(),
        );
    }

    public function fetch_deposit_withdraw_fees(?array $codes = null, $params = array ()) {
        return Async\async(function () use ($codes, $params) {
            /**
             * fetch deposit and withdraw fees
             *
             * @see https://github.com/bitoex/bitopro-offical-api-docs/blob/master/api/v3/public/get_currency_info.md
             *
             * @param {string[]|null} $codes list of unified currency $codes
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} a list of ~@link https://docs.ccxt.com/#/?id=fee-structure fee structures~
             */
            Async\await($this->load_markets());
            $response = Async\await($this->publicGetProvisioningCurrencies ($params));
            //
            //     {
            //         "data":array(
            //             {
            //                 "currency":"eth",
            //                 "withdrawFee":"0.007",
            //                 "minWithdraw":"0.001",
            //                 "maxWithdraw":"1000",
            //                 "maxDailyWithdraw":"2000",
            //                 "withdraw":true,
            //                 "deposit":true,
            //                 "depositConfirmation":"12"
            //             }
            //         )
            //     }
            //
            $data = $this->safe_list($response, 'data', array());
            return $this->parse_deposit_withdraw_fees($data, $codes, 'currency');
        }) ();
    }

    public function sign($path, $api = 'public', $method = 'GET', $params = array (), $headers = null, $body = null) {
        $url = '/' . $this->implode_params($path, $params);
        $query = $this->omit($params, $this->extract_params($path));
        if ($headers === null) {
            $headers = array();
        }
        $headers['X-BITOPRO-API'] = 'ccxt';
        if ($api === 'private') {
            $this->check_required_credentials();
            if ($method === 'POST' || $method === 'PUT') {
                $body = $this->json($params);
                $payload = base64_encode($body);
                $signature = $this->hmac($this->encode($payload), $this->encode($this->secret), 'sha384');
                $headers['X-BITOPRO-APIKEY'] = $this->apiKey;
                $headers['X-BITOPRO-PAYLOAD'] = $payload;
                $headers['X-BITOPRO-SIGNATURE'] = $signature;
            } elseif ($method === 'GET' || $method === 'DELETE') {
                if ($query) {
                    $url .= '?' . $this->urlencode($query);
                }
                $nonce = $this->milliseconds();
                $rawData = array(
                    'nonce' => $nonce,
                );
                $data = $this->json($rawData);
                $payload = base64_encode($data);
                $signature = $this->hmac($this->encode($payload), $this->encode($this->secret), 'sha384');
                $headers['X-BITOPRO-APIKEY'] = $this->apiKey;
                $headers['X-BITOPRO-PAYLOAD'] = $payload;
                $headers['X-BITOPRO-SIGNATURE'] = $signature;
            }
        } elseif ($api === 'public' && $method === 'GET') {
            if ($query) {
                $url .= '?' . $this->urlencode($query);
            }
        }
        $url = $this->urls['api']['rest'] . $url;
        return array( 'url' => $url, 'method' => $method, 'body' => $body, 'headers' => $headers );
    }

    public function handle_errors(int $code, string $reason, string $url, string $method, array $headers, string $body, $response, $requestHeaders, $requestBody) {
        if ($response === null) {
            return null; // fallback to the default $error handler
        }
        if ($code >= 200 && $code < 300) {
            return null;
        }
        $feedback = $this->id . ' ' . $body;
        $error = $this->safe_string($response, 'error');
        $this->throw_exactly_matched_exception($this->exceptions['exact'], $error, $feedback);
        $this->throw_broadly_matched_exception($this->exceptions['broad'], $error, $feedback);
        throw new ExchangeError($feedback); // unknown message
    }
}
