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

class btcmarkets extends Exchange {

    public function describe(): mixed {
        return $this->deep_extend(parent::describe(), array(
            'id' => 'btcmarkets',
            'name' => 'BTC Markets',
            'countries' => array( 'AU' ), // Australia
            'rateLimit' => 1000, // market data cached for 1 second (trades cached for 2 seconds)
            'version' => 'v3',
            'has' => array(
                'CORS' => null,
                'spot' => true,
                'margin' => false,
                'swap' => false,
                'future' => false,
                'option' => false,
                'addMargin' => false,
                'borrowCrossMargin' => false,
                'borrowIsolatedMargin' => false,
                'borrowMargin' => false,
                'cancelOrder' => true,
                'cancelOrders' => true,
                'closeAllPositions' => false,
                'closePosition' => false,
                'createDepositAddress' => false,
                'createOrder' => true,
                'createOrderWithTakeProfitAndStopLoss' => false,
                'createOrderWithTakeProfitAndStopLossWs' => false,
                'createPostOnlyOrder' => false,
                'createReduceOnlyOrder' => false,
                'createTriggerOrder' => true,
                'fetchBalance' => true,
                'fetchBorrowInterest' => false,
                'fetchBorrowRate' => false,
                'fetchBorrowRateHistories' => false,
                'fetchBorrowRateHistory' => false,
                'fetchBorrowRates' => false,
                'fetchBorrowRatesPerSymbol' => false,
                'fetchClosedOrders' => 'emulated',
                'fetchCrossBorrowRate' => false,
                'fetchCrossBorrowRates' => false,
                'fetchCurrencies' => false,
                'fetchDepositAddress' => false,
                'fetchDepositAddresses' => false,
                'fetchDepositAddressesByNetwork' => false,
                'fetchDeposits' => true,
                'fetchDepositsWithdrawals' => 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' => true,
                'fetchPosition' => false,
                'fetchPositionHistory' => false,
                'fetchPositionMode' => false,
                'fetchPositions' => false,
                'fetchPositionsForSymbol' => false,
                'fetchPositionsHistory' => false,
                'fetchPositionsRisk' => false,
                'fetchPremiumIndexOHLCV' => false,
                'fetchSettlementHistory' => false,
                'fetchTicker' => true,
                'fetchTime' => true,
                'fetchTrades' => true,
                'fetchTransactions' => 'emulated',
                'fetchVolatilityHistory' => false,
                'fetchWithdrawals' => true,
                'reduceMargin' => false,
                'repayCrossMargin' => false,
                'repayIsolatedMargin' => false,
                'repayMargin' => false,
                'setLeverage' => false,
                'setMargin' => false,
                'setMarginMode' => false,
                'setPositionMode' => false,
                'withdraw' => true,
            ),
            'urls' => array(
                'logo' => 'https://github.com/user-attachments/assets/8c8d6907-3873-4cc4-ad20-e22fba28247e',
                'api' => array(
                    'public' => 'https://api.btcmarkets.net',
                    'private' => 'https://api.btcmarkets.net',
                ),
                'www' => 'https://btcmarkets.net',
                'doc' => array(
                    'https://api.btcmarkets.net/doc/v3',
                    'https://github.com/BTCMarkets/API',
                ),
            ),
            'api' => array(
                'public' => array(
                    'get' => array(
                        'markets',
                        'markets/{marketId}/ticker',
                        'markets/{marketId}/trades',
                        'markets/{marketId}/orderbook',
                        'markets/{marketId}/candles',
                        'markets/tickers',
                        'markets/orderbooks',
                        'time',
                    ),
                ),
                'private' => array(
                    'get' => array(
                        'orders',
                        'orders/{id}',
                        'batchorders/{ids}',
                        'trades',
                        'trades/{id}',
                        'withdrawals',
                        'withdrawals/{id}',
                        'deposits',
                        'deposits/{id}',
                        'transfers',
                        'transfers/{id}',
                        'addresses',
                        'withdrawal-fees',
                        'assets',
                        'accounts/me/trading-fees',
                        'accounts/me/withdrawal-limits',
                        'accounts/me/balances',
                        'accounts/me/transactions',
                        'reports/{id}',
                    ),
                    'post' => array(
                        'orders',
                        'batchorders',
                        'withdrawals',
                        'reports',
                    ),
                    'delete' => array(
                        'orders',
                        'orders/{id}',
                        'batchorders/{ids}',
                    ),
                    'put' => array(
                        'orders/{id}',
                    ),
                ),
            ),
            'timeframes' => array(
                '1m' => '1m',
                '1h' => '1h',
                '1d' => '1d',
            ),
            'features' => array(
                'spot' => array(
                    'sandbox' => false,
                    'createOrder' => array(
                        'marginMode' => false,
                        'triggerPrice' => true, // todo => check
                        'triggerPriceType' => null,
                        'triggerDirection' => false,
                        'stopLossPrice' => false,
                        'takeProfitPrice' => false,
                        'attachedStopLossTakeProfit' => null,
                        'timeInForce' => array(
                            'IOC' => true,
                            'FOK' => true,
                            'PO' => true,
                            'GTD' => false,
                        ),
                        'hedged' => false,
                        'leverage' => false,
                        'marketBuyRequiresPrice' => false,
                        'marketBuyByCost' => false,
                        'selfTradePrevention' => true, // todo => check
                        'trailing' => false,
                        'iceberg' => false,
                    ),
                    'createOrders' => null,
                    'fetchMyTrades' => array(
                        'marginMode' => false,
                        'limit' => 100,
                        'daysBack' => 100000,
                        'untilDays' => 100000,
                        'symbolRequired' => true,
                    ),
                    'fetchOrder' => array(
                        'marginMode' => false,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => false,
                    ),
                    'fetchOpenOrders' => array(
                        'marginMode' => false,
                        'limit' => 100,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => false,
                    ),
                    'fetchOrders' => array(
                        'marginMode' => false,
                        'limit' => 100,
                        'daysBack' => 100000,
                        'untilDays' => 100000,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => false,
                    ),
                    'fetchClosedOrders' => array(
                        'marginMode' => false,
                        'limit' => 100,
                        'daysBack' => 100000,
                        'daysBackCanceled' => 1,
                        'untilDays' => 100000,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => false,
                    ),
                    'fetchOHLCV' => array(
                        'limit' => 1000,
                    ),
                ),
                'swap' => array(
                    'linear' => null,
                    'inverse' => null,
                ),
                'future' => array(
                    'linear' => null,
                    'inverse' => null,
                ),
            ),
            'precisionMode' => TICK_SIZE,
            'exceptions' => array(
                'exact' => array(
                    'InsufficientFund' => '\\ccxt\\InsufficientFunds',
                    'InvalidPrice' => '\\ccxt\\InvalidOrder',
                    'InvalidAmount' => '\\ccxt\\InvalidOrder',
                    'MissingArgument' => '\\ccxt\\BadRequest',
                    'OrderAlreadyCancelled' => '\\ccxt\\InvalidOrder',
                    'OrderNotFound' => '\\ccxt\\OrderNotFound',
                    'OrderStatusIsFinal' => '\\ccxt\\InvalidOrder',
                    'InvalidPaginationParameter' => '\\ccxt\\BadRequest',
                ),
                'broad' => array(
                ),
            ),
            'fees' => array(
                'percentage' => true,
                'tierBased' => true,
                'maker' => $this->parse_number('-0.0005'),
                'taker' => $this->parse_number('0.0020'),
            ),
            'options' => array(
                'fees' => array(
                    'AUD' => array(
                        'maker' => $this->parse_number('0.0085'),
                        'taker' => $this->parse_number('0.0085'),
                    ),
                ),
            ),
        ));
    }

