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

class btcbox extends Exchange {

    public function describe(): mixed {
        return $this->deep_extend(parent::describe(), array(
            'id' => 'btcbox',
            'name' => 'BtcBox',
            'countries' => array( 'JP' ),
            'rateLimit' => 1000,
            'version' => 'v1',
            'pro' => false,
            'has' => array(
                'CORS' => null,
                'spot' => true,
                'margin' => false,
                'swap' => false,
                'future' => false,
                'option' => false,
                'addMargin' => false,
                'borrowCrossMargin' => false,
                'borrowIsolatedMargin' => false,
                'borrowMargin' => false,
                'cancelOrder' => true,
                'closeAllPositions' => false,
                'closePosition' => false,
                'createOrder' => true,
                'createOrderWithTakeProfitAndStopLoss' => false,
                'createOrderWithTakeProfitAndStopLossWs' => false,
                'createPostOnlyOrder' => false,
                'createReduceOnlyOrder' => false,
                'fetchBalance' => true,
                'fetchBorrowInterest' => false,
                'fetchBorrowRate' => false,
                'fetchBorrowRateHistories' => false,
                'fetchBorrowRateHistory' => false,
                'fetchBorrowRates' => false,
                'fetchBorrowRatesPerSymbol' => false,
                'fetchCrossBorrowRate' => false,
                'fetchCrossBorrowRates' => false,
                'fetchCurrencies' => false,
                '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,
                'fetchMarkOHLCV' => false,
                'fetchMarkPrices' => false,
                'fetchMyLiquidations' => false,
                'fetchMySettlementHistory' => false,
                '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,
                'fetchTickers' => true,
                'fetchTrades' => true,
                'fetchTransfer' => false,
                'fetchTransfers' => false,
                'fetchVolatilityHistory' => false,
                'fetchWithdrawal' => false,
                'fetchWithdrawals' => false,
                'reduceMargin' => false,
                'repayCrossMargin' => false,
                'repayIsolatedMargin' => false,
                'repayMargin' => false,
                'setLeverage' => false,
                'setMargin' => false,
                'setMarginMode' => false,
                'setPositionMode' => false,
                'transfer' => false,
                'withdraw' => false,
                'ws' => false,
            ),
            'urls' => array(
                'logo' => 'https://github.com/user-attachments/assets/1e2cb499-8d0f-4f8f-9464-3c015cfbc76b',
                'api' => array(
                    'rest' => 'https://www.btcbox.co.jp/api',
                ),
                'www' => 'https://www.btcbox.co.jp/',
                'doc' => 'https://blog.btcbox.jp/en/archives/8762',
                'fees' => 'https://support.btcbox.co.jp/hc/en-us/articles/360001235694-Fees-introduction',
            ),
            'api' => array(
                'public' => array(
                    'get' => array(
                        'depth',
                        'orders',
                        'ticker',
                        'tickers',
                    ),
                ),
                'private' => array(
                    'post' => array(
                        'balance',
                        'trade_add',
                        'trade_cancel',
                        'trade_list',
                        'trade_view',
                        'wallet',
                    ),
                ),
                'webApi' => array(
                    'get' => array(
                        'ajax/coin/coinInfo',
                    ),
                ),
            ),
            'options' => array(
                'fetchMarkets' => array(
                    'webApiEnable' => true, // fetches from WEB
                    'webApiRetries' => 3,
                ),
                'amountPrecision' => '0.0001', // exchange has only few pairs and all of them
            ),
            'features' => array(
                'spot' => array(
                    'sandbox' => false,
                    'createOrder' => array(
                        'marginMode' => false,
                        'triggerPrice' => false,
                        'triggerPriceType' => null,
                        'triggerDirection' => false,
                        'stopLossPrice' => false,
                        'takeProfitPrice' => false,
                        'attachedStopLossTakeProfit' => null,
                        'timeInForce' => array(
                            'IOC' => false,
                            'FOK' => false,
                            'PO' => false,
                            'GTD' => false,
                        ),
                        'hedged' => false,
                        'leverage' => false,
                        'marketBuyRequiresPrice' => false,
                        'marketBuyByCost' => false,
                        'selfTradePrevention' => false,
                        'trailing' => false,
                        'iceberg' => false,
                    ),
                    'createOrders' => null,
                    'fetchMyTrades' => null,
                    'fetchOrder' => array(
                        'marginMode' => false,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => true,
                    ),
                    'fetchOpenOrders' => array(
                        'marginMode' => false,
                        'limit' => 100,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => true,
                    ),
                    'fetchOrders' => array(
                        'marginMode' => false,
                        'limit' => 100,
                        'daysBack' => null,
                        'untilDays' => null,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => true,
                    ),
                    'fetchClosedOrders' => null,
                    'fetchOHLCV' => null,
                ),
                'swap' => array(
                    'linear' => null,
                    'inverse' => null,
                ),
                'future' => array(
                    'linear' => null,
                    'inverse' => null,
                ),
            ),
            'precisionMode' => TICK_SIZE,
            'exceptions' => array(
                '104' => '\\ccxt\\AuthenticationError',
                '105' => '\\ccxt\\PermissionDenied',
                '106' => '\\ccxt\\InvalidNonce',
                '107' => '\\ccxt\\InvalidOrder', // price should be an integer
                '200' => '\\ccxt\\InsufficientFunds',
                '201' => '\\ccxt\\InvalidOrder', // amount too small
                '202' => '\\ccxt\\InvalidOrder', // price should be [0 : 1000000]
                '203' => '\\ccxt\\OrderNotFound',
                '401' => '\\ccxt\\OrderNotFound', // cancel canceled, closed or non-existent order
                '402' => '\\ccxt\\DDoSProtection',
            ),
        ));
    }

