<?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\blockchaincom as Exchange;
use ccxt\ExchangeError;
use ccxt\ArgumentsRequired;
use ccxt\InsufficientFunds;
use ccxt\Precise;
use \React\Async;
use \React\Promise\PromiseInterface;

class blockchaincom extends Exchange {

    public function describe(): mixed {
        return $this->deep_extend(parent::describe(), array(
            'id' => 'blockchaincom',
            'secret' => null,
            'name' => 'Blockchain.com',
            'countries' => array( 'LX' ),
            'rateLimit' => 500, // prev 1000
            'version' => 'v3',
            'pro' => true,
            'has' => array(
                'CORS' => false,
                'spot' => true,
                'margin' => null, // on exchange but not implemented in CCXT
                'swap' => false,
                'future' => false,
                'option' => false,
                'cancelAllOrders' => true,
                'cancelOrder' => true,
                'createOrder' => true,
                'createStopLimitOrder' => true,
                'createStopMarketOrder' => true,
                'createStopOrder' => true,
                'fetchBalance' => true,
                'fetchCanceledOrders' => true,
                'fetchClosedOrders' => true,
                'fetchCurrencies' => false,
                'fetchDeposit' => true,
                'fetchDepositAddress' => true,
                'fetchDepositAddresses' => false,
                'fetchDepositAddressesByNetwork' => false,
                'fetchDeposits' => true,
                'fetchFundingHistory' => false,
                'fetchFundingRate' => false,
                'fetchFundingRateHistory' => false,
                'fetchFundingRates' => false,
                'fetchIndexOHLCV' => false,
                'fetchL2OrderBook' => true,
                'fetchL3OrderBook' => true,
                'fetchLedger' => false,
                'fetchMarginMode' => false,
                'fetchMarkets' => true,
                'fetchMarkOHLCV' => false,
                'fetchMyTrades' => true,
                'fetchOHLCV' => false,
                'fetchOpenInterestHistory' => false,
                'fetchOpenOrders' => true,
                'fetchOrder' => true,
                'fetchOrderBook' => true,
                'fetchPositionMode' => false,
                'fetchPremiumIndexOHLCV' => false,
                'fetchTicker' => true,
                'fetchTickers' => true,
                'fetchTrades' => false,
                'fetchTradingFee' => false,
                'fetchTradingFees' => true,
                'fetchTransfer' => false,
                'fetchTransfers' => false,
                'fetchWithdrawal' => true,
                'fetchWithdrawals' => true,
                'fetchWithdrawalWhitelist' => true, // fetches exchange specific benficiary-ids needed for withdrawals
                'transfer' => false,
                'withdraw' => true,
            ),
            'timeframes' => null,
            'urls' => array(
                'logo' => 'https://github.com/user-attachments/assets/975e3054-3399-4363-bcee-ec3c6d63d4e8',
                'test' => array(
                    'public' => 'https://testnet-api.delta.exchange',
                    'private' => 'https://testnet-api.delta.exchange',
                ),
                'api' => array(
                    'public' => 'https://api.blockchain.com/v3/exchange',
                    'private' => 'https://api.blockchain.com/v3/exchange',
                ),
                'www' => 'https://blockchain.com',
                'doc' => array(
                    'https://api.blockchain.com/v3',
                ),
                'fees' => 'https://exchange.blockchain.com/fees',
            ),
            'api' => array(
                'public' => array(
                    'get' => array(
                        'tickers' => 1, // fetchTickers
                        'tickers/{symbol}' => 1, // fetchTicker
                        'symbols' => 1, // fetchMarkets
                        'symbols/{symbol}' => 1, // fetchMarket
                        'l2/{symbol}' => 1, // fetchL2OrderBook
                        'l3/{symbol}' => 1, // fetchL3OrderBook
                    ),
                ),
                'private' => array(
                    'get' => array(
                        'fees' => 1, // fetchFees
                        'orders' => 1, // fetchOpenOrders, fetchClosedOrders
                        'orders/{orderId}' => 1, // fetchOrder(id)
                        'trades' => 1,
                        'fills' => 1, // fetchMyTrades
                        'deposits' => 1, // fetchDeposits
                        'deposits/{depositId}' => 1, // fetchDeposit
                        'accounts' => 1, // fetchBalance
                        'accounts/{account}/{currency}' => 1,
                        'whitelist' => 1, // fetchWithdrawalWhitelist
                        'whitelist/{currency}' => 1, // fetchWithdrawalWhitelistByCurrency
                        'withdrawals' => 1, // fetchWithdrawalWhitelist
                        'withdrawals/{withdrawalId}' => 1, // fetchWithdrawalById
                    ),
                    'post' => array(
                        'orders' => 1, // createOrder
                        'deposits/{currency}' => 1, // fetchDepositAddress by currency (only crypto supported)
                        'withdrawals' => 1, // withdraw
                    ),
                    'delete' => array(
                        'orders' => 1, // cancelOrders
                        'orders/{orderId}' => 1, // cancelOrder
                    ),
                ),
            ),
            'fees' => array(
                'trading' => array(
                    'feeSide' => 'get',
                    'tierBased' => true,
                    'percentage' => true,
                    'tiers' => array(
                        'taker' => array(
                            array( $this->parse_number('0'), $this->parse_number('0.0045') ),
                            array( $this->parse_number('10000'), $this->parse_number('0.0035') ),
                            array( $this->parse_number('50000'), $this->parse_number('0.0018') ),
                            array( $this->parse_number('100000'), $this->parse_number('0.0018') ),
                            array( $this->parse_number('500000'), $this->parse_number('0.0018') ),
                            array( $this->parse_number('1000000'), $this->parse_number('0.0018') ),
                            array( $this->parse_number('2500000'), $this->parse_number('0.0018') ),
                            array( $this->parse_number('5000000'), $this->parse_number('0.0016') ),
                            array( $this->parse_number('25000000'), $this->parse_number('0.0014') ),
                            array( $this->parse_number('100000000'), $this->parse_number('0.0011') ),
                            array( $this->parse_number('500000000'), $this->parse_number('0.0008') ),
                            array( $this->parse_number('1000000000'), $this->parse_number('0.0006') ),
                        ),
                        'maker' => array(
                            array( $this->parse_number('0'), $this->parse_number('0.004') ),
                            array( $this->parse_number('10000'), $this->parse_number('0.0017') ),
                            array( $this->parse_number('50000'), $this->parse_number('0.0015') ),
                            array( $this->parse_number('100000'), $this->parse_number('0.0008') ),
                            array( $this->parse_number('500000'), $this->parse_number('0.0007') ),
                            array( $this->parse_number('1000000'), $this->parse_number('0.0006') ),
                            array( $this->parse_number('2500000'), $this->parse_number('0.0005') ),
                            array( $this->parse_number('5000000'), $this->parse_number('0.0004') ),
                            array( $this->parse_number('25000000'), $this->parse_number('0.0003') ),
                            array( $this->parse_number('100000000'), $this->parse_number('0.0002') ),
                            array( $this->parse_number('500000000'), $this->parse_number('0.0001') ),
                            array( $this->parse_number('1000000000'), $this->parse_number('0') ),
                        ),
                    ),
                ),
            ),
            'requiredCredentials' => array(
                'apiKey' => false,
                'secret' => true,
            ),
            'options' => array(
                'networks' => array(
                    'ERC20' => 'ETH',
                    'TRC20' => 'TRX',
                    'ALGO' => 'ALGO',
                    'ADA' => 'ADA',
                    'AR' => 'AR',
                    'ATOM' => 'ATOM',
                    'AVAXC' => 'AVAX',
                    'BCH' => 'BCH',
                    'BSV' => 'BSV',
                    'BTC' => 'BTC',
                    // 'BEP20' => 'BNB', // todo
                    'DCR' => 'DCR',
                    'DESO' => 'DESO',
                    'DASH' => 'DASH',
                    'CELO' => 'CELO',
                    'CHZ' => 'CHZ',
                    'MATIC' => 'MATIC',
                    'SOL' => 'SOL',
                    'DOGE' => 'DOGE',
                    'DOT' => 'DOT',
                    'EOS' => 'EOS',
                    'ETC' => 'ETC',
                    'FIL' => 'FIL',
                    'KAVA' => 'KAVA',
                    'LTC' => 'LTC',
                    'IOTA' => 'MIOTA',
                    'NEAR' => 'NEAR',
                    'STX' => 'STX',
                    'XLM' => 'XLM',
                    'XMR' => 'XMR',
                    'XRP' => 'XRP',
                    'XTZ' => 'XTZ',
                    'ZEC' => 'ZEC',
                    'ZIL' => 'ZIL',
                    // 'THETA' => 'THETA', // todo => possible TFUEL THETA FUEL is also same, but API might have a mistake
                    // todo => uncomment below after consensus
                    // 'MOBILECOIN' => 'MOB',
                    // 'KIN' => 'KIN',
                    // 'DIGITALGOLD' => 'DGLD',
                ),
            ),
            'features' => array(
                'spot' => array(
                    'sandbox' => false,
                    'createOrder' => array(
                        'marginMode' => false,
                        'triggerPrice' => true,
                        'triggerPriceType' => null,
                        'triggerDirection' => false,
                        'stopLossPrice' => false, // todo
                        'takeProfitPrice' => false, // todo
                        'attachedStopLossTakeProfit' => null,
                        'timeInForce' => array(
                            'IOC' => true,
                            'FOK' => true,
                            'PO' => false,
                            'GTD' => true, // todo implementation
                        ),
                        'hedged' => false,
                        'leverage' => false,
                        'marketBuyRequiresPrice' => false,
                        'marketBuyByCost' => false,
                        'selfTradePrevention' => false,
                        'trailing' => false,
                        'iceberg' => false,
                    ),
                    'createOrders' => null,
                    'fetchMyTrades' => array(
                        'marginMode' => false,
                        'limit' => 1000,
                        'daysBack' => 100000, // todo implementation
                        'untilDays' => 100000, // todo implementation
                        'symbolRequired' => false,
                    ),
                    'fetchOrder' => array(
                        'marginMode' => false,
                        'trigger' => false,
                        'symbolRequired' => false,
                        'trailing' => false,
                    ),
                    'fetchOpenOrders' => array(
                        'marginMode' => false,
                        'limit' => 1000,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => false,
                    ),
                    'fetchOrders' => null, // todo implement
                    'fetchClosedOrders' => array(
                        'marginMode' => false,
                        'limit' => 1000,
                        'daysBack' => 100000,
                        'daysBackCanceled' => 1,
                        'untilDays' => 100000,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => false,
                    ),
                    'fetchOHLCV' => null, // todo webapi
                ),
                'swap' => array(
                    'linear' => null,
                    'inverse' => null,
                ),
                'future' => array(
                    'linear' => null,
                    'inverse' => null,
                ),
            ),
            'precisionMode' => TICK_SIZE,
            'exceptions' => array(
                'exact' => array(
                    '401' => '\\ccxt\\AuthenticationError',
                    '404' => '\\ccxt\\OrderNotFound',
                ),
                'broad' => array(),
            ),
        ));
    }