    public function fetch_transactions_with_method($method, ?string $code = null, ?int $since = null, ?int $limit = null, $params = array ()) {
        return Async\async(function () use ($method, $code, $since, $limit, $params) {
            Async\await($this->load_markets());
            $request = array();
            if ($limit !== null) {
                $request['limit'] = $limit;
            }
            if ($since !== null) {
                $request['after'] = $since;
            }
            $currency = null;
            if ($code !== null) {
                $currency = $this->currency($code);
            }
            $response = Async\await($this->$method ($this->extend($request, $params)));
            return $this->parse_transactions($response, $currency, $since, $limit);
        }) ();
    }

    public function fetch_deposits_withdrawals(?string $code = null, ?int $since = null, ?int $limit = null, $params = array ()): PromiseInterface {
        return Async\async(function () use ($code, $since, $limit, $params) {
            /**
             * fetch history of deposits and withdrawals
             *
             * @see https://docs.btcmarkets.net/v3/#tag/Fund-Management-APIs/paths/{1v3}1transfers/get
             *
             * @param {string} [$code] unified currency $code for the currency of the deposit/withdrawals, default is null
             * @param {int} [$since] timestamp in ms of the earliest deposit/withdrawal, default is null
             * @param {int} [$limit] max number of deposit/withdrawals 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=transaction-structure transaction structure~
             */
            return Async\await($this->fetch_transactions_with_method('privateGetTransfers', $code, $since, $limit, $params));
        }) ();
    }

    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://docs.btcmarkets.net/v3/#tag/Fund-Management-APIs/paths/{1v3}1deposits/get
             *
             * @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~
             */
            return Async\await($this->fetch_transactions_with_method('privateGetDeposits', $code, $since, $limit, $params));
        }) ();
    }

    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://docs.btcmarkets.net/v3/#tag/Fund-Management-APIs/paths/{1v3}1withdrawals/get
             *
             * @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~
             */
            return Async\await($this->fetch_transactions_with_method('privateGetWithdrawals', $code, $since, $limit, $params));
        }) ();
    }

    public function parse_transaction_status(?string $status) {
        $statuses = array(
            'Accepted' => 'pending',
            'Pending Authorization' => 'pending',
            'Complete' => 'ok',
            'Cancelled' => 'cancelled',
            'Failed' => 'failed',
        );
        return $this->safe_string($statuses, $status, $status);
    }

    public function parse_transaction_type($type) {
        $statuses = array(
            'Withdraw' => 'withdrawal',
            'Deposit' => 'deposit',
        );
        return $this->safe_string($statuses, $type, $type);
    }

    public function parse_transaction(array $transaction, ?array $currency = null): array {
        //
        //    {
        //         "id" => "6500230339",
        //         "assetName" => "XRP",
        //         "amount" => "500",
        //         "type" => "Deposit",
        //         "creationTime" => "2020-07-27T07:52:08.640000Z",
        //         "status" => "Complete",
        //         "description" => "RIPPLE Deposit, XRP 500",
        //         "fee" => "0",
        //         "lastUpdate" => "2020-07-27T07:52:08.665000Z",
        //         "paymentDetail" => {
        //             "txId" => "lsjflsjdfljsd",
        //             "address" => "kjasfkjsdf?dt=873874545"
        //         }
        //    }
        //
        //    {
        //         "id" => "500985282",
        //         "assetName" => "BTC",
        //         "amount" => "0.42570126",
        //         "type" => "Withdraw",
        //         "creationTime" => "2017-07-29T12:49:03.931000Z",
        //         "status" => "Complete",
        //         "description" => "BTC withdraw from [nick-btcmarkets@snowmonkey.co.uk] to Address => 1B9DsnSYQ54VMqFHVJYdGoLMCYzFwrQzsj $amount => 0.42570126 $fee => 0.00000000",
        //         "fee" => "0.0005",
        //         "lastUpdate" => "2017-07-29T12:52:20.676000Z",
        //         "paymentDetail" => {
        //             "txId" => "fkjdsfjsfljsdfl",
        //             "address" => "a;daddjas;djas"
        //         }
        //    }
        //
        //    {
        //         "id" => "505102262",
        //         "assetName" => "XRP",
        //         "amount" => "979.836",
        //         "type" => "Deposit",
        //         "creationTime" => "2017-07-31T08:50:01.053000Z",
        //         "status" => "Complete",
        //         "description" => "Ripple Deposit, X 979.8360",
        //         "fee" => "0",
        //         "lastUpdate" => "2017-07-31T08:50:01.290000Z"
        //     }
        //
        $timestamp = $this->parse8601($this->safe_string($transaction, 'creationTime'));
        $lastUpdate = $this->parse8601($this->safe_string($transaction, 'lastUpdate'));
        $type = $this->parse_transaction_type($this->safe_string_lower($transaction, 'type'));
        if ($type === 'withdraw') {
            $type = 'withdrawal';
        }
        $cryptoPaymentDetail = $this->safe_dict($transaction, 'paymentDetail', array());
        $txid = $this->safe_string($cryptoPaymentDetail, 'txId');
        $address = $this->safe_string($cryptoPaymentDetail, 'address');
        $tag = null;
        if ($address !== null) {
            $addressParts = explode('?dt=', $address);
            $numParts = count($addressParts);
            if ($numParts > 1) {
                $address = $addressParts[0];
                $tag = $addressParts[1];
            }
        }
        $addressTo = $address;
        $tagTo = $tag;
        $addressFrom = null;
        $tagFrom = null;
        $fee = $this->safe_string($transaction, 'fee');
        $status = $this->parse_transaction_status($this->safe_string($transaction, 'status'));
        $currencyId = $this->safe_string($transaction, 'assetName');
        $code = $this->safe_currency_code($currencyId);
        $amount = $this->safe_string($transaction, 'amount');
        if ($fee) {
            $amount = Precise::string_sub($amount, $fee);
        }
        return array(
            'id' => $this->safe_string($transaction, 'id'),
            'txid' => $txid,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'network' => null,
            'address' => $address,
            'addressTo' => $addressTo,
            'addressFrom' => $addressFrom,
            'tag' => $tag,
            'tagTo' => $tagTo,
            'tagFrom' => $tagFrom,
            'type' => $type,
            'amount' => $this->parse_number($amount),
            'currency' => $code,
            'status' => $status,
            'updated' => $lastUpdate,
            'comment' => $this->safe_string($transaction, 'description'),
            'internal' => null,
            'fee' => array(
                'currency' => $code,
                'cost' => $this->parse_number($fee),
                'rate' => null,
            ),
            'info' => $transaction,
        );
    }

    public function fetch_markets($params = array ()): PromiseInterface {
        return Async\async(function () use ($params) {
            /**
             * retrieves data on all markets for btcmarkets
             *
             * @see https://docs.btcmarkets.net/v3/#tag/Market-Data-APIs/paths/{1v3}1markets/get
             *
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array[]} an array of objects representing market data
             */
            $response = Async\await($this->publicGetMarkets ($params));
            //
            //     array(
            //         {
            //             "marketId":"COMP-AUD",
            //             "baseAssetName":"COMP",
            //             "quoteAssetName":"AUD",
            //             "minOrderAmount":"0.00006",
            //             "maxOrderAmount":"1000000",
            //             "amountDecimals":"8",
            //             "priceDecimals":"2",
            //             "status" => "Online"
            //         }
            //     )
            //
            return $this->parse_markets($response);
        }) ();
    }

    public function parse_market(array $market): array {
        $baseId = $this->safe_string($market, 'baseAssetName');
        $quoteId = $this->safe_string($market, 'quoteAssetName');
        $id = $this->safe_string($market, 'marketId');
        $base = $this->safe_currency_code($baseId);
        $quote = $this->safe_currency_code($quoteId);
        $symbol = $base . '/' . $quote;
        $fees = $this->safe_value($this->safe_dict($this->options, 'fees', array()), $quote, $this->fees);
        $pricePrecision = $this->parse_number($this->parse_precision($this->safe_string($market, 'priceDecimals')));
        $minAmount = $this->safe_number($market, 'minOrderAmount');
        $maxAmount = $this->safe_number($market, 'maxOrderAmount');
        $status = $this->safe_string($market, 'status');
        $minPrice = null;
        if ($quote === 'AUD') {
            $minPrice = $pricePrecision;
        }
        return array(
            'id' => $id,
            'symbol' => $symbol,
            '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' => ($status === 'Online'),
            'contract' => false,
            'linear' => null,
            'inverse' => null,
            'taker' => $fees['taker'],
            'maker' => $fees['maker'],
            'contractSize' => null,
            'expiry' => null,
            'expiryDatetime' => null,
            'strike' => null,
            'optionType' => null,
            'precision' => array(
                'amount' => $this->parse_number($this->parse_precision($this->safe_string($market, 'amountDecimals'))),
                'price' => $pricePrecision,
            ),
            'limits' => array(
                'leverage' => array(
                    'min' => null,
                    'max' => null,
                ),
                'amount' => array(
                    'min' => $minAmount,
                    'max' => $maxAmount,
                ),
                'price' => array(
                    'min' => $minPrice,
                    'max' => null,
                ),
                'cost' => array(
                    'min' => null,
                    'max' => null,
                ),
            ),
            'created' => null,
            'info' => $market,
        );
    }

    public function fetch_time($params = array ()): PromiseInterface {
        return Async\async(function () use ($params) {
            /**
             * fetches the current integer timestamp in milliseconds from the exchange server
             *
             * @see https://docs.btcmarkets.net/v3/#tag/Misc-APIs/paths/{1v3}1time/get
             *
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {int} the current integer timestamp in milliseconds from the exchange server
             */
            $response = Async\await($this->publicGetTime ($params));
            //
            //     {
            //         "timestamp" => "2019-09-01T18:34:27.045000Z"
            //     }
            //
            return $this->parse8601($this->safe_string($response, 'timestamp'));
        }) ();
    }

    public function parse_balance($response): array {
        $result = array( 'info' => $response );
        for ($i = 0; $i < count($response); $i++) {
            $balance = $response[$i];
            $currencyId = $this->safe_string($balance, 'assetName');
            $code = $this->safe_currency_code($currencyId);
            $account = $this->account();
            $account['used'] = $this->safe_string($balance, 'locked');
            $account['total'] = $this->safe_string($balance, 'balance');
            $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://docs.btcmarkets.net/v3/#tag/Account-APIs/paths/{1v3}1accounts{1me}1balances/get
             *
             * @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->privateGetAccountsMeBalances ($params));
            return $this->parse_balance($response);
        }) ();
    }

    public function parse_ohlcv($ohlcv, ?array $market = null): array {
        //
        //     array(
        //         "2020-09-12T18:30:00.000000Z",
        //         "14409.45", // open
        //         "14409.45", // high
        //         "14403.91", // low
        //         "14403.91", // close
        //         "0.01571701" // volume
        //     )
        //
        return array(
            $this->parse8601($this->safe_string($ohlcv, 0)),
            $this->safe_number($ohlcv, 1), // open
            $this->safe_number($ohlcv, 2), // high
            $this->safe_number($ohlcv, 3), // low
            $this->safe_number($ohlcv, 4), // close
            $this->safe_number($ohlcv, 5), // 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://docs.btcmarkets.net/v3/#tag/Market-Data-APIs/paths/{1v3}1markets{1}marketId~~1candles/get
             *
             * @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);
            $request = array(
                'marketId' => $market['id'],
                'timeWindow' => $this->safe_string($this->timeframes, $timeframe, $timeframe),
                // 'from' => $this->iso8601($since),
                // 'to' => $this->iso8601($this->milliseconds()),
                // 'before' => 1234567890123,
                // 'after' => 1234567890123,
                // 'limit' => $limit, // default 10, max 200
            );
            if ($since !== null) {
                $request['from'] = $this->iso8601($since);
            }
            if ($limit !== null) {
                $request['limit'] = min ($limit, 200); // default is 10, max 200
            }
            $response = Async\await($this->publicGetMarketsMarketIdCandles ($this->extend($request, $params)));
            //
            //     [
            //         ["2020-09-12T18:30:00.000000Z","14409.45","14409.45","14403.91","14403.91","0.01571701"],
            //         ["2020-09-12T18:21:00.000000Z","14409.45","14409.45","14409.45","14409.45","0.0035"],
            //         ["2020-09-12T18:03:00.000000Z","14361.37","14361.37","14361.37","14361.37","0.00345221"],
            //     ]
            //
            return $this->parse_ohlcvs($response, $market, $timeframe, $since, $limit);
        }) ();
    }

    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://docs.btcmarkets.net/v3/#tag/Market-Data-APIs/paths/{1v3}1markets{1}marketId~~1orderbook/get
             *
             * @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(
                'marketId' => $market['id'],
            );
            $response = Async\await($this->publicGetMarketsMarketIdOrderbook ($this->extend($request, $params)));
            //
            //     {
            //         "marketId":"BTC-AUD",
            //         "snapshotId":1599936148941000,
            //         "asks":[
            //             ["14459.45","0.00456475"],
            //             ["14463.56","2"],
            //             ["14470.91","0.98"],
            //         ],
            //         "bids":[
            //             ["14421.01","0.52"],
            //             ["14421","0.75"],
            //             ["14418","0.3521"],
            //         ]
            //     }
            //
            $timestamp = $this->safe_integer_product($response, 'snapshotId', 0.001);
            $orderbook = $this->parse_order_book($response, $symbol, $timestamp);
            $orderbook['nonce'] = $this->safe_integer($response, 'snapshotId');
            return $orderbook;
        }) ();
    }

    public function parse_ticker(array $ticker, ?array $market = null): array {
        //
        // fetchTicker
        //
        //     {
        //         "marketId":"BAT-AUD",
        //         "bestBid":"0.3751",
        //         "bestAsk":"0.377",
        //         "lastPrice":"0.3769",
        //         "volume24h":"56192.97613335",
        //         "volumeQte24h":"21179.13270465",
        //         "price24h":"0.0119",
        //         "pricePct24h":"3.26",
        //         "low24h":"0.3611",
        //         "high24h":"0.3799",
        //         "timestamp":"2020-08-09T18:28:23.280000Z"
        //     }
        //
        $marketId = $this->safe_string($ticker, 'marketId');
        $market = $this->safe_market($marketId, $market, '-');
        $symbol = $market['symbol'];
        $timestamp = $this->parse8601($this->safe_string($ticker, 'timestamp'));
        $last = $this->safe_string($ticker, 'lastPrice');
        $baseVolume = $this->safe_string($ticker, 'volume24h');
        $quoteVolume = $this->safe_string($ticker, 'volumeQte24h');
        $change = $this->safe_string($ticker, 'price24h');
        $percentage = $this->safe_string($ticker, 'pricePct24h');
        return $this->safe_ticker(array(
            'symbol' => $symbol,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'high' => $this->safe_string($ticker, 'high24h'),
            'low' => $this->safe_string($ticker, 'low'),
            'bid' => $this->safe_string($ticker, 'bestBid'),
            'bidVolume' => null,
            'ask' => $this->safe_string($ticker, 'bestAsk'),
            'askVolume' => null,
            'vwap' => null,
            'open' => null,
            'close' => $last,
            'last' => $last,
            'previousClose' => null,
            'change' => $change,
            'percentage' => $percentage,
            'average' => null,
            'baseVolume' => $baseVolume,
            'quoteVolume' => $quoteVolume,
            '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://docs.btcmarkets.net/v3/#tag/Market-Data-APIs/paths/{1v3}1markets{1}marketId~~1ticker/get
             *
             * @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(
                'marketId' => $market['id'],
            );
            $response = Async\await($this->publicGetMarketsMarketIdTicker ($this->extend($request, $params)));
            //
            //     {
            //         "marketId":"BAT-AUD",
            //         "bestBid":"0.3751",
            //         "bestAsk":"0.377",
            //         "lastPrice":"0.3769",
            //         "volume24h":"56192.97613335",
            //         "volumeQte24h":"21179.13270465",
            //         "price24h":"0.0119",
            //         "pricePct24h":"3.26",
            //         "low24h":"0.3611",
            //         "high24h":"0.3799",
            //         "timestamp":"2020-08-09T18:28:23.280000Z"
            //     }
            //
            return $this->parse_ticker($response, $market);
        }) ();
    }

    public function fetch_ticker_2(string $symbol, $params = array ()) {
        return Async\async(function () use ($symbol, $params) {
            Async\await($this->load_markets());
            $market = $this->market($symbol);
            $request = array(
                'id' => $market['id'],
            );
            $response = Async\await($this->publicGetMarketsMarketIdTicker ($this->extend($request, $params)));
            return $this->parse_ticker($response, $market);
        }) ();
    }

    public function parse_trade(array $trade, ?array $market = null): array {
        //
        // public fetchTrades
        //
        //     {
        //         "id":"6191646611",
        //         "price":"539.98",
        //         "amount":"0.5",
        //         "timestamp":"2020-08-09T15:21:05.016000Z",
        //         "side":"Ask"
        //     }
        //
        // private fetchMyTrades
        //
        //     {
        //         "id" => "36014819",
        //         "marketId" => "XRP-AUD",
        //         "timestamp" => "2019-06-25T16:01:02.977000Z",
        //         "price" => "0.67",
        //         "amount" => "1.50533262",
        //         "side" => "Ask",
        //         "fee" => "0.00857285",
        //         "orderId" => "3648306",
        //         "liquidityType" => "Taker",
        //         "clientOrderId" => "48"
        //     }
        //
        $timestamp = $this->parse8601($this->safe_string($trade, 'timestamp'));
        $marketId = $this->safe_string($trade, 'marketId');
        $market = $this->safe_market($marketId, $market, '-');
        $feeCurrencyCode = ($market['quote'] === 'AUD') ? $market['quote'] : $market['base'];
        $side = $this->safe_string($trade, 'side');
        if ($side === 'Bid') {
            $side = 'buy';
        } elseif ($side === 'Ask') {
            $side = 'sell';
        }
        $id = $this->safe_string($trade, 'id');
        $priceString = $this->safe_string($trade, 'price');
        $amountString = $this->safe_string($trade, 'amount');
        $orderId = $this->safe_string($trade, 'orderId');
        $fee = null;
        $feeCostString = $this->safe_string($trade, 'fee');
        if ($feeCostString !== null) {
            $fee = array(
                'cost' => $feeCostString,
                'currency' => $feeCurrencyCode,
            );
        }
        $takerOrMaker = $this->safe_string_lower($trade, 'liquidityType');
        return $this->safe_trade(array(
            'info' => $trade,
            'id' => $id,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'order' => $orderId,
            'symbol' => $market['symbol'],
            'type' => null,
            'side' => $side,
            'price' => $priceString,
            'amount' => $amountString,
            'cost' => null,
            'takerOrMaker' => $takerOrMaker,
            '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://docs.btcmarkets.net/v3/#tag/Market-Data-APIs/paths/{1v3}1markets{1}marketId~~1trades/get
             *
             * @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(
                // 'since' => 59868345231,
                'marketId' => $market['id'],
            );
            $response = Async\await($this->publicGetMarketsMarketIdTrades ($this->extend($request, $params)));
            //
            //     array(
            //         array("id":"6191646611","price":"539.98","amount":"0.5","timestamp":"2020-08-09T15:21:05.016000Z","side":"Ask"),
            //         array("id":"6191646610","price":"539.99","amount":"0.5","timestamp":"2020-08-09T15:21:05.015000Z","side":"Ask"),
            //         array("id":"6191646590","price":"540","amount":"0.00233785","timestamp":"2020-08-09T15:21:04.171000Z","side":"Bid"),
            //     )
            //
            return $this->parse_trades($response, $market, $since, $limit);
        }) ();
    }

    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://docs.btcmarkets.net/v3/#tag/Order-Placement-APIs/paths/{1v3}1orders/post
             *
             * @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 {float} [$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(
                'marketId' => $market['id'],
                // 'price' => $this->price_to_precision($symbol, $price),
                'amount' => $this->amount_to_precision($symbol, $amount),
                // 'type' => 'Limit', // "Limit", "Market", "Stop Limit", "Stop", "Take Profit"
                'side' => ($side === 'buy') ? 'Bid' : 'Ask',
                // 'triggerPrice' => $this->price_to_precision($symbol, $triggerPrice), // required for Stop, Stop Limit, Take Profit orders
                // 'targetAmount' => $this->amount_to_precision($symbol, targetAmount), // target $amount when a desired target outcome is required for order execution
                // 'timeInForce' => 'GTC', // GTC, FOK, IOC
                // 'postOnly' => false, // boolean if this is a post-only order
                // 'selfTrade' => 'A', // A = allow, P = prevent
                // 'clientOrderId' => $this->uuid(),
            );
            $lowercaseType = strtolower($type);
            $orderTypes = $this->safe_value($this->options, 'orderTypes', array(
                'limit' => 'Limit',
                'market' => 'Market',
                'stop' => 'Stop',
                'stop limit' => 'Stop Limit',
                'take profit' => 'Take Profit',
            ));
            $request['type'] = $this->safe_string($orderTypes, $lowercaseType, $type);
            $priceIsRequired = false;
            $triggerPriceIsRequired = false;
            if ($lowercaseType === 'limit') {
                $priceIsRequired = true;
            // } elseif ($lowercaseType === 'market') {
            //     ...
            // }
            } elseif ($lowercaseType === 'stop limit') {
                $triggerPriceIsRequired = true;
                $priceIsRequired = true;
            } elseif ($lowercaseType === 'take profit') {
                $triggerPriceIsRequired = true;
            } elseif ($lowercaseType === 'stop') {
                $triggerPriceIsRequired = true;
            }
            if ($priceIsRequired) {
                if ($price === null) {
                    throw new ArgumentsRequired($this->id . ' createOrder() requires a $price argument for a ' . $type . 'order');
                } else {
                    $request['price'] = $this->price_to_precision($symbol, $price);
                }
            }
            if ($triggerPriceIsRequired) {
                $triggerPrice = $this->safe_number($params, 'triggerPrice');
                $params = $this->omit($params, 'triggerPrice');
                if ($triggerPrice === null) {
                    throw new ArgumentsRequired($this->id . ' createOrder() requires a $triggerPrice parameter for a ' . $type . 'order');
                } else {
                    $request['triggerPrice'] = $this->price_to_precision($symbol, $triggerPrice);
                }
            }
            $clientOrderId = $this->safe_string($params, 'clientOrderId');
            if ($clientOrderId !== null) {
                $request['clientOrderId'] = $clientOrderId;
            }
            $params = $this->omit($params, 'clientOrderId');
            $response = Async\await($this->privatePostOrders ($this->extend($request, $params)));
            //
            //     {
            //         "orderId" => "7524",
            //         "marketId" => "BTC-AUD",
            //         "side" => "Bid",
            //         "type" => "Limit",
            //         "creationTime" => "2019-08-30T11:08:21.956000Z",
            //         "price" => "100.12",
            //         "amount" => "1.034",
            //         "openAmount" => "1.034",
            //         "status" => "Accepted",
            //         "clientOrderId" => "1234-5678",
            //         "timeInForce" => "IOC",
            //         "postOnly" => false,
            //         "selfTrade" => "P",
            //         "triggerAmount" => "105",
            //         "targetAmount" => "1000"
            //     }
            //
            return $this->parse_order($response, $market);
        }) ();
    }

    public function cancel_orders($ids, ?string $symbol = null, $params = array ()) {
        return Async\async(function () use ($ids, $symbol, $params) {
            /**
             * cancel multiple $orders
             *
             * @see https://docs.btcmarkets.net/v3/#tag/Batch-Order-APIs/paths/{1v3}1batchorders{1}$ids~/delete
             *
             * @param {string[]} $ids order $ids
             * @param {string} $symbol not used by btcmarkets $cancelOrders ()
             * @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~
             */
            Async\await($this->load_markets());
            for ($i = 0; $i < count($ids); $i++) {
                $ids[$i] = intval($ids[$i]);
            }
            $request = array(
                'ids' => $ids,
            );
            $response = Async\await($this->privateDeleteBatchordersIds ($this->extend($request, $params)));
            //
            //    {
            //       "cancelOrders" => array(
            //            array(
            //               "orderId" => "414186",
            //               "clientOrderId" => "6"
            //            ),
            //            ...
            //        ),
            //        "unprocessedRequests" => array(
            //            {
            //               "code" => "OrderAlreadyCancelled",
            //               "message" => "order is already cancelled.",
            //               "requestId" => "1"
            //            }
            //        )
            //    }
            //
            $cancelOrders = $this->safe_list($response, 'cancelOrders', array());
            $unprocessedRequests = $this->safe_list($response, 'unprocessedRequests', array());
            $orders = $this->array_concat($cancelOrders, $unprocessedRequests);
            return $this->parse_orders($orders);
        }) ();
    }

    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://docs.btcmarkets.net/v3/#operation/cancelOrder
             *
             * @param {string} $id order $id
             * @param {string} $symbol not used by btcmarket cancelOrder ()
             * @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());
            $request = array(
                'id' => $id,
            );
            $response = Async\await($this->privateDeleteOrdersId ($this->extend($request, $params)));
            //
            //    {
            //        "orderId" => "7524",
            //        "clientOrderId" => "123-456"
            //    }
            //
            return $this->parse_order($response);
        }) ();
    }

    public function calculate_fee($symbol, $type, $side, $amount, $price, $takerOrMaker = 'taker', $params = array ()) {
        /**
         * calculates the presumptive fee that would be charged for an order
         * @param {string} $symbol unified $market $symbol
         * @param {string} $type not used by btcmarkets.calculateFee
         * @param {string} $side not used by btcmarkets.calculateFee
         * @param {float} $amount how much you want to trade, in units of the base $currency on most exchanges, or number of contracts
         * @param {float} $price the $price for the order to be filled at, in units of the quote $currency
         * @param {string} $takerOrMaker 'taker' or 'maker'
         * @param {array} $params
         * @return {array} contains the $rate, the percentage multiplied to the order $amount to obtain the fee $amount, and $cost, the total value of the fee in units of the quote $currency, for the order
         */
        $market = $this->markets[$symbol];
        $currency = null;
        $cost = null;
        if ($market['quote'] === 'AUD') {
            $currency = $market['quote'];
            $amountString = $this->number_to_string($amount);
            $priceString = $this->number_to_string($price);
            $otherUnitsAmount = Precise::string_mul($amountString, $priceString);
            $cost = $this->cost_to_precision($symbol, $otherUnitsAmount);
        } else {
            $currency = $market['base'];
            $cost = $this->amount_to_precision($symbol, $amount);
        }
        $rate = $market[$takerOrMaker];
        $rateCost = Precise::string_mul($this->number_to_string($rate), $cost);
        return array(
            'type' => $takerOrMaker,
            'currency' => $currency,
            'rate' => $rate,
            'cost' => floatval($this->fee_to_precision($symbol, $rateCost)),
        );
    }

    public function parse_order_status(?string $status) {
        $statuses = array(
            'Accepted' => 'open',
            'Placed' => 'open',
            'Partially Matched' => 'open',
            'Fully Matched' => 'closed',
            'Cancelled' => 'canceled',
            'Partially Cancelled' => 'canceled',
            'Failed' => 'rejected',
        );
        return $this->safe_string($statuses, $status, $status);
    }

    public function parse_order(array $order, ?array $market = null): array {
        //
        // createOrder
        //
        //     {
        //         "orderId" => "7524",
        //         "marketId" => "BTC-AUD",
        //         "side" => "Bid",
        //         "type" => "Limit",
        //         "creationTime" => "2019-08-30T11:08:21.956000Z",
        //         "price" => "100.12",
        //         "amount" => "1.034",
        //         "openAmount" => "1.034",
        //         "status" => "Accepted",
        //         "clientOrderId" => "1234-5678",
        //         "timeInForce" => "IOC",
        //         "postOnly" => false,
        //         "selfTrade" => "P",
        //         "triggerAmount" => "105",
        //         "targetAmount" => "1000"
        //     }
        //
        $timestamp = $this->parse8601($this->safe_string($order, 'creationTime'));
        $marketId = $this->safe_string($order, 'marketId');
        $market = $this->safe_market($marketId, $market, '-');
        $side = $this->safe_string($order, 'side');
        if ($side === 'Bid') {
            $side = 'buy';
        } elseif ($side === 'Ask') {
            $side = 'sell';
        }
        $type = $this->safe_string_lower($order, 'type');
        $price = $this->safe_string($order, 'price');
        $amount = $this->safe_string($order, 'amount');
        $remaining = $this->safe_string($order, 'openAmount');
        $status = $this->parse_order_status($this->safe_string($order, 'status'));
        $id = $this->safe_string($order, 'orderId');
        $clientOrderId = $this->safe_string($order, 'clientOrderId');
        $timeInForce = $this->safe_string($order, 'timeInForce');
        $postOnly = $this->safe_bool($order, 'postOnly');
        return $this->safe_order(array(
            'info' => $order,
            'id' => $id,
            'clientOrderId' => $clientOrderId,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'lastTradeTimestamp' => null,
            'symbol' => $market['symbol'],
            'type' => $type,
            'timeInForce' => $timeInForce,
            'postOnly' => $postOnly,
            'side' => $side,
            'price' => $price,
            'triggerPrice' => $this->safe_number($order, 'triggerPrice'),
            'cost' => null,
            'amount' => $amount,
            'filled' => null,
            'remaining' => $remaining,
            'average' => null,
            'status' => $status,
            'trades' => null,
            'fee' => null,
        ), $market);
    }

    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://docs.btcmarkets.net/v3/#operation/getOrderById
             *
             * @param {string} $id the order $id
             * @param {string} $symbol not used by btcmarkets 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~
             */
            Async\await($this->load_markets());
            $request = array(
                'id' => $id,
            );
            $response = Async\await($this->privateGetOrdersId ($this->extend($request, $params)));
            return $this->parse_order($response);
        }) ();
    }

    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://docs.btcmarkets.net/v3/#operation/listOrders
             *
             * @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~
             */
            Async\await($this->load_markets());
            $request = array(
                'status' => 'all',
            );
            $market = null;
            if ($symbol !== null) {
                $market = $this->market($symbol);
                $request['marketId'] = $market['id'];
            }
            if ($since !== null) {
                $request['after'] = $since;
            }
            if ($limit !== null) {
                $request['limit'] = $limit;
            }
            $response = Async\await($this->privateGetOrders ($this->extend($request, $params)));
            return $this->parse_orders($response, $market, $since, $limit);
        }) ();
    }

    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://docs.btcmarkets.net/v3/#operation/listOrders
             *
             * @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~
             */
            $request = array( 'status' => 'open' );
            return Async\await($this->fetch_orders($symbol, $since, $limit, $this->extend($request, $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://docs.btcmarkets.net/v3/#operation/listOrders
             *
             * @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~
             */
            $orders = Async\await($this->fetch_orders($symbol, $since, $limit, $params));
            return $this->filter_by($orders, 'status', 'closed');
        }) ();
    }

    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://docs.btcmarkets.net/v3/#operation/getTrades
             *
             * @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();
            $market = null;
            if ($symbol !== null) {
                $market = $this->market($symbol);
                $request['marketId'] = $market['id'];
            }
            if ($since !== null) {
                $request['after'] = $since;
            }
            if ($limit !== null) {
                $request['limit'] = $limit;
            }
            $response = Async\await($this->privateGetTrades ($this->extend($request, $params)));
            //
            //     array(
            //         array(
            //             "id" => "36014819",
            //             "marketId" => "XRP-AUD",
            //             "timestamp" => "2019-06-25T16:01:02.977000Z",
            //             "price" => "0.67",
            //             "amount" => "1.50533262",
            //             "side" => "Ask",
            //             "fee" => "0.00857285",
            //             "orderId" => "3648306",
            //             "liquidityType" => "Taker",
            //             "clientOrderId" => "48"
            //         ),
            //         {
            //             "id" => "3568960",
            //             "marketId" => "GNT-AUD",
            //             "timestamp" => "2019-06-20T08:44:04.488000Z",
            //             "price" => "0.1362",
            //             "amount" => "0.85",
            //             "side" => "Bid",
            //             "fee" => "0.00098404",
            //             "orderId" => "3543015",
            //             "liquidityType" => "Maker"
            //         }
            //     )
            //
            return $this->parse_trades($response, $market, $since, $limit);
        }) ();
    }

    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://docs.btcmarkets.net/v3/#tag/Fund-Management-APIs/paths/{1v3}1withdrawals/post
             *
             * @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());
            $currency = $this->currency($code);
            $request = array(
                'currency_id' => $currency['id'],
                'amount' => $this->currency_to_precision($code, $amount),
            );
            if ($code !== 'AUD') {
                $this->check_address($address);
                $request['toAddress'] = $address;
            }
            if ($tag !== null) {
                $request['toAddress'] = $address . '?dt=' . $tag;
            }
            $response = Async\await($this->privatePostWithdrawals ($this->extend($request, $params)));
            //
            //      {
            //          "id" => "4126657",
            //          "assetName" => "XRP",
            //          "amount" => "25",
            //          "type" => "Withdraw",
            //          "creationTime" => "2019-09-04T00:04:10.973000Z",
            //          "status" => "Pending Authorization",
            //          "description" => "XRP withdraw from [me@test.com] to Address => abc $amount => 25 fee => 0",
            //          "fee" => "0",
            //          "lastUpdate" => "2019-09-04T00:04:11.018000Z",
            //          "paymentDetail" => {
            //              "address" => "abc"
            //          }
            //      }
            //
            return $this->parse_transaction($response, $currency);
        }) ();
    }

    public function nonce() {
        return $this->milliseconds();
    }

    public function sign($path, $api = 'public', $method = 'GET', $params = array (), $headers = null, $body = null) {
        $request = '/' . $this->version . '/' . $this->implode_params($path, $params);
        $query = $this->keysort($this->omit($params, $this->extract_params($path)));
        if ($api === 'private') {
            $this->check_required_credentials();
            $nonce = (string) $this->nonce();
            $secret = base64_decode($this->secret);
            $auth = $method . $request . $nonce;
            if (($method === 'GET') || ($method === 'DELETE')) {
                if ($query) {
                    $request .= '?' . $this->urlencode($query);
                }
            } else {
                $body = $this->json($query);
                $auth .= $body;
            }
            $signature = $this->hmac($this->encode($auth), $secret, 'sha512', 'base64');
            $headers = array(
                'Accept' => 'application/json',
                'Accept-Charset' => 'UTF-8',
                'Content-Type' => 'application/json',
                'BM-AUTH-APIKEY' => $this->apiKey,
                'BM-AUTH-TIMESTAMP' => $nonce,
                'BM-AUTH-SIGNATURE' => $signature,
            );
        } elseif ($api === 'public') {
            if ($query) {
                $request .= '?' . $this->urlencode($query);
            }
        }
        $url = $this->urls['api'][$api] . $request;
        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 default error handler
        }
        //
        //     array("code":"UnAuthorized","message":"invalid access token")
        //     array("code":"MarketNotFound","message":"invalid marketId")
        //
        $errorCode = $this->safe_string($response, 'code');
        $message = $this->safe_string($response, 'message');
        if ($errorCode !== null) {
            $feedback = $this->id . ' ' . $body;
            $this->throw_exactly_matched_exception($this->exceptions['exact'], $message, $feedback);
            $this->throw_exactly_matched_exception($this->exceptions['exact'], $errorCode, $feedback);
            $this->throw_broadly_matched_exception($this->exceptions['broad'], $message, $feedback);
            throw new ExchangeError($feedback); // unknown $message
        }
        return null;
    }
}