    public function fetch_markets($params = array ()): PromiseInterface {
        return Async\async(function () use ($params) {
            /**
             * retrieves data on all $markets for ace
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array[]} an array of objects representing market data
             */
            $promise1 = $this->publicGetTickers ();
            $promise2 = $this->fetch_web_endpoint('fetchMarkets', 'webApiGetAjaxCoinCoinInfo', true);
            list($response1, $response2) = Async\await(Promise\all(array( $promise1, $promise2 )));
            //
            $result2Data = $this->safe_dict($response2, 'data', array());
            $marketIds = is_array($response1) ? array_keys($response1) : array();
            $markets = array();
            for ($i = 0; $i < count($marketIds); $i++) {
                $marketId = $marketIds[$i];
                $symbolParts = explode('_', $marketId);
                $baseCurr = $this->safe_string($symbolParts, 0);
                $quote = $this->safe_string($symbolParts, 1);
                $quoteId = strtolower($quote);
                $id = strtolower($baseCurr);
                $res = $response1[$marketId];
                $symbol = $baseCurr . '/' . $quote;
                $fee = ($id === 'BTC') ? $this->parse_number('0.0005') : $this->parse_number('0.0010');
                $details = $this->safe_dict($result2Data, $id, array());
                $tradeDetails = $this->safe_dict($details, 'trade', array());
                $markets[] = $this->safe_market_structure(array(
                    'id' => $id,
                    'uppercaseId' => null,
                    'symbol' => $symbol,
                    'base' => $baseCurr,
                    'baseId' => $id,
                    'quote' => $quote,
                    'quoteId' => $quoteId,
                    'settle' => null,
                    'settleId' => null,
                    'type' => 'spot',
                    'spot' => true,
                    'margin' => false,
                    'swap' => false,
                    'future' => false,
                    'option' => false,
                    'taker' => $fee,
                    'maker' => $fee,
                    'contract' => false,
                    'linear' => null,
                    'inverse' => null,
                    'contractSize' => null,
                    'expiry' => null,
                    'expiryDatetime' => null,
                    'strike' => null,
                    'optionType' => null,
                    'limits' => array(
                        'amount' => array(
                            'min' => null,
                            'max' => null,
                        ),
                        'price' => array(
                            'min' => null,
                            'max' => null,
                        ),
                        'cost' => array(
                            'min' => null,
                            'max' => null,
                        ),
                        'leverage' => array(
                            'min' => null,
                            'max' => null,
                        ),
                    ),
                    'precision' => array(
                        'price' => $this->parse_number($this->parse_precision($this->safe_string($tradeDetails, 'pricedecimal'))),
                        'amount' => null,
                    ),
                    'active' => $this->safe_string($tradeDetails, 'enable') === '1',
                    'created' => null,
                    'info' => $res,
                ));
            }
            return $markets;
        }) ();
    }

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