    public function fetch_markets($params = array ()): PromiseInterface {
        return Async\async(function () use ($params) {
            /**
             * retrieves data on all $markets for blockchaincom
             *
             * @see https://api.blockchain.com/v3/#getsymbols
             *
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array[]} an array of objects representing $market data
             */
            //
            //     "USDC-GBP" => {
            //         "base_currency" => "USDC",
            //         "base_currency_scale" => 6,
            //         "counter_currency" => "GBP",
            //         "counter_currency_scale" => 2,
            //         "min_price_increment" => 10000,
            //         "min_price_increment_scale" => 8,
            //         "min_order_size" => 500000000,
            //         "min_order_size_scale" => 8,
            //         "max_order_size" => 0,
            //         "max_order_size_scale" => 8,
            //         "lot_size" => 10000,
            //         "lot_size_scale" => 8,
            //         "status" => "open",
            //         "id" => 68,
            //         "auction_price" => 0,
            //         "auction_size" => 0,
            //         "auction_time" => "",
            //         "imbalance" => 0
            //     }
            //
            $markets = Async\await($this->publicGetSymbols ($params));
            $marketIds = is_array($markets) ? array_keys($markets) : array();
            $result = array();
            for ($i = 0; $i < count($marketIds); $i++) {
                $marketId = $marketIds[$i];
                $market = $this->safe_value($markets, $marketId);
                $baseId = $this->safe_string($market, 'base_currency');
                $quoteId = $this->safe_string($market, 'counter_currency');
                $base = $this->safe_currency_code($baseId);
                $quote = $this->safe_currency_code($quoteId);
                $numericId = $this->safe_number($market, 'id');
                $active = null;
                $marketState = $this->safe_string($market, 'status');
                if ($marketState === 'open') {
                    $active = true;
                } else {
                    $active = false;
                }
                // price precision
                $minPriceIncrementString = $this->safe_string($market, 'min_price_increment');
                $minPriceIncrementScaleString = $this->safe_string($market, 'min_price_increment_scale');
                $minPriceScalePrecisionString = $this->parse_precision($minPriceIncrementScaleString);
                $pricePrecisionString = Precise::string_mul($minPriceIncrementString, $minPriceScalePrecisionString);
                // amount precision
                $lotSizeString = $this->safe_string($market, 'lot_size');
                $lotSizeScaleString = $this->safe_string($market, 'lot_size_scale');
                $lotSizeScalePrecisionString = $this->parse_precision($lotSizeScaleString);
                $amountPrecisionString = Precise::string_mul($lotSizeString, $lotSizeScalePrecisionString);
                // minimum order size
                $minOrderSizeString = $this->safe_string($market, 'min_order_size');
                $minOrderSizeScaleString = $this->safe_string($market, 'min_order_size_scale');
                $minOrderSizeScalePrecisionString = $this->parse_precision($minOrderSizeScaleString);
                $minOrderSizePreciseString = Precise::string_mul($minOrderSizeString, $minOrderSizeScalePrecisionString);
                $minOrderSize = $this->parse_number($minOrderSizePreciseString);
                // maximum order size
                $maxOrderSize = null;
                $maxOrderSize = $this->safe_string($market, 'max_order_size');
                if ($maxOrderSize !== '0') {
                    $maxOrderSizeScaleString = $this->safe_string($market, 'max_order_size_scale');
                    $maxOrderSizeScalePrecisionString = $this->parse_precision($maxOrderSizeScaleString);
                    $maxOrderSizeString = Precise::string_mul($maxOrderSize, $maxOrderSizeScalePrecisionString);
                    $maxOrderSize = $this->parse_number($maxOrderSizeString);
                } else {
                    $maxOrderSize = null;
                }
                $result[] = array(
                    'info' => $market,
                    'id' => $marketId,
                    'numericId' => $numericId,
                    'symbol' => $base . '/' . $quote,
                    'base' => $base,
                    'quote' => $quote,
                    'settle' => null,
                    'baseId' => $baseId,
                    'quoteId' => $quoteId,
                    'settleId' => null,
                    'type' => 'spot',
                    'spot' => true,
                    'margin' => false,
                    'swap' => false,
                    'future' => false,
                    'option' => false,
                    'active' => $active,
                    'contract' => false,
                    'linear' => null,
                    'inverse' => null,
                    'contractSize' => null,
                    'expiry' => null,
                    'expiryDatetime' => null,
                    'strike' => null,
                    'optionType' => null,
                    'precision' => array(
                        'amount' => $this->parse_number($amountPrecisionString),
                        'price' => $this->parse_number($pricePrecisionString),
                    ),
                    'limits' => array(
                        'leverage' => array(
                            'min' => null,
                            'max' => null,
                        ),
                        'amount' => array(
                            'min' => $minOrderSize,
                            'max' => $maxOrderSize,
                        ),
                        'price' => array(
                            'min' => null,
                            'max' => null,
                        ),
                        'cost' => array(
                            'min' => null,
                            'max' => null,
                        ),
                    ),
                    'created' => null,
                );
            }
            return $result;
        }) ();
    }

    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://api.blockchain.com/v3/#getl3orderbook
             *
             * @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
             */
            return Async\await($this->fetch_l3_order_book($symbol, $limit, $params));
        }) ();
    }

    public function fetch_l3_order_book(string $symbol, ?int $limit = null, $params = array ()) {
        return Async\async(function () use ($symbol, $limit, $params) {
            /**
             * fetches level 3 information on open orders with bid (buy) and ask (sell) prices, volumes and other data
             *
             * @see https://api.blockchain.com/v3/#getl3orderbook
             *
             * @param {string} $symbol unified $market $symbol
             * @param {int} [$limit] max number of orders to return, default is null
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} an ~@link https://docs.ccxt.com/#/?id=order-book-structure order book structure~
             */
            Async\await($this->load_markets());
            $market = $this->market($symbol);
            $request = array(
                'symbol' => $market['id'],
            );
            if ($limit !== null) {
                $request['depth'] = $limit;
            }
            $response = Async\await($this->publicGetL3Symbol ($this->extend($request, $params)));
            return $this->parse_order_book($response, $market['symbol'], null, 'bids', 'asks', 'px', 'qty');
        }) ();
    }

    public function fetch_l2_order_book(string $symbol, ?int $limit = null, $params = array ()) {
        return Async\async(function () use ($symbol, $limit, $params) {
            Async\await($this->load_markets());
            $market = $this->market($symbol);
            $request = array(
                'symbol' => $market['id'],
            );
            if ($limit !== null) {
                $request['depth'] = $limit;
            }
            $response = Async\await($this->publicGetL2Symbol ($this->extend($request, $params)));
            return $this->parse_order_book($response, $market['symbol'], null, 'bids', 'asks', 'px', 'qty');
        }) ();
    }

    public function parse_ticker(array $ticker, ?array $market = null): array {
        //
        //     {
        //     "symbol" => "BTC-USD",
        //     "price_24h" => 47791.86,
        //     "volume_24h" => 362.88635738,
        //     "last_trade_price" => 47587.75
        //     }
        //
        $marketId = $this->safe_string($ticker, 'symbol');
        $symbol = $this->safe_symbol($marketId, $market, '-');
        $last = $this->safe_string($ticker, 'last_trade_price');
        $baseVolume = $this->safe_string($ticker, 'volume_24h');
        $open = $this->safe_string($ticker, 'price_24h');
        return $this->safe_ticker(array(
            'symbol' => $symbol,
            'timestamp' => null,
            'datetime' => null,
            'high' => null,
            'low' => null,
            'bid' => null,
            'bidVolume' => null,
            'ask' => null,
            'askVolume' => null,
            'vwap' => null,
            'open' => $open,
            'close' => null,
            'last' => $last,
            'previousClose' => null,
            'change' => null,
            'percentage' => null,
            'average' => null,
            'baseVolume' => $baseVolume,
            '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://api.blockchain.com/v3/#gettickerbysymbol
             *
             * @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(
                'symbol' => $market['id'],
            );
            $response = Async\await($this->publicGetTickersSymbol ($this->extend($request, $params)));
            return $this->parse_ticker($response, $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://api.blockchain.com/v3/#gettickers
             *
             * @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());
            $tickers = Async\await($this->publicGetTickers ($params));
            return $this->parse_tickers($tickers, $symbols);
        }) ();
    }

    public function parse_order_state($state) {
        $states = array(
            'OPEN' => 'open',
            'REJECTED' => 'rejected',
            'FILLED' => 'closed',
            'CANCELED' => 'canceled',
            'PART_FILLED' => 'open',
            'EXPIRED' => 'expired',
        );
        return $this->safe_string($states, $state, $state);
    }

    public function parse_order(array $order, ?array $market = null): array {
        //
        //     {
        //         "clOrdId" => "00001",
        //         "ordType" => "MARKET",
        //         "ordStatus" => "FILLED",
        //         "side" => "BUY",
        //         "symbol" => "USDC-USDT",
        //         "exOrdId" => "281775861306290",
        //         "price" => null,
        //         "text" => "Fill",
        //         "lastShares" => "30.0",
        //         "lastPx" => "0.9999",
        //         "leavesQty" => "0.0",
        //         "cumQty" => "30.0",
        //         "avgPx" => "0.9999",
        //         "timestamp" => "1633940339619"
        //     }
        //
        $clientOrderId = $this->safe_string($order, 'clOrdId');
        $type = $this->safe_string_lower($order, 'ordType');
        $statusId = $this->safe_string($order, 'ordStatus');
        $state = $this->parse_order_state($statusId);
        $side = $this->safe_string_lower($order, 'side');
        $marketId = $this->safe_string($order, 'symbol');
        $symbol = $this->safe_symbol($marketId, $market, '-');
        $exchangeOrderId = $this->safe_string($order, 'exOrdId');
        $price = ($type !== 'market') ? $this->safe_string($order, 'price') : null;
        $average = $this->safe_number($order, 'avgPx');
        $timestamp = $this->safe_integer($order, 'timestamp');
        $datetime = $this->iso8601($timestamp);
        $filled = $this->safe_string($order, 'cumQty');
        $remaining = $this->safe_string($order, 'leavesQty');
        $result = $this->safe_order(array(
            'id' => $exchangeOrderId,
            'clientOrderId' => $clientOrderId,
            'datetime' => $datetime,
            'timestamp' => $timestamp,
            'lastTradeTimestamp' => null,
            'status' => $state,
            'symbol' => $symbol,
            'type' => $type,
            'timeInForce' => null,
            'side' => $side,
            'price' => $price,
            'average' => $average,
            'amount' => null,
            'filled' => $filled,
            'remaining' => $remaining,
            'cost' => null,
            'trades' => array(),
            'fees' => array(),
            'info' => $order,
        ));
        return $result;
    }

    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://api.blockchain.com/v3/#createorder
             *
             * @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
             * @return {array} an ~@link https://docs.ccxt.com/#/?id=order-structure order structure~
             */
            Async\await($this->load_markets());
            $market = $this->market($symbol);
            $orderType = $this->safe_string($params, 'ordType', $type);
            $uppercaseOrderType = strtoupper($orderType);
            $clientOrderId = $this->safe_string_2($params, 'clientOrderId', 'clOrdId', $this->uuid16());
            $params = $this->omit($params, array( 'ordType', 'clientOrderId', 'clOrdId' ));
            $request = array(
                // 'stopPx' : limit $price
                // 'timeInForce' : "GTC" for Good Till Cancel, "IOC" for Immediate or Cancel, "FOK" for Fill or Kill, "GTD" Good Till Date
                // 'expireDate' : expiry date in the format YYYYMMDD
                // 'minQty' : The minimum quantity required for an IOC fill
                'ordType' => $uppercaseOrderType,
                'symbol' => $market['id'],
                'side' => strtoupper($side),
                'orderQty' => $this->amount_to_precision($symbol, $amount),
                'clOrdId' => $clientOrderId,
            );
            $triggerPrice = $this->safe_value_n($params, array( 'triggerPrice', 'stopPx', 'stopPrice' ));
            $params = $this->omit($params, array( 'triggerPrice', 'stopPx', 'stopPrice' ));
            if ($uppercaseOrderType === 'STOP' || $uppercaseOrderType === 'STOPLIMIT') {
                if ($triggerPrice === null) {
                    throw new ArgumentsRequired($this->id . ' createOrder() requires a stopPx or $triggerPrice param for a ' . $uppercaseOrderType . ' order');
                }
            }
            if ($triggerPrice !== null) {
                if ($uppercaseOrderType === 'MARKET') {
                    $request['ordType'] = 'STOP';
                } elseif ($uppercaseOrderType === 'LIMIT') {
                    $request['ordType'] = 'STOPLIMIT';
                }
            }
            $priceRequired = false;
            $stopPriceRequired = false;
            if ($request['ordType'] === 'LIMIT' || $request['ordType'] === 'STOPLIMIT') {
                $priceRequired = true;
            }
            if ($request['ordType'] === 'STOP' || $request['ordType'] === 'STOPLIMIT') {
                $stopPriceRequired = true;
            }
            if ($priceRequired) {
                $request['price'] = $this->price_to_precision($symbol, $price);
            }
            if ($stopPriceRequired) {
                $request['stopPx'] = $this->price_to_precision($symbol, $triggerPrice);
            }
            $response = Async\await($this->privatePostOrders ($this->extend($request, $params)));
            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://api.blockchain.com/v3/#deleteorder
             *
             * @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~
             */
            $request = array(
                'orderId' => $id,
            );
            $response = Async\await($this->privateDeleteOrdersOrderId ($this->extend($request, $params)));
            return $this->safe_order(array(
                'id' => $id,
                'info' => $response,
            ));
        }) ();
    }

    public function cancel_all_orders(?string $symbol = null, $params = array ()) {
        return Async\async(function () use ($symbol, $params) {
            /**
             * cancel all open orders
             *
             * @see https://api.blockchain.com/v3/#deleteallorders
             *
             * @param {string} $symbol unified market $symbol of the market to cancel orders in, all markets are used if null, default is null
             * @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~
             */
            // cancels all open orders if no $symbol specified
            // cancels all open orders of specified $symbol, if $symbol is specified
            Async\await($this->load_markets());
            $request = array(
                // 'symbol' => $marketId,
            );
            if ($symbol !== null) {
                $marketId = $this->market_id($symbol);
                $request['symbol'] = $marketId;
            }
            $response = Async\await($this->privateDeleteOrders ($this->extend($request, $params)));
            //
            // array()
            //
            return array(
                $this->safe_order(array(
                    'info' => $response,
                )),
            );
        }) ();
    }

    public function fetch_trading_fees($params = array ()): PromiseInterface {
        return Async\async(function () use ($params) {
            /**
             * fetch the trading fees for multiple markets
             *
             * @see https://api.blockchain.com/v3/#getfees
             *
             * @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->privateGetFees ($params));
            //
            //     {
            //         "makerRate" => "0.002",
            //         "takerRate" => "0.004",
            //         "volumeInUSD" => "0.0"
            //     }
            //
            $makerFee = $this->safe_number($response, 'makerRate');
            $takerFee = $this->safe_number($response, 'takerRate');
            $result = array();
            for ($i = 0; $i < count($this->symbols); $i++) {
                $symbol = $this->symbols[$i];
                $result[$symbol] = array(
                    'info' => $response,
                    'symbol' => $symbol,
                    'maker' => $makerFee,
                    'taker' => $takerFee,
                );
            }
            return $result;
        }) ();
    }

    public function fetch_canceled_orders(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()) {
        return Async\async(function () use ($symbol, $since, $limit, $params) {
            /**
             * fetches information on multiple canceled orders made by the user
             *
             * @see https://api.blockchain.com/v3/#getorders
             *
             * @param {string} $symbol unified market $symbol of the market orders were made in
             * @param {int} [$since] timestamp in ms of the earliest order, default is null
             * @param {int} [$limit] max number of orders to return, default is 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~
             */
            $state = 'CANCELED';
            return Async\await($this->fetch_orders_by_state($state, $symbol, $since, $limit, $params));
        }) ();
    }

    public function fetch_closed_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 closed orders made by the user
             *
             * @see https://api.blockchain.com/v3/#getorders
             *
             * @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~
             */
            $state = 'FILLED';
            return Async\await($this->fetch_orders_by_state($state, $symbol, $since, $limit, $params));
        }) ();
    }

    public function fetch_open_orders(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()): PromiseInterface {
        return Async\async(function () use ($symbol, $since, $limit, $params) {
            /**
             * fetch all unfilled currently open orders
             *
             * @see https://api.blockchain.com/v3/#getorders
             *
             * @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~
             */
            $state = 'OPEN';
            return Async\await($this->fetch_orders_by_state($state, $symbol, $since, $limit, $params));
        }) ();
    }

    public function fetch_orders_by_state($state, ?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()) {
        return Async\async(function () use ($state, $symbol, $since, $limit, $params) {
            Async\await($this->load_markets());
            $request = array(
                // 'to' => unix epoch ms
                // 'from' => unix epoch ms
                'status' => $state,
                'limit' => 100,
            );
            $market = null;
            if ($symbol !== null) {
                $market = $this->market($symbol);
                $request['symbol'] = $market['id'];
            }
            $response = Async\await($this->privateGetOrders ($this->extend($request, $params)));
            return $this->parse_orders($response, $market, $since, $limit);
        }) ();
    }

    public function parse_trade(array $trade, ?array $market = null): array {
        //
        //     {
        //         "exOrdId":281685751028507,
        //         "tradeId":281685434947633,
        //         "execId":8847494003,
        //         "side":"BUY",
        //         "symbol":"AAVE-USDT",
        //         "price":405.34,
        //         "qty":0.1,
        //         "fee":0.162136,
        //         "timestamp":1634559249687
        //     }
        //
        $orderId = $this->safe_string($trade, 'exOrdId');
        $tradeId = $this->safe_string($trade, 'tradeId');
        $side = strtolower($this->safe_string($trade, 'side'));
        $marketId = $this->safe_string($trade, 'symbol');
        $priceString = $this->safe_string($trade, 'price');
        $amountString = $this->safe_string($trade, 'qty');
        $timestamp = $this->safe_integer($trade, 'timestamp');
        $datetime = $this->iso8601($timestamp);
        $market = $this->safe_market($marketId, $market, '-');
        $symbol = $market['symbol'];
        $fee = null;
        $feeCostString = $this->safe_string($trade, 'fee');
        if ($feeCostString !== null) {
            $feeCurrency = $market['quote'];
            $fee = array( 'cost' => $feeCostString, 'currency' => $feeCurrency );
        }
        return $this->safe_trade(array(
            'id' => $tradeId,
            'timestamp' => $timestamp,
            'datetime' => $datetime,
            'symbol' => $symbol,
            'order' => $orderId,
            'type' => null,
            'side' => $side,
            'takerOrMaker' => null,
            'price' => $priceString,
            'amount' => $amountString,
            'cost' => null,
            'fee' => $fee,
            'info' => $trade,
        ), $market);
    }

    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://api.blockchain.com/v3/#getfills
             *
             * @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~
             */
            Async\await($this->load_markets());
            $request = array();
            if ($limit !== null) {
                $request['limit'] = $limit;
            }
            $market = null;
            if ($symbol !== null) {
                $request['symbol'] = $this->market_id($symbol);
                $market = $this->market($symbol);
            }
            $trades = Async\await($this->privateGetFills ($this->extend($request, $params)));
            return $this->parse_trades($trades, $market, $since, $limit, $params); // need to define
        }) ();
    }

    public function fetch_deposit_address(string $code, $params = array ()): PromiseInterface {
        return Async\async(function () use ($code, $params) {
            /**
             * fetch the deposit $address for a $currency associated with this account
             *
             * @see https://api.blockchain.com/v3/#getdepositaddress
             *
             * @param {string} $code unified $currency $code
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} an ~@link https://docs.ccxt.com/#/?id=$address-structure $address structure~
             */
            Async\await($this->load_markets());
            $currency = $this->currency($code);
            $request = array(
                'currency' => $currency['id'],
            );
            $response = Async\await($this->privatePostDepositsCurrency ($this->extend($request, $params)));
            $rawAddress = $this->safe_string($response, 'address');
            $tag = null;
            $address = null;
            if ($rawAddress !== null) {
                $addressParts = explode(';', $rawAddress);
                // if a $tag or memo is used it is separated by a colon in the 'address' value
                $tag = $this->safe_string($addressParts, 0);
                $address = $this->safe_string($addressParts, 1);
            }
            return array(
                'info' => $response,
                'currency' => $currency['code'],
                'network' => null,
                'address' => $address,
                'tag' => $tag,
            );
        }) ();
    }

    public function parse_transaction_state($state) {
        $states = array(
            'COMPLETED' => 'ok', //
            'REJECTED' => 'failed',
            'PENDING' => 'pending',
            'FAILED' => 'failed',
            'REFUNDED' => 'refunded',
        );
        return $this->safe_string($states, $state, $state);
    }

    public function parse_transaction(array $transaction, ?array $currency = null): array {
        //
        // deposit
        //
        //     {
        //         "depositId":"748e9180-be0d-4a80-e175-0156150efc95",
        //         "amount":0.009,
        //         "currency":"ETH",
        //         "address":"0xEC6B5929D454C8D9546d4221ace969E1810Fa92c",
        //         "state":"COMPLETED",
        //         "txHash":"582114562140e51a80b481c2dfebaf62b4ab9769b8ff54820bb67e34d4a3ab0c",
        //         "timestamp":1633697196241
        //     }
        //
        // withdrawal
        //
        //     {
        //         "amount":30.0,
        //         "currency":"USDT",
        //         "beneficiary":"cab00d11-6e7f-46b7-b453-2e8ef6f101fa", // blockchain specific $id
        //         "withdrawalId":"99df5ef7-eab6-4033-be49-312930fbd1ea",
        //         "fee":34.005078,
        //         "state":"COMPLETED",
        //         "timestamp":1634218452549
        //     }
        //
        $type = null;
        $id = null;
        $amount = $this->safe_number($transaction, 'amount');
        $timestamp = $this->safe_integer($transaction, 'timestamp');
        $currencyId = $this->safe_string($transaction, 'currency');
        $code = $this->safe_currency_code($currencyId, $currency);
        $state = $this->safe_string($transaction, 'state');
        if (is_array($transaction) && array_key_exists('depositId', $transaction)) {
            $type = 'deposit';
            $id = $this->safe_string($transaction, 'depositId');
        } elseif (is_array($transaction) && array_key_exists('withdrawalId', $transaction)) {
            $type = 'withdrawal';
            $id = $this->safe_string($transaction, 'withdrawalId');
        }
        $feeCost = ($type === 'withdrawal') ? $this->safe_number($transaction, 'fee') : null;
        $fee = null;
        if ($feeCost !== null) {
            $fee = array( 'currency' => $code, 'cost' => $feeCost );
        }
        $address = $this->safe_string($transaction, 'address');
        $txid = $this->safe_string($transaction, 'txhash');
        return array(
            'info' => $transaction,
            'id' => $id,
            'txid' => $txid,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'network' => null,
            'addressFrom' => null,
            'address' => $address,
            'addressTo' => $address,
            'tagFrom' => null,
            'tag' => null,
            'tagTo' => null,
            'type' => $type,
            'amount' => $amount,
            'currency' => $code,
            'status' => $this->parse_transaction_state($state), // 'status' =>   'pending',   // 'ok', 'failed', 'canceled', string
            'updated' => null,
            'comment' => null,
            'internal' => null,
            'fee' => $fee,
        );
    }

    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://api.blockchain.com/v3/#createwithdrawal
             *
             * @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~
             */
            Async\await($this->load_markets());
            $currency = $this->currency($code);
            $request = array(
                'amount' => $amount,
                'currency' => $currency['id'],
                'beneficiary' => $address,
                'sendMax' => false,
            );
            $response = Async\await($this->privatePostWithdrawals ($this->extend($request, $params)));
            //
            //     array(
            //         "amount" => "30.0",
            //         "currency" => "USDT",
            //         "beneficiary" => "adcd43fb-9ba6-41f7-8c0d-7013482cb88f",
            //         "withdrawalId" => "99df5ef7-eab6-4033-be49-312930fbd1ea",
            //         "fee" => "34.005078",
            //         "state" => "PENDING",
            //         "timestamp" => "1634218452595"
            //     ),
            //
            return $this->parse_transaction($response, $currency);
        }) ();
    }

    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://api.blockchain.com/v3/#getwithdrawals
             *
             * @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~
             */
            Async\await($this->load_markets());
            $request = array(
                // 'from' : integer timestamp in ms
                // 'to' : integer timestamp in ms
            );
            if ($since !== null) {
                $request['from'] = $since;
            }
            $currency = null;
            if ($code !== null) {
                $currency = $this->currency($code);
            }
            $response = Async\await($this->privateGetWithdrawals ($this->extend($request, $params)));
            return $this->parse_transactions($response, $currency, $since, $limit);
        }) ();
    }

    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://api.blockchain.com/v3/#getwithdrawalbyid
             *
             * @param {string} $id withdrawal $id
             * @param {string} $code not used by blockchaincom.fetchWithdrawal
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} a ~@link https://docs.ccxt.com/#/?$id=transaction-structure transaction structure~
             */
            Async\await($this->load_markets());
            $request = array(
                'withdrawalId' => $id,
            );
            $response = Async\await($this->privateGetWithdrawalsWithdrawalId ($this->extend($request, $params)));
            return $this->parse_transaction($response);
        }) ();
    }

    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://api.blockchain.com/v3/#getdeposits
             *
             * @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~
             */
            Async\await($this->load_markets());
            $request = array(
                // 'from' : integer timestamp in ms
                // 'to' : integer timestap in ms
            );
            if ($since !== null) {
                $request['from'] = $since;
            }
            $currency = null;
            if ($code !== null) {
                $currency = $this->currency($code);
            }
            $response = Async\await($this->privateGetDeposits ($this->extend($request, $params)));
            return $this->parse_transactions($response, $currency, $since, $limit);
        }) ();
    }

    public function fetch_deposit(string $id, ?string $code = null, $params = array ()) {
        return Async\async(function () use ($id, $code, $params) {
            /**
             * fetch information on a $deposit
             *
             * @see https://api.blockchain.com/v3/#getdepositbyid
             *
             * @param {string} $id $deposit $id
             * @param {string} $code not used by blockchaincom fetchDeposit ()
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} a ~@link https://docs.ccxt.com/#/?$id=transaction-structure transaction structure~
             */
            Async\await($this->load_markets());
            $depositId = $this->safe_string($params, 'depositId', $id);
            $request = array(
                'depositId' => $depositId,
            );
            $deposit = Async\await($this->privateGetDepositsDepositId ($this->extend($request, $params)));
            return $this->parse_transaction($deposit);
        }) ();
    }

    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://api.blockchain.com/v3/#getaccounts
             *
             * @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());
            $accountName = $this->safe_string($params, 'account', 'primary');
            $params = $this->omit($params, 'account');
            $request = array(
                'account' => $accountName,
            );
            $response = Async\await($this->privateGetAccounts ($this->extend($request, $params)));
            //
            //     {
            //         "primary" => array(
            //             array(
            //                 "currency":"ETH",
            //                 "balance":0.009,
            //                 "available":0.009,
            //                 "balance_local":30.82869,
            //                 "available_local":30.82869,
            //                 "rate":3425.41
            //             ),
            //             ...
            //         )
            //     }
            //
            $balances = $this->safe_value($response, $accountName);
            if ($balances === null) {
                throw new ExchangeError($this->id . ' fetchBalance() could not find the "' . $accountName . '" account');
            }
            $result = array( 'info' => $response );
            for ($i = 0; $i < count($balances); $i++) {
                $entry = $balances[$i];
                $currencyId = $this->safe_string($entry, 'currency');
                $code = $this->safe_currency_code($currencyId);
                $account = $this->account();
                $account['free'] = $this->safe_string($entry, 'available');
                $account['total'] = $this->safe_string($entry, 'balance');
                $result[$code] = $account;
            }
            return $this->safe_balance($result);
        }) ();
    }

    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://api.blockchain.com/v3/#getorderbyid
             *
             * @param {string} $id the order $id
             * @param {string} $symbol not used by blockchaincom fetchOrder
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} An ~@link https://docs.ccxt.com/#/?$id=order-structure order structure~
             */
            // note => only works with exchange-order-$id
            // does not work with clientOrderId
            Async\await($this->load_markets());
            $request = array(
                'orderId' => $id,
            );
            $response = Async\await($this->privateGetOrdersOrderId ($this->extend($request, $params)));
            //
            //     {
            //         "exOrdId" => 11111111,
            //         "clOrdId" => "ABC",
            //         "ordType" => "MARKET",
            //         "ordStatus" => "FILLED",
            //         "side" => "BUY",
            //         "price" => 0.12345,
            //         "text" => "string",
            //         "symbol" => "BTC-USD",
            //         "lastShares" => 0.5678,
            //         "lastPx" => 3500.12,
            //         "leavesQty" => 10,
            //         "cumQty" => 0.123345,
            //         "avgPx" => 345.33,
            //         "timestamp" => 1592830770594
            //     }
            //
            return $this->parse_order($response);
        }) ();
    }

    public function sign($path, $api = 'public', $method = 'GET', $params = array (), $headers = null, $body = null) {
        $requestPath = '/' . $this->implode_params($path, $params);
        $url = $this->urls['api'][$api] . $requestPath;
        $query = $this->omit($params, $this->extract_params($path));
        if ($api === 'public') {
            if ($query) {
                $url .= '?' . $this->urlencode($query);
            }
        } elseif ($api === 'private') {
            $this->check_required_credentials();
            $headers = array(
                'X-API-Token' => $this->secret,
            );
            if (($method === 'GET')) {
                if ($query) {
                    $url .= '?' . $this->urlencode($query);
                }
            } else {
                $body = $this->json($query);
                $headers['Content-Type'] = 'application/json';
            }
        }
        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) {
        // {"timestamp":"2021-10-21T15:13:58.837+00:00","status":404,"error":"Not Found","message":"","path":"/orders/505050"
        if ($response === null) {
            return null;
        }
        $text = $this->safe_string($response, 'text');
        if ($text !== null) { // if trade currency account is empty returns 200 with rejected order
            if ($text === 'Insufficient Balance') {
                throw new InsufficientFunds($this->id . ' ' . $body);
            }
        }
        $errorCode = $this->safe_string($response, 'status');
        $errorMessage = $this->safe_string($response, 'error');
        if ($code !== null) {
            $feedback = $this->id . ' ' . $this->json($response);
            $this->throw_exactly_matched_exception($this->exceptions['exact'], $errorCode, $feedback);
            $this->throw_broadly_matched_exception($this->exceptions['broad'], $errorMessage, $feedback);
        }
        return null;
    }
}