    public function parse_balance($response): array {
        $result = array( 'info' => $response );
        $codes = is_array($this->currencies) ? array_keys($this->currencies) : array();
        for ($i = 0; $i < count($codes); $i++) {
            $code = $codes[$i];
            $currency = $this->currency($code);
            $currencyId = $currency['id'];
            $free = $currencyId . '_balance';
            if (is_array($response) && array_key_exists($free, $response)) {
                $account = $this->account();
                $used = $currencyId . '_lock';
                $account['free'] = $this->safe_string($response, $free);
                $account['used'] = $this->safe_string($response, $used);
                $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://blog.btcbox.jp/en/archives/8762#toc13
             *
             * @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->privatePostBalance ($params));
            return $this->parse_balance($response);
        }) ();
    }

    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://blog.btcbox.jp/en/archives/8762#toc6
             *
             * @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();
            $numSymbols = count($this->symbols);
            if ($numSymbols > 1) {
                $request['coin'] = $market['baseId'];
            }
            $response = Async\await($this->publicGetDepth ($this->extend($request, $params)));
            return $this->parse_order_book($response, $market['symbol']);
        }) ();
    }

    public function parse_ticker(array $ticker, ?array $market = null): array {
        $symbol = $this->safe_symbol(null, $market);
        $last = $this->safe_string($ticker, 'last');
        return $this->safe_ticker(array(
            'symbol' => $symbol,
            'timestamp' => null,
            'datetime' => null,
            'high' => $this->safe_string($ticker, 'high'),
            'low' => $this->safe_string($ticker, 'low'),
            'bid' => $this->safe_string($ticker, 'buy'),
            'bidVolume' => null,
            'ask' => $this->safe_string($ticker, 'sell'),
            'askVolume' => null,
            'vwap' => null,
            'open' => null,
            'close' => $last,
            'last' => $last,
            'previousClose' => null,
            'change' => null,
            'percentage' => null,
            'average' => null,
            'baseVolume' => $this->safe_string($ticker, 'vol'),
            'quoteVolume' => $this->safe_string($ticker, 'volume'),
            '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://blog.btcbox.jp/en/archives/8762#toc5
             *
             * @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();
            $numSymbols = count($this->symbols);
            if ($numSymbols > 1) {
                $request['coin'] = $market['baseId'];
            }
            $response = Async\await($this->publicGetTicker ($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
             * @param {string[]} [$symbols] unified $symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} a dictionary of ~@link https://docs.ccxt.com/#/?id=ticker-structure ticker structures~
             */
            Async\await($this->load_markets());
            $response = Async\await($this->publicGetTickers ($params));
            return $this->parse_tickers($response, $symbols);
        }) ();
    }

    public function parse_trade(array $trade, ?array $market = null): array {
        //
        // fetchTrades (public)
        //
        //      {
        //          "date":"0",
        //          "price":3,
        //          "amount":0.1,
        //          "tid":"1",
        //          "type":"buy"
        //      }
        //
        $timestamp = $this->safe_timestamp($trade, 'date');
        $market = $this->safe_market(null, $market);
        $id = $this->safe_string($trade, 'tid');
        $priceString = $this->safe_string($trade, 'price');
        $amountString = $this->safe_string($trade, 'amount');
        $type = null;
        $side = $this->safe_string($trade, 'type');
        return $this->safe_trade(array(
            'info' => $trade,
            'id' => $id,
            'order' => null,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'symbol' => $market['symbol'],
            'type' => $type,
            'side' => $side,
            'takerOrMaker' => null,
            'price' => $priceString,
            'amount' => $amountString,
            'cost' => null,
            'fee' => null,
        ), $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://blog.btcbox.jp/en/archives/8762#toc7
             *
             * @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();
            $numSymbols = count($this->symbols);
            if ($numSymbols > 1) {
                $request['coin'] = $market['baseId'];
            }
            $response = Async\await($this->publicGetOrders ($this->extend($request, $params)));
            //
            //     array(
            //          array(
            //              "date":"0",
            //              "price":3,
            //              "amount":0.1,
            //              "tid":"1",
            //              "type":"buy"
            //          ),
            //     )
            //
            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://blog.btcbox.jp/en/archives/8762#toc18
             *
             * @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);
            $request = array(
                'amount' => $amount,
                'price' => $price,
                'type' => $side,
                'coin' => $market['baseId'],
            );
            $response = Async\await($this->privatePostTradeAdd ($this->extend($request, $params)));
            //
            //     {
            //         "result":true,
            //         "id":"11"
            //     }
            //
            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://blog.btcbox.jp/en/archives/8762#toc17
             *
             * @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~
             */
            Async\await($this->load_markets());
            // a special case for btcbox – default $symbol is BTC/JPY
            if ($symbol === null) {
                $symbol = 'BTC/JPY';
            }
            $market = $this->market($symbol);
            $request = array(
                'id' => $id,
                'coin' => $market['baseId'],
            );
            $response = Async\await($this->privatePostTradeCancel ($this->extend($request, $params)));
            //
            //     array("result":true, "id":"11")
            //
            return $this->parse_order($response, $market);
        }) ();
    }

    public function parse_order_status(?string $status) {
        $statuses = array(
            // TODO => complete list
            'part' => 'open', // partially or not at all executed
            'all' => 'closed', // fully executed
            'cancelled' => 'canceled',
            'closed' => 'closed', // never encountered, seems to be bug in the doc
            'no' => 'closed', // not clarified in the docs...
        );
        return $this->safe_string($statuses, $status, $status);
    }

    public function parse_order(array $order, ?array $market = null): array {
        //
        //     {
        //         "id":11,
        //         "datetime":"2014-10-21 10:47:20",
        //         "type":"sell",
        //         "price":42000,
        //         "amount_original":1.2,
        //         "amount_outstanding":1.2,
        //         "status":"closed",
        //         "trades":array() // no clarification of trade value structure of $order endpoint
        //     }
        //
        $id = $this->safe_string($order, 'id');
        $datetimeString = $this->safe_string($order, 'datetime');
        $timestamp = null;
        if ($datetimeString !== null) {
            $timestamp = $this->parse8601($order['datetime'] . '+09:00'); // Tokyo time
        }
        $amount = $this->safe_string($order, 'amount_original');
        $remaining = $this->safe_string($order, 'amount_outstanding');
        $price = $this->safe_string($order, 'price');
        // $status is set by fetchOrder method only
        $status = $this->parse_order_status($this->safe_string($order, 'status'));
        // fetchOrders do not return $status, use heuristic
        if ($status === null) {
            if (Precise::string_equals($remaining, '0')) {
                $status = 'closed';
            }
        }
        $trades = null; // todo => $this->parse_trades($order['trades']);
        $market = $this->safe_market(null, $market);
        $side = $this->safe_string($order, 'type');
        return $this->safe_order(array(
            'id' => $id,
            'clientOrderId' => null,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'lastTradeTimestamp' => null,
            'amount' => $amount,
            'remaining' => $remaining,
            'filled' => null,
            'side' => $side,
            'type' => null,
            'timeInForce' => null,
            'postOnly' => null,
            'status' => $status,
            'symbol' => $market['symbol'],
            'price' => $price,
            'triggerPrice' => null,
            'cost' => null,
            'trades' => $trades,
            'fee' => null,
            'info' => $order,
            'average' => 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://blog.btcbox.jp/en/archives/8762#toc16
             *
             * @param {string} $id the order $id
             * @param {string} $symbol unified $symbol of the $market the order was made in
             * @param {array} [$params] extra parameters specific to the exchange API endpoint
             * @return {array} An ~@link https://docs.ccxt.com/#/?$id=order-structure order structure~
             */
            Async\await($this->load_markets());
            // a special case for btcbox – default $symbol is BTC/JPY
            if ($symbol === null) {
                $symbol = 'BTC/JPY';
            }
            $market = $this->market($symbol);
            $request = $this->extend(array(
                'id' => $id,
                'coin' => $market['baseId'],
            ), $params);
            $response = Async\await($this->privatePostTradeView ($this->extend($request, $params)));
            //
            //      {
            //          "id":11,
            //          "datetime":"2014-10-21 10:47:20",
            //          "type":"sell",
            //          "price":42000,
            //          "amount_original":1.2,
            //          "amount_outstanding":1.2,
            //          "status":"closed",
            //          "trades":array()
            //      }
            //
            return $this->parse_order($response, $market);
        }) ();
    }

    public function fetch_orders_by_type($type, ?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()) {
        return Async\async(function () use ($type, $symbol, $since, $limit, $params) {
            Async\await($this->load_markets());
            // a special case for btcbox – default $symbol is BTC/JPY
            $market = $this->market($symbol);
            $request = array(
                'type' => $type, // 'open' or 'all'
                'coin' => $market['baseId'],
            );
            $response = Async\await($this->privatePostTradeList ($this->extend($request, $params)));
            //
            // array(
            //      array(
            //          "id":"7",
            //          "datetime":"2014-10-20 13:27:38",
            //          "type":"buy",
            //          "price":42750,
            //          "amount_original":0.235,
            //          "amount_outstanding":0.235
            //      ),
            // )
            //
            $orders = $this->parse_orders($response, $market, $since, $limit);
            // status (open/closed/canceled) is null
            // btcbox does not return status, but we know it's 'open' queried for open $orders
            if ($type === 'open') {
                for ($i = 0; $i < count($orders); $i++) {
                    $orders[$i]['status'] = 'open';
                }
            }
            return $orders;
        }) ();
    }

    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://blog.btcbox.jp/en/archives/8762#toc15
             *
             * @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~
             */
            return Async\await($this->fetch_orders_by_type('all', $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://blog.btcbox.jp/en/archives/8762#toc15
             *
             * @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~
             */
            return Async\await($this->fetch_orders_by_type('open', $symbol, $since, $limit, $params));
        }) ();
    }

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

    public function sign($path, $api = 'public', $method = 'GET', $params = array (), $headers = null, $body = null) {
        $url = $this->urls['api']['rest'] . '/' . $this->version . '/' . $path;
        if ($api === 'public') {
            if ($params) {
                $url .= '?' . $this->urlencode($params);
            }
        } elseif ($api === 'webApi') {
            $url = $this->urls['www'] . '/' . $path;
        } else {
            $this->check_required_credentials();
            $nonce = (string) $this->nonce();
            $query = $this->extend(array(
                'key' => $this->apiKey,
                'nonce' => $nonce,
            ), $params);
            $request = $this->urlencode($query);
            $secret = $this->hash($this->encode($this->secret), 'md5');
            $query['signature'] = $this->hmac($this->encode($request), $this->encode($secret), 'sha256');
            $body = $this->urlencode($query);
            $headers = array(
                'Content-Type' => 'application/x-www-form-urlencoded',
            );
        }
        return array( 'url' => $url, 'method' => $method, 'body' => $body, 'headers' => $headers );
    }

    public function handle_errors(int $httpCode, string $reason, string $url, string $method, array $headers, string $body, $response, $requestHeaders, $requestBody) {
        if ($response === null) {
            return null; // resort to defaultErrorHandler
        }
        // typical error $response => array("result":false,"code":"401")
        if ($httpCode >= 400) {
            return null; // resort to defaultErrorHandler
        }
        $result = $this->safe_value($response, 'result');
        if ($result === null || $result === true) {
            return null; // either public API (no error codes expected) or success
        }
        $code = $this->safe_value($response, 'code');
        $feedback = $this->id . ' ' . $body;
        $this->throw_exactly_matched_exception($this->exceptions, $code, $feedback);
        throw new ExchangeError($feedback); // unknown message
    }

    public function request($path, $api = 'public', $method = 'GET', $params = array (), $headers = null, $body = null, $config = array ()) {
        return Async\async(function () use ($path, $api, $method, $params, $headers, $body, $config) {
            $response = Async\await($this->fetch2($path, $api, $method, $params, $headers, $body, $config));
            if (gettype($response) === 'string') {
                // sometimes the exchange returns whitespace prepended to json
                $response = $this->strip($response);
                if (!$this->is_json_encoded_object($response)) {
                    throw new ExchangeError($this->id . ' ' . $response);
                }
                $response = json_decode($response, $as_associative_array = true);
            }
            return $response;
        }) ();
    }
}
