<?php

namespace ccxt;

// 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\abstract\coinbaseexchange as Exchange;

class coinbaseexchange extends Exchange {

    public function describe(): mixed {
        return $this->deep_extend(parent::describe(), array(
            'id' => 'coinbaseexchange',
            'name' => 'Coinbase Exchange',
            'countries' => array( 'US' ),
            'rateLimit' => 100,
            'userAgent' => $this->userAgents['chrome'],
            'pro' => true,
            'has' => array(
                'CORS' => true,
                'spot' => true,
                'margin' => false,
                'swap' => false,
                'future' => false,
                'option' => false,
                'addMargin' => false,
                'borrowCrossMargin' => false,
                'borrowIsolatedMargin' => false,
                'borrowMargin' => false,
                'cancelAllOrders' => true,
                'cancelOrder' => true,
                'closeAllPositions' => false,
                'closePosition' => false,
                'createDepositAddress' => true,
                'createOrder' => true,
                'createOrderWithTakeProfitAndStopLoss' => false,
                'createOrderWithTakeProfitAndStopLossWs' => false,
                'createPostOnlyOrder' => false,
                'createReduceOnlyOrder' => false,
                'createStopLimitOrder' => true,
                'createStopMarketOrder' => true,
                'createStopOrder' => true,
                'fetchAccounts' => true,
                'fetchBalance' => true,
                'fetchBorrowInterest' => false,
                'fetchBorrowRate' => false,
                'fetchBorrowRateHistories' => false,
                'fetchBorrowRateHistory' => false,
                'fetchBorrowRates' => false,
                'fetchBorrowRatesPerSymbol' => false,
                'fetchClosedOrders' => true,
                'fetchCrossBorrowRate' => false,
                'fetchCrossBorrowRates' => false,
                'fetchCurrencies' => true,
                'fetchDepositAddress' => false, // the exchange does not have this method, only createDepositAddress, see https://github.com/ccxt/ccxt/pull/7405
                '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,
                'fetchLedger' => true,
                '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,
                'fetchOrderTrades' => true,
                'fetchPosition' => false,
                'fetchPositionHistory' => false,
                'fetchPositionMode' => false,
                'fetchPositions' => false,
                'fetchPositionsForSymbol' => false,
                'fetchPositionsHistory' => false,
                'fetchPositionsRisk' => false,
                'fetchPremiumIndexOHLCV' => false,
                'fetchSettlementHistory' => false,
                'fetchTicker' => true,
                'fetchTickers' => true,
                'fetchTime' => true,
                'fetchTrades' => true,
                'fetchTradingFee' => false,
                'fetchTradingFees' => 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,
            ),
            'timeframes' => array(
                '1m' => 60,
                '5m' => 300,
                '15m' => 900,
                '1h' => 3600,
                '6h' => 21600,
                '1d' => 86400,
            ),
            'hostname' => 'exchange.coinbase.com',
            'urls' => array(
                'test' => array(
                    'public' => 'https://api-public.sandbox.exchange.coinbase.com',
                    'private' => 'https://api-public.sandbox.exchange.coinbase.com',
                ),
                'logo' => 'https://github.com/ccxt/ccxt/assets/43336371/34a65553-88aa-4a38-a714-064bd228b97e',
                'api' => array(
                    'public' => 'https://api.{hostname}',
                    'private' => 'https://api.{hostname}',
                ),
                'www' => 'https://coinbase.com/',
                'doc' => 'https://docs.cloud.coinbase.com/exchange/docs/',
                'fees' => array(
                    'https://docs.pro.coinbase.com/#fees',
                    'https://support.pro.coinbase.com/customer/en/portal/articles/2945310-fees',
                ),
            ),
            'requiredCredentials' => array(
                'apiKey' => true,
                'secret' => true,
                'password' => true,
            ),
            'api' => array(
                'public' => array(
                    'get' => array(
                        'currencies',
                        'products',
                        'products/{id}',
                        'products/{id}/book',
                        'products/{id}/candles',
                        'products/{id}/stats',
                        'products/{id}/ticker',
                        'products/{id}/trades',
                        'time',
                        'products/spark-lines', // experimental,
                        'products/volume-summary',
                    ),
                ),
                'private' => array(
                    'get' => array(
                        'address-book',
                        'accounts',
                        'accounts/{id}',
                        'accounts/{id}/holds',
                        'accounts/{id}/ledger',
                        'accounts/{id}/transfers',
                        'coinbase-accounts',
                        'fills',
                        'funding',
                        'fees',
                        'margin/profile_information',
                        'margin/buying_power',
                        'margin/withdrawal_power',
                        'margin/withdrawal_power_all',
                        'margin/exit_plan',
                        'margin/liquidation_history',
                        'margin/position_refresh_amounts',
                        'margin/status',
                        'oracle',
                        'orders',
                        'orders/{id}',
                        'orders/client:{client_oid}',
                        'otc/orders',
                        'payment-methods',
                        'position',
                        'profiles',
                        'profiles/{id}',
                        'reports/{report_id}',
                        'transfers',
                        'transfers/{transfer_id}',
                        'users/self/exchange-limits',
                        'users/self/hold-balances',
                        'users/self/trailing-volume',
                        'withdrawals/fee-estimate',
                        'conversions/{conversion_id}',
                        'conversions',
                        'conversions/fees',
                        'loans/lending-overview',
                        'loans/lending-overview-xm',
                        'loans/loan-preview',
                        'loans/loan-preview-xm',
                        'loans/repayment-preview',
                        'loans/repayment-preview-xm',
                        'loans/interest/{loan_id}',
                        'loans/interest/history/{loan_id}',
                        'loans/interest',
                        'loans/assets',
                        'loans',
                    ),
                    'post' => array(
                        'conversions',
                        'deposits/coinbase-account',
                        'deposits/payment-method',
                        'coinbase-accounts/{id}/addresses',
                        'funding/repay',
                        'orders',
                        'position/close',
                        'profiles/margin-transfer',
                        'profiles/transfer',
                        'reports',
                        'withdrawals/coinbase',
                        'withdrawals/coinbase-account',
                        'withdrawals/crypto',
                        'withdrawals/payment-method',
                        'loans/open',
                        'loans/repay-interest',
                        'loans/repay-principal',
                    ),
                    'delete' => array(
                        'orders',
                        'orders/client:{client_oid}',
                        'orders/{id}',
                    ),
                ),
            ),
            'commonCurrencies' => array(
                'CGLD' => 'CELO',
            ),
            'precisionMode' => TICK_SIZE,
            'fees' => array(
                'trading' => array(
                    'tierBased' => true, // complicated tier system per coin
                    'percentage' => true,
                    'maker' => $this->parse_number('0.004'), // highest fee of all tiers
                    'taker' => $this->parse_number('0.006'), // highest fee of all tiers
                ),
                'funding' => array(
                    'tierBased' => false,
                    'percentage' => false,
                    'withdraw' => array(
                        'BCH' => 0,
                        'BTC' => 0,
                        'LTC' => 0,
                        'ETH' => 0,
                        'EUR' => 0.15,
                        'USD' => 25,
                    ),
                    'deposit' => array(
                        'BCH' => 0,
                        'BTC' => 0,
                        'LTC' => 0,
                        'ETH' => 0,
                        'EUR' => 0.15,
                        'USD' => 10,
                    ),
                ),
            ),
            'features' => array(
                'default' => array(
                    'sandbox' => true,
                    'createOrder' => array(
                        'marginMode' => true,
                        'triggerPrice' => true,
                        'triggerPriceType' => null,
                        'triggerDirection' => false,
                        'stopLossPrice' => false, // todo
                        'takeProfitPrice' => false, // todo
                        'attachedStopLossTakeProfit' => null,
                        'timeInForce' => array(
                            'IOC' => true,
                            'FOK' => true,
                            'PO' => true,
                            'GTD' => true,
                        ),
                        'hedged' => false,
                        'trailing' => false,
                        'leverage' => false,
                        'marketBuyByCost' => false,
                        'marketBuyRequiresPrice' => false,
                        'selfTradePrevention' => false,
                        'iceberg' => true, // todo => implement
                    ),
                    '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' => 300,
                    ),
                ),
                'spot' => array(
                    'extends' => 'default',
                ),
                'swap' => array(
                    'linear' => null,
                    'inverse' => null,
                ),
                'future' => array(
                    'linear' => null,
                    'inverse' => null,
                ),
            ),
            'options' => array(
                'networks' => array(
                    'BTC' => 'bitcoin',
                    // LIGHTNING unsupported
                    'ETH' => 'ethereum',
                    // TRON unsupported
                    'SOL' => 'solana',
                    // BSC unsupported
                    'ARBONE' => 'arbitrum',
                    'AVAXC' => 'avacchain',
                    'MATIC' => 'polygon',
                    'BASE' => 'base',
                    'SUI' => 'sui',
                    'OP' => 'optimism',
                    'NEAR' => 'near',
                    // CRONOS unsupported
                    // GNO unsupported
                    'APT' => 'aptos',
                    // SCROLL unsupported
                    'KAVA' => 'kava',
                    // TAIKO unsupported
                    // BOB unsupported
                    // LINEA unsupported
                    'BLAST' => 'blast',
                    'XLM' => 'stellar',
                    // RSK unsupported
                    'SEI' => 'sei',
                    // TON unsupported
                    // MANTLE unsupported
                    'ADA' => 'cardano',
                    // HYPE unsupported
                    'CORE' => 'coredao',
                    'ALGO' => 'algorand',
                    // RUNE unsupported
                    'OSMO' => 'osmosis',
                    // XIN unsupported
                    'CELO' => 'celo',
                    'HBAR' => 'hedera',
                    // FTM unsupported
                    // WEMIX unsupported
                    'ZKSYNC' => 'zksync',
                    // KLAY unsupported
                    // HT unsupported
                    // FSN unsupported
                    // EOS unsupported, eosio?
                    // ACA unsupported
                    'STX' => 'stacks',
                    'XTZ' => 'tezos',
                    // NEO unsupported
                    // METIS unsupported
                    // TLOS unsupported
                    'EGLD' => 'elrond',
                    // ASTR unsupported
                    // CFX unsupported
                    // GLMR unsupported
                    // CANTO unsupported
                    // SCRT unsupported
                    'LTC' => 'litecoin',
                    // AURORA unsupported
                    // ONG unsupported
                    'ATOM' => 'cosmos',
                    // CHZ unsupported
                    'FIL' => 'filecoin',
                    'DOT' => 'polkadot',
                    'DOGE' => 'dogecoin',
                    // BRC20 unsupported
                    'XRP' => 'ripple',
                    // XMR unsupported
                    'DASH' => 'dash',
                    // akash, aleo,  axelar, bitcoincash, berachain, deso, ethereumclassic, unichain, flow, flare, dfinity, story,kusama,  mina, ronin, oasis, bittensor, celestia, noble, vara, vechain, zcash, horizen, zetachain
                ),
            ),
            'exceptions' => array(
                'exact' => array(
                    'Insufficient funds' => '\\ccxt\\InsufficientFunds',
                    'NotFound' => '\\ccxt\\OrderNotFound',
                    'Invalid API Key' => '\\ccxt\\AuthenticationError',
                    'invalid signature' => '\\ccxt\\AuthenticationError',
                    'Invalid Passphrase' => '\\ccxt\\AuthenticationError',
                    'Invalid order id' => '\\ccxt\\InvalidOrder',
                    'Private rate limit exceeded' => '\\ccxt\\RateLimitExceeded',
                    'Trading pair not available' => '\\ccxt\\PermissionDenied',
                    'Product not found' => '\\ccxt\\InvalidOrder',
                ),
                'broad' => array(
                    'Order already done' => '\\ccxt\\OrderNotFound',
                    'order not found' => '\\ccxt\\OrderNotFound',
                    'price too small' => '\\ccxt\\InvalidOrder',
                    'price too precise' => '\\ccxt\\InvalidOrder',
                    'under maintenance' => '\\ccxt\\OnMaintenance',
                    'size is too small' => '\\ccxt\\InvalidOrder',
                    'Cancel only mode' => '\\ccxt\\OnMaintenance', // https://github.com/ccxt/ccxt/issues/7690
                ),
            ),
        ));
    }

    public function fetch_currencies($params = array ()): ?array {
        /**
         * fetches all available currencies on an exchange
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getcurrencies
         *
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array} an associative dictionary of currencies
         */
        $response = $this->publicGetCurrencies ($params);
        //
        //   {
        //     "id" => "USDT",
        //     "name" => "Tether",
        //     "min_size" => "0.000001",
        //     "status" => "online",
        //     "message" => "",
        //     "max_precision" => "0.000001",
        //     "convertible_to" => array(),
        //     "details" => array(
        //       "type" => "crypto",
        //       "symbol" => null,
        //       "network_confirmations" => 14,
        //       "sort_order" => 0,
        //       "crypto_address_link" => "https://etherscan.io/token/0xdac17f958d2ee523a2206206994597c13d831ec7?a=array({address})",
        //       "crypto_transaction_link" => "https://etherscan.io/tx/0xarray({txId})",
        //       "push_payment_methods" => array(),
        //       "group_types" => array(),
        //       "display_name" => null,
        //       "processing_time_seconds" => null,
        //       "min_withdrawal_amount" => 0.000001,
        //       "max_withdrawal_amount" => 20000000
        //     ),
        //     "default_network" => "ethereum",
        //     "supported_networks" => array(
        //       {
        //         "id" => "ethereum",
        //         "name" => "Ethereum",
        //         "status" => "online",
        //         "contract_address" => "0xdac17f958d2ee523a2206206994597c13d831ec7",
        //         "crypto_address_link" => "https://etherscan.io/token/0xdac17f958d2ee523a2206206994597c13d831ec7?a=array({address})",
        //         "crypto_transaction_link" => "https://etherscan.io/tx/0xarray({txId})",
        //         "min_withdrawal_amount" => 0.000001,
        //         "max_withdrawal_amount" => 20000000,
        //         "network_confirmations" => 14,
        //         "processing_time_seconds" => null
        //       }
        //     ),
        //     "display_name" => "USDT"
        //   }
        //
        $result = array();
        for ($i = 0; $i < count($response); $i++) {
            $currency = $response[$i];
            $id = $this->safe_string($currency, 'id');
            $name = $this->safe_string($currency, 'name');
            $code = $this->safe_currency_code($id);
            $details = $this->safe_dict($currency, 'details', array());
            $networks = array();
            $supportedNetworks = $this->safe_list($currency, 'supported_networks', array());
            for ($j = 0; $j < count($supportedNetworks); $j++) {
                $network = $supportedNetworks[$j];
                $networkId = $this->safe_string($network, 'id');
                $networkCode = $this->network_id_to_code($networkId);
                $networks[$networkCode] = array(
                    'id' => $networkId,
                    'name' => $this->safe_string($network, 'name'),
                    'network' => $networkCode,
                    'active' => $this->safe_string($network, 'status') === 'online',
                    'withdraw' => null,
                    'deposit' => null,
                    'fee' => null,
                    'precision' => null,
                    'limits' => array(
                        'withdraw' => array(
                            'min' => $this->safe_number($network, 'min_withdrawal_amount'),
                            'max' => $this->safe_number($network, 'max_withdrawal_amount'),
                        ),
                    ),
                    'contract' => $this->safe_string($network, 'contract_address'),
                    'info' => $network,
                );
            }
            $result[$code] = $this->safe_currency_structure(array(
                'id' => $id,
                'code' => $code,
                'info' => $currency,
                'type' => $this->safe_string($details, 'type'),
                'name' => $name,
                'active' => $this->safe_string($currency, 'status') === 'online',
                'deposit' => null,
                'withdraw' => null,
                'fee' => null,
                'precision' => $this->safe_number($currency, 'max_precision'),
                'limits' => array(
                    'amount' => array(
                        'min' => $this->safe_number($details, 'min_size'),
                        'max' => null,
                    ),
                    'withdraw' => array(
                        'min' => $this->safe_number($details, 'min_withdrawal_amount'),
                        'max' => $this->safe_number($details, 'max_withdrawal_amount'),
                    ),
                ),
                'networks' => $networks,
            ));
        }
        return $result;
    }

    public function fetch_markets($params = array ()): array {
        /**
         * retrieves data on all markets for coinbaseexchange
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getproducts
         *
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array[]} an array of objects representing $market data
         */
        $response = $this->publicGetProducts ($params);
        //
        //     array(
        //         array(
        //             "id" => "BTCAUCTION-USD",
        //             "base_currency" => "BTC",
        //             "quote_currency" => "USD",
        //             "base_min_size" => "0.000016",
        //             "base_max_size" => "1500",
        //             "quote_increment" => "0.01",
        //             "base_increment" => "0.00000001",
        //             "display_name" => "BTCAUCTION/USD",
        //             "min_market_funds" => "1",
        //             "max_market_funds" => "20000000",
        //             "margin_enabled" => false,
        //             "fx_stablecoin" => false,
        //             "max_slippage_percentage" => "0.02000000",
        //             "post_only" => false,
        //             "limit_only" => false,
        //             "cancel_only" => true,
        //             "trading_disabled" => false,
        //             "status" => "online",
        //             "status_message" => '',
        //             "auction_mode" => false
        //         ),
        //         {
        //             "id" => "BTC-USD",
        //             "base_currency" => "BTC",
        //             "quote_currency" => "USD",
        //             "base_min_size" => "0.000016",
        //             "base_max_size" => "1500",
        //             "quote_increment" => "0.01",
        //             "base_increment" => "0.00000001",
        //             "display_name" => "BTC/USD",
        //             "min_market_funds" => "1",
        //             "max_market_funds" => "20000000",
        //             "margin_enabled" => false,
        //             "fx_stablecoin" => false,
        //             "max_slippage_percentage" => "0.02000000",
        //             "post_only" => false,
        //             "limit_only" => false,
        //             "cancel_only" => false,
        //             "trading_disabled" => false,
        //             "status" => "online",
        //             "status_message" => '',
        //             "auction_mode" => false
        //         }
        //     )
        //
        $result = array();
        for ($i = 0; $i < count($response); $i++) {
            $market = $response[$i];
            $id = $this->safe_string($market, 'id');
            list($baseId, $quoteId) = explode('-', $id);
            // BTCAUCTION-USD vs BTC-USD conflict workaround, see the output sample above
            // $baseId = $this->safe_string($market, 'base_currency');
            // $quoteId = $this->safe_string($market, 'quote_currency');
            $base = $this->safe_currency_code($baseId);
            $quote = $this->safe_currency_code($quoteId);
            $status = $this->safe_string($market, 'status');
            $result[] = $this->extend($this->fees['trading'], array(
                'id' => $id,
                'symbol' => $base . '/' . $quote,
                'base' => $base,
                'quote' => $quote,
                'settle' => null,
                'baseId' => $baseId,
                'quoteId' => $quoteId,
                'settleId' => null,
                'type' => 'spot',
                'spot' => true,
                'margin' => $this->safe_value($market, 'margin_enabled'),
                'swap' => false,
                'future' => false,
                'option' => false,
                'active' => ($status === 'online'),
                'contract' => false,
                'linear' => null,
                'inverse' => null,
                'contractSize' => null,
                'expiry' => null,
                'expiryDatetime' => null,
                'strike' => null,
                'optionType' => null,
                'precision' => array(
                    'amount' => $this->safe_number($market, 'base_increment'),
                    'price' => $this->safe_number($market, 'quote_increment'),
                ),
                'limits' => array(
                    'leverage' => array(
                        'min' => null,
                        'max' => null,
                    ),
                    'amount' => array(
                        'min' => null,
                        'max' => null,
                    ),
                    'price' => array(
                        'min' => null,
                        'max' => null,
                    ),
                    'cost' => array(
                        'min' => $this->safe_number($market, 'min_market_funds'),
                        'max' => null,
                    ),
                ),
                'created' => null,
                'info' => $market,
            ));
        }
        return $result;
    }

    public function fetch_accounts($params = array ()): array {
        /**
         * fetch all the accounts associated with a profile
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getaccounts
         *
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array} a dictionary of ~@link https://docs.ccxt.com/#/?id=account-structure account structures~ indexed by the account type
         */
        $this->load_markets();
        $response = $this->privateGetAccounts ($params);
        //
        //     array(
        //         array(
        //             "id" => "4aac9c60-cbda-4396-9da4-4aa71e95fba0",
        //             "currency" => "BTC",
        //             "balance" => "0.0000000000000000",
        //             "available" => "0",
        //             "hold" => "0.0000000000000000",
        //             "profile_id" => "b709263e-f42a-4c7d-949a-a95c83d065da"
        //         ),
        //         array(
        //             "id" => "f75fa69a-1ad1-4a80-bd61-ee7faa6135a3",
        //             "currency" => "USDC",
        //             "balance" => "0.0000000000000000",
        //             "available" => "0",
        //             "hold" => "0.0000000000000000",
        //             "profile_id" => "b709263e-f42a-4c7d-949a-a95c83d065da"
        //         ),
        //     )
        //
        return $this->parse_accounts($response, $params);
    }

    public function parse_account($account) {
        //
        //     {
        //         "id" => "4aac9c60-cbda-4396-9da4-4aa71e95fba0",
        //         "currency" => "BTC",
        //         "balance" => "0.0000000000000000",
        //         "available" => "0",
        //         "hold" => "0.0000000000000000",
        //         "profile_id" => "b709263e-f42a-4c7d-949a-a95c83d065da"
        //     }
        //
        $currencyId = $this->safe_string($account, 'currency');
        return array(
            'id' => $this->safe_string($account, 'id'),
            'type' => null,
            'code' => $this->safe_currency_code($currencyId),
            'info' => $account,
        );
    }

    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, 'currency');
            $code = $this->safe_currency_code($currencyId);
            $account = $this->account();
            $account['free'] = $this->safe_string($balance, 'available');
            $account['used'] = $this->safe_string($balance, 'hold');
            $account['total'] = $this->safe_string($balance, 'balance');
            $result[$code] = $account;
        }
        return $this->safe_balance($result);
    }

    public function fetch_balance($params = array ()): array {
        /**
         * query for balance and get the amount of funds available for trading or funds locked in orders
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getaccounts
         *
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array} a ~@link https://docs.ccxt.com/#/?id=balance-structure balance structure~
         */
        $this->load_markets();
        $response = $this->privateGetAccounts ($params);
        return $this->parse_balance($response);
    }

    public function fetch_order_book(string $symbol, ?int $limit = null, $params = array ()): array {
        /**
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getproductbook
         *
         * fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
         * @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
         */
        $this->load_markets();
        // level 1 - only the best bid and ask
        // level 2 - top 50 bids and asks (aggregated)
        // level 3 - full order book (non aggregated)
        $request = array(
            'id' => $this->market_id($symbol),
            'level' => 2, // 1 best bidask, 2 aggregated, 3 full
        );
        $response = $this->publicGetProductsIdBook ($this->extend($request, $params));
        //
        //     {
        //         "sequence":1924393896,
        //         "bids":[
        //             ["0.01825","24.34811287",2],
        //             ["0.01824","72.5463",3],
        //             ["0.01823","424.54298049",6],
        //         ],
        //         "asks":[
        //             ["0.01826","171.10414904",4],
        //             ["0.01827","22.60427028",1],
        //             ["0.01828","397.46018784",7],
        //         ]
        //     }
        //
        $orderbook = $this->parse_order_book($response, $symbol);
        $orderbook['nonce'] = $this->safe_integer($response, 'sequence');
        return $orderbook;
    }

    public function parse_ticker(array $ticker, ?array $market = null): array {
        //
        // fetchTickers
        //
        //      array(
        //         1639472400, // $timestamp
        //         4.26, // $low
        //         4.38, // $high
        //         4.35, // $open
        //         4.27 // close
        //      )
        //
        // fetchTicker
        //
        //     publicGetProductsIdTicker
        //
        //     {
        //         "trade_id":843439,
        //         "price":"0.997999",
        //         "size":"80.29769",
        //         "time":"2020-01-28T02:13:33.012523Z",
        //         "bid":"0.997094",
        //         "ask":"0.998",
        //         "volume":"1903188.03750000"
        //     }
        //
        //     publicGetProductsIdStats
        //
        //     {
        //         "open" => "34.19000000",
        //         "high" => "95.70000000",
        //         "low" => "7.06000000",
        //         "volume" => "2.41000000"
        //     }
        //
        $timestamp = null;
        $bid = null;
        $ask = null;
        $last = null;
        $high = null;
        $low = null;
        $open = null;
        $volume = null;
        $symbol = ($market === null) ? null : $market['symbol'];
        if (gettype($ticker) === 'array' && array_keys($ticker) === array_keys(array_keys($ticker))) {
            $last = $this->safe_string($ticker, 4);
            $timestamp = $this->milliseconds();
        } else {
            $timestamp = $this->parse8601($this->safe_value($ticker, 'time'));
            $bid = $this->safe_string($ticker, 'bid');
            $ask = $this->safe_string($ticker, 'ask');
            $high = $this->safe_string($ticker, 'high');
            $low = $this->safe_string($ticker, 'low');
            $open = $this->safe_string($ticker, 'open');
            $last = $this->safe_string_2($ticker, 'price', 'last');
            $volume = $this->safe_string($ticker, 'volume');
        }
        return $this->safe_ticker(array(
            'symbol' => $symbol,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'high' => $high,
            'low' => $low,
            'bid' => $bid,
            'bidVolume' => null,
            'ask' => $ask,
            'askVolume' => null,
            'vwap' => null,
            'open' => $open,
            'close' => $last,
            'last' => $last,
            'previousClose' => null,
            'change' => null,
            'percentage' => null,
            'average' => null,
            'baseVolume' => $volume,
            'quoteVolume' => null,
            'info' => $ticker,
        ), $market);
    }

    public function fetch_tickers(?array $symbols = null, $params = array ()): array {
        /**
         * fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each $market
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getproduct
         *
         * @param {string[]|null} $symbols unified $symbols of the markets to fetch the ticker for, all $market tickers are returned if not assigned
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array} a dictionary of ~@link https://docs.ccxt.com/#/?id=ticker-structure ticker structures~
         */
        $this->load_markets();
        $symbols = $this->market_symbols($symbols);
        $request = array();
        $response = $this->publicGetProductsSparkLines ($this->extend($request, $params));
        //
        //     {
        //         YYY-USD => array(
        //             array(
        //                 1639472400, // timestamp
        //                 4.26, // low
        //                 4.38, // high
        //                 4.35, // open
        //                 4.27 // close
        //             ),
        //             array(
        //                 1639468800,
        //                 4.31,
        //                 4.45,
        //                 4.35,
        //                 4.35
        //             ),
        //         )
        //     }
        //
        $result = array();
        $marketIds = is_array($response) ? array_keys($response) : array();
        $delimiter = '-';
        for ($i = 0; $i < count($marketIds); $i++) {
            $marketId = $marketIds[$i];
            $entry = $this->safe_value($response, $marketId, array());
            $first = $this->safe_value($entry, 0, array());
            $market = $this->safe_market($marketId, null, $delimiter);
            $symbol = $market['symbol'];
            $result[$symbol] = $this->parse_ticker($first, $market);
        }
        return $this->filter_by_array_tickers($result, 'symbol', $symbols);
    }

    public function fetch_ticker(string $symbol, $params = array ()): array {
        /**
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getproductticker
         *
         * fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific $market
         * @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~
         */
        $this->load_markets();
        $market = $this->market($symbol);
        $request = array(
            'id' => $market['id'],
        );
        // publicGetProductsIdTicker or publicGetProductsIdStats
        $method = $this->safe_string($this->options, 'fetchTickerMethod', 'publicGetProductsIdTicker');
        $response = $this->$method ($this->extend($request, $params));
        //
        // publicGetProductsIdTicker
        //
        //     {
        //         "trade_id":843439,
        //         "price":"0.997999",
        //         "size":"80.29769",
        //         "time":"2020-01-28T02:13:33.012523Z",
        //         "bid":"0.997094",
        //         "ask":"0.998",
        //         "volume":"1903188.03750000"
        //     }
        //
        // publicGetProductsIdStats
        //
        //     {
        //         "open" => "34.19000000",
        //         "high" => "95.70000000",
        //         "low" => "7.06000000",
        //         "volume" => "2.41000000"
        //     }
        //
        return $this->parse_ticker($response, $market);
    }

    public function parse_trade(array $trade, ?array $market = null): array {
        //
        //     {
        //         "type" => "match",
        //         "trade_id" => 82047307,
        //         "maker_order_id" => "0f358725-2134-435e-be11-753912a326e0",
        //         "taker_order_id" => "252b7002-87a3-425c-ac73-f5b9e23f3caf",
        //         "order_id" => "d50ec984-77a8-460a-b958-66f114b0de9b",
        //         "side" => "sell",
        //         "size" => "0.00513192",
        //         "price" => "9314.78",
        //         "product_id" => "BTC-USD",
        //         "profile_id" => "6244401d-c078-40d9-b305-7ad3551bc3b0",
        //         "sequence" => 12038915443,
        //         "time" => "2020-01-31T20:03:41.158814Z"
        //         "created_at" => "2014-11-07T22:19:28.578544Z",
        //         "liquidity" => "T",
        //         "fee" => "0.00025",
        //         "settled" => true,
        //         "usd_volume" => "0.0924556000000000",
        //         "user_id" => "595eb864313c2b02ddf2937d"
        //     }
        //
        $timestamp = $this->parse8601($this->safe_string_2($trade, 'time', 'created_at'));
        $marketId = $this->safe_string($trade, 'product_id');
        $market = $this->safe_market($marketId, $market, '-');
        $feeRate = null;
        $takerOrMaker = null;
        $cost = null;
        $feeCurrencyId = $this->safe_string_lower($market, 'quoteId');
        if ($feeCurrencyId !== null) {
            $costField = $feeCurrencyId . '_value';
            $cost = $this->safe_string($trade, $costField);
            $liquidity = $this->safe_string($trade, 'liquidity');
            if ($liquidity !== null) {
                $takerOrMaker = ($liquidity === 'T') ? 'taker' : 'maker';
                $feeRate = $this->safe_string($market, $takerOrMaker);
            }
        }
        $feeCost = $this->safe_string_2($trade, 'fill_fees', 'fee');
        $fee = array(
            'cost' => $feeCost,
            'currency' => $market['quote'],
            'rate' => $feeRate,
        );
        $id = $this->safe_string($trade, 'trade_id');
        $side = ($trade['side'] === 'buy') ? 'sell' : 'buy';
        $orderId = $this->safe_string($trade, 'order_id');
        // Coinbase Pro returns inverted $side to fetchMyTrades vs fetchTrades
        $makerOrderId = $this->safe_string($trade, 'maker_order_id');
        $takerOrderId = $this->safe_string($trade, 'taker_order_id');
        if (($orderId !== null) || (($makerOrderId !== null) && ($takerOrderId !== null))) {
            $side = ($trade['side'] === 'buy') ? 'buy' : 'sell';
        }
        $price = $this->safe_string($trade, 'price');
        $amount = $this->safe_string($trade, 'size');
        return $this->safe_trade(array(
            'id' => $id,
            'order' => $orderId,
            'info' => $trade,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'symbol' => $market['symbol'],
            'type' => null,
            'takerOrMaker' => $takerOrMaker,
            'side' => $side,
            'price' => $price,
            'amount' => $amount,
            'fee' => $fee,
            'cost' => $cost,
        ), $market);
    }

    public function fetch_my_trades(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()) {
        /**
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getfills
         *
         * fetch all trades made by the user
         * @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
         * @param {int} [$params->until] the latest time in ms to fetch trades for
         * @param {boolean} [$params->paginate] default false, when true will automatically $paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-$params)
         * @return {Trade[]} a list of ~@link https://docs.ccxt.com/#/?id=trade-structure trade structures~
         */
        if ($symbol === null) {
            throw new ArgumentsRequired($this->id . ' fetchMyTrades() requires a $symbol argument');
        }
        $paginate = false;
        list($paginate, $params) = $this->handle_option_and_params($params, 'fetchMyTrades', 'paginate');
        if ($paginate) {
            return $this->fetch_paginated_call_dynamic('fetchMyTrades', $symbol, $since, $limit, $params, 100);
        }
        $this->load_markets();
        $market = $this->market($symbol);
        $request = array(
            'product_id' => $market['id'],
        );
        if ($limit !== null) {
            $request['limit'] = $limit;
        }
        if ($since !== null) {
            $request['start_date'] = $this->iso8601($since);
        }
        $until = $this->safe_value_2($params, 'until', 'end_date');
        if ($until !== null) {
            $params = $this->omit($params, array( 'until' ));
            $request['end_date'] = $this->iso8601($until);
        }
        $response = $this->privateGetFills ($this->extend($request, $params));
        return $this->parse_trades($response, $market, $since, $limit);
    }

    public function fetch_trades(string $symbol, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getproducttrades
         *
         * get the list of most recent trades for a particular $symbol
         * @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~
         */
        $this->load_markets();
        $market = $this->market($symbol);
        $request = array(
            'id' => $market['id'], // fixes issue #2
        );
        if ($limit !== null) {
            $request['limit'] = $limit; // default 100
        }
        $response = $this->publicGetProductsIdTrades ($this->extend($request, $params));
        //
        //    array(
        //        array(
        //            "trade_id" => "15035219",
        //            "side" => "sell",
        //            "size" => "0.27426731",
        //            "price" => "25820.42000000",
        //            "time" => "2023-09-10T13:47:41.447577Z"
        //        ),
        //    )
        //
        return $this->parse_trades($response, $market, $since, $limit);
    }

    public function fetch_trading_fees($params = array ()): array {
        /**
         * fetch the trading fees for multiple markets
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getfees
         *
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array} a dictionary of ~@link https://docs.ccxt.com/#/?id=fee-structure fee structures~ indexed by market symbols
         */
        $this->load_markets();
        $response = $this->privateGetFees ($params);
        //
        //    {
        //        "maker_fee_rate" => "0.0050",
        //        "taker_fee_rate" => "0.0050",
        //        "usd_volume" => "43806.92"
        //    }
        //
        $maker = $this->safe_number($response, 'maker_fee_rate');
        $taker = $this->safe_number($response, 'taker_fee_rate');
        $result = array();
        for ($i = 0; $i < count($this->symbols); $i++) {
            $symbol = $this->symbols[$i];
            $result[$symbol] = array(
                'info' => $response,
                'symbol' => $symbol,
                'maker' => $maker,
                'taker' => $taker,
                'percentage' => true,
                'tierBased' => true,
            );
        }
        return $result;
    }

    public function parse_ohlcv($ohlcv, ?array $market = null): array {
        //
        //     array(
        //         1591514160,
        //         0.02507,
        //         0.02507,
        //         0.02507,
        //         0.02507,
        //         0.02816506
        //     )
        //
        return array(
            $this->safe_timestamp($ohlcv, 0),
            $this->safe_number($ohlcv, 3),
            $this->safe_number($ohlcv, 2),
            $this->safe_number($ohlcv, 1),
            $this->safe_number($ohlcv, 4),
            $this->safe_number($ohlcv, 5),
        );
    }

    public function fetch_ohlcv(string $symbol, $timeframe = '1m', ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getproductcandles
         *
         * fetches historical candlestick data containing the open, high, low, and close price, and the volume of a $market
         * @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
         * @param {int} [$params->until] the latest time in ms to fetch trades for
         * @param {boolean} [$params->paginate] default false, when true will automatically $paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-$params)
         * @return {int[][]} A list of candles ordered, open, high, low, close, volume
         */
        $this->load_markets();
        $paginate = false;
        list($paginate, $params) = $this->handle_option_and_params($params, 'fetchOHLCV', 'paginate', false);
        if ($paginate) {
            return $this->fetch_paginated_call_deterministic('fetchOHLCV', $symbol, $since, $limit, $timeframe, $params, 300);
        }
        $market = $this->market($symbol);
        $parsedTimeframe = $this->safe_integer($this->timeframes, $timeframe);
        $request = array(
            'id' => $market['id'],
        );
        if ($parsedTimeframe !== null) {
            $request['granularity'] = $parsedTimeframe;
        } else {
            $request['granularity'] = $timeframe;
        }
        $until = $this->safe_value_2($params, 'until', 'end');
        $params = $this->omit($params, array( 'until' ));
        if ($since !== null) {
            $request['start'] = $this->iso8601($since);
            if ($limit === null) {
                // https://docs.pro.coinbase.com/#get-historic-rates
                $limit = 300; // max = 300
            } else {
                $limit = min (300, $limit);
            }
            if ($until === null) {
                $parsedTimeframeMilliseconds = $parsedTimeframe * 1000;
                if ($this->is_round_number(fmod($since, $parsedTimeframeMilliseconds))) {
                    $request['end'] = $this->iso8601($this->sum(($limit - 1) * $parsedTimeframeMilliseconds, $since));
                } else {
                    $request['end'] = $this->iso8601($this->sum($limit * $parsedTimeframeMilliseconds, $since));
                }
            } else {
                $request['end'] = $this->iso8601($until);
            }
        }
        $response = $this->publicGetProductsIdCandles ($this->extend($request, $params));
        //
        //     [
        //         [1591514160,0.02507,0.02507,0.02507,0.02507,0.02816506],
        //         [1591514100,0.02507,0.02507,0.02507,0.02507,1.63830323],
        //         [1591514040,0.02505,0.02507,0.02505,0.02507,0.19918178]
        //     ]
        //
        return $this->parse_ohlcvs($response, $market, $timeframe, $since, $limit);
    }

    public function fetch_time($params = array ()): ?int {
        /**
         * fetches the current integer timestamp in milliseconds from the exchange server
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {int} the current integer timestamp in milliseconds from the exchange server
         */
        $response = $this->publicGetTime ($params);
        //
        //     {
        //         "iso":"2020-05-12T08:00:51.504Z",
        //         "epoch":1589270451.504
        //     }
        //
        return $this->safe_timestamp($response, 'epoch');
    }

    public function parse_order_status(?string $status) {
        $statuses = array(
            'pending' => 'open',
            'active' => 'open',
            'open' => 'open',
            'done' => 'closed',
            'canceled' => 'canceled',
            'canceling' => 'open',
        );
        return $this->safe_string($statuses, $status, $status);
    }

    public function parse_order(array $order, ?array $market = null): array {
        //
        // createOrder
        //
        //     {
        //         "id" => "d0c5340b-6d6c-49d9-b567-48c4bfca13d2",
        //         "price" => "0.10000000",
        //         "size" => "0.01000000",
        //         "product_id" => "BTC-USD",
        //         "side" => "buy",
        //         "stp" => "dc",
        //         "type" => "limit",
        //         "time_in_force" => "GTC",
        //         "post_only" => false,
        //         "created_at" => "2016-12-08T20:02:28.53864Z",
        //         "fill_fees" => "0.0000000000000000",
        //         "filled_size" => "0.00000000",
        //         "executed_value" => "0.0000000000000000",
        //         "status" => "pending",
        //         "settled" => false
        //     }
        //
        $timestamp = $this->parse8601($this->safe_string($order, 'created_at'));
        $marketId = $this->safe_string($order, 'product_id');
        $market = $this->safe_market($marketId, $market, '-');
        $status = $this->parse_order_status($this->safe_string($order, 'status'));
        $doneReason = $this->safe_string($order, 'done_reason');
        if (($status === 'closed') && ($doneReason === 'canceled')) {
            $status = 'canceled';
        }
        $price = $this->safe_string($order, 'price');
        $filled = $this->safe_string($order, 'filled_size');
        $amount = $this->safe_string($order, 'size', $filled);
        $cost = $this->safe_string($order, 'executed_value');
        $feeCost = $this->safe_number($order, 'fill_fees');
        $fee = null;
        if ($feeCost !== null) {
            $fee = array(
                'cost' => $feeCost,
                'currency' => $market['quote'],
                'rate' => null,
            );
        }
        $id = $this->safe_string($order, 'id');
        $type = $this->safe_string($order, 'type');
        $side = $this->safe_string($order, 'side');
        $timeInForce = $this->safe_string($order, 'time_in_force');
        $postOnly = $this->safe_value($order, 'post_only');
        $triggerPrice = $this->safe_number($order, 'stop_price');
        $clientOrderId = $this->safe_string($order, 'client_oid');
        return $this->safe_order(array(
            'id' => $id,
            'clientOrderId' => $clientOrderId,
            'info' => $order,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'lastTradeTimestamp' => null,
            'status' => $status,
            'symbol' => $market['symbol'],
            'type' => $type,
            'timeInForce' => $timeInForce,
            'postOnly' => $postOnly,
            'side' => $side,
            'price' => $price,
            'triggerPrice' => $triggerPrice,
            'cost' => $cost,
            'amount' => $amount,
            'filled' => $filled,
            'remaining' => null,
            'fee' => $fee,
            'average' => null,
            'trades' => null,
        ), $market);
    }

    public function fetch_order(string $id, ?string $symbol = null, $params = array ()) {
        /**
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getorder
         *
         * fetches information on an order made by the user
         * @param {string} $id the order $id
         * @param {string} $symbol not used by coinbaseexchange 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~
         */
        $this->load_markets();
        $request = array();
        $clientOrderId = $this->safe_string_2($params, 'clientOrderId', 'client_oid');
        $method = null;
        if ($clientOrderId === null) {
            $method = 'privateGetOrdersId';
            $request['id'] = $id;
        } else {
            $method = 'privateGetOrdersClientClientOid';
            $request['client_oid'] = $clientOrderId;
            $params = $this->omit($params, array( 'clientOrderId', 'client_oid' ));
        }
        $response = $this->$method ($this->extend($request, $params));
        return $this->parse_order($response);
    }

    public function fetch_order_trades(string $id, ?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()) {
        /**
         * fetch all the trades made from a single order
         * @param {string} $id order $id
         * @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 to retrieve
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array[]} a list of ~@link https://docs.ccxt.com/#/?$id=trade-structure trade structures~
         */
        $this->load_markets();
        $market = null;
        if ($symbol !== null) {
            $market = $this->market($symbol);
        }
        $request = array(
            'order_id' => $id,
        );
        $response = $this->privateGetFills ($this->extend($request, $params));
        return $this->parse_trades($response, $market, $since, $limit);
    }

    public function fetch_orders(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getorders
         *
         * fetches information on multiple orders made by the user
         * @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
         * @param {int} [$params->until] the latest time in ms to fetch open orders for
         * @return {Order[]} a list of ~@link https://docs.ccxt.com/#/?id=order-structure order structures~
         */
        $request = array(
            'status' => 'all',
        );
        return $this->fetch_open_orders($symbol, $since, $limit, $this->extend($request, $params));
    }

    public function fetch_open_orders(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getorders
         *
         * fetch all unfilled currently open orders
         * @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
         * @param {int} [$params->until] the latest time in ms to fetch open orders for
         * @param {boolean} [$params->paginate] default false, when true will automatically $paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-$params)
         * @return {Order[]} a list of ~@link https://docs.ccxt.com/#/?id=order-structure order structures~
         */
        $this->load_markets();
        $paginate = false;
        list($paginate, $params) = $this->handle_option_and_params($params, 'fetchOpenOrders', 'paginate');
        if ($paginate) {
            return $this->fetch_paginated_call_dynamic('fetchOpenOrders', $symbol, $since, $limit, $params, 100);
        }
        $request = array();
        $market = null;
        if ($symbol !== null) {
            $market = $this->market($symbol);
            $request['product_id'] = $market['id'];
        }
        if ($limit !== null) {
            $request['limit'] = $limit; // default 100
        }
        if ($since !== null) {
            $request['start_date'] = $this->iso8601($since);
        }
        $until = $this->safe_value_2($params, 'until', 'end_date');
        if ($until !== null) {
            $params = $this->omit($params, array( 'until' ));
            $request['end_date'] = $this->iso8601($until);
        }
        $response = $this->privateGetOrders ($this->extend($request, $params));
        return $this->parse_orders($response, $market, $since, $limit);
    }

    public function fetch_closed_orders(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getorders
         *
         * fetches information on multiple closed orders made by the user
         * @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
         * @param {int} [$params->until] the latest time in ms to fetch open orders for
         * @return {Order[]} a list of ~@link https://docs.ccxt.com/#/?id=order-structure order structures~
         */
        $request = array(
            'status' => 'done',
        );
        return $this->fetch_open_orders($symbol, $since, $limit, $this->extend($request, $params));
    }

    public function create_order(string $symbol, string $type, string $side, float $amount, ?float $price = null, $params = array ()) {
        /**
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_postorders
         *
         * create a trade order
         * @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~
         */
        $this->load_markets();
        $market = $this->market($symbol);
        $request = array(
            // common $params --------------------------------------------------
            // 'client_oid' => $clientOrderId,
            'type' => $type,
            'side' => $side,
            'product_id' => $market['id'],
            // 'size' => $this->amount_to_precision($symbol, $amount),
            // 'stp' => 'dc', // self-trade prevention, dc = decrease and cancel, co = cancel oldest, cn = cancel newest, cb = cancel both
            // 'stop' => 'loss', // "loss" = stop loss below $price, "entry" = take profit above $price
            // 'stop_price' => $this->price_to_precision($symbol, $price),
            // limit order $params ---------------------------------------------
            // 'price' => $this->price_to_precision($symbol, $price),
            // 'size' => $this->amount_to_precision($symbol, $amount),
            // 'time_in_force' => 'GTC', // GTC, GTT, IOC, or FOK
            // 'cancel_after' [optional]* min, hour, day, requires time_in_force to be GTT
            // 'post_only' => false, // invalid when time_in_force is IOC or FOK
            // $market order $params --------------------------------------------
            // 'size' => $this->amount_to_precision($symbol, $amount),
            // 'funds' => $this->cost_to_precision($symbol, $amount),
        );
        $clientOrderId = $this->safe_string_2($params, 'clientOrderId', 'client_oid');
        if ($clientOrderId !== null) {
            $request['client_oid'] = $clientOrderId;
        }
        $triggerPrice = $this->safe_number_n($params, array( 'stopPrice', 'stop_price', 'triggerPrice' ));
        if ($triggerPrice !== null) {
            $request['stop_price'] = $this->price_to_precision($symbol, $triggerPrice);
        }
        $timeInForce = $this->safe_string_2($params, 'timeInForce', 'time_in_force');
        if ($timeInForce !== null) {
            $request['time_in_force'] = $timeInForce;
        }
        $postOnly = $this->safe_value_2($params, 'postOnly', 'post_only', false);
        if ($postOnly) {
            $request['post_only'] = true;
        }
        $params = $this->omit($params, array( 'timeInForce', 'time_in_force', 'stopPrice', 'stop_price', 'clientOrderId', 'client_oid', 'postOnly', 'post_only', 'triggerPrice' ));
        if ($type === 'limit') {
            $request['price'] = $this->price_to_precision($symbol, $price);
            $request['size'] = $this->amount_to_precision($symbol, $amount);
        } elseif ($type === 'market') {
            $cost = $this->safe_number_2($params, 'cost', 'funds');
            if ($cost === null) {
                if ($price !== null) {
                    $cost = $amount * $price;
                }
            } else {
                $params = $this->omit($params, array( 'cost', 'funds' ));
            }
            if ($cost !== null) {
                $request['funds'] = $this->cost_to_precision($symbol, $cost);
            } else {
                $request['size'] = $this->amount_to_precision($symbol, $amount);
            }
        }
        $response = $this->privatePostOrders ($this->extend($request, $params));
        //
        //     {
        //         "id" => "d0c5340b-6d6c-49d9-b567-48c4bfca13d2",
        //         "price" => "0.10000000",
        //         "size" => "0.01000000",
        //         "product_id" => "BTC-USD",
        //         "side" => "buy",
        //         "stp" => "dc",
        //         "type" => "limit",
        //         "time_in_force" => "GTC",
        //         "post_only" => false,
        //         "created_at" => "2016-12-08T20:02:28.53864Z",
        //         "fill_fees" => "0.0000000000000000",
        //         "filled_size" => "0.00000000",
        //         "executed_value" => "0.0000000000000000",
        //         "status" => "pending",
        //         "settled" => false
        //     }
        //
        return $this->parse_order($response, $market);
    }

    public function cancel_order(string $id, ?string $symbol = null, $params = array ()) {
        /**
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_deleteorder
         *
         * cancels an open order
         * @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~
         */
        $this->load_markets();
        $request = array(
            // 'product_id' => $market['id'], // the $request will be more performant if you include it
        );
        $clientOrderId = $this->safe_string_2($params, 'clientOrderId', 'client_oid');
        $method = null;
        if ($clientOrderId === null) {
            $method = 'privateDeleteOrdersId';
            $request['id'] = $id;
        } else {
            $method = 'privateDeleteOrdersClientClientOid';
            $request['client_oid'] = $clientOrderId;
            $params = $this->omit($params, array( 'clientOrderId', 'client_oid' ));
        }
        $market = null;
        if ($symbol !== null) {
            $market = $this->market($symbol);
            $request['product_id'] = $market['symbol']; // the $request will be more performant if you include it
        }
        $response = $this->$method ($this->extend($request, $params));
        return $this->safe_order(array( 'info' => $response ));
    }

    public function cancel_all_orders(?string $symbol = null, $params = array ()) {
        /**
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_deleteorders
         *
         * cancel all open orders
         * @param {string} $symbol unified $market $symbol, only orders in the $market of this $symbol are cancelled when $symbol is not null
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array[]} a list of ~@link https://docs.ccxt.com/#/?id=order-structure order structures~
         */
        $this->load_markets();
        $request = array();
        $market = null;
        if ($symbol !== null) {
            $market = $this->market($symbol);
            $request['product_id'] = $market['symbol']; // the $request will be more performant if you include it
        }
        $response = $this->privateDeleteOrders ($this->extend($request, $params));
        return array( $this->safe_order(array( 'info' => $response )) );
    }

    public function fetch_payment_methods($params = array ()) {
        return $this->privateGetPaymentMethods ($params);
    }

    public function withdraw(string $code, float $amount, string $address, ?string $tag = null, $params = array ()): array {
        /**
         * make a withdrawal
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_postwithdrawpaymentmethod
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_postwithdrawcoinbaseaccount
         *
         * @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);
        $this->check_address($address);
        $this->load_markets();
        $currency = $this->currency($code);
        $request = array(
            'currency' => $currency['id'],
            'amount' => $amount,
        );
        $method = 'privatePostWithdrawals';
        if (is_array($params) && array_key_exists('payment_method_id', $params)) {
            $method .= 'PaymentMethod';
        } elseif (is_array($params) && array_key_exists('coinbase_account_id', $params)) {
            $method .= 'CoinbaseAccount';
        } else {
            $method .= 'Crypto';
            $request['crypto_address'] = $address;
            if ($tag !== null) {
                $request['destination_tag'] = $tag;
            }
        }
        $response = $this->$method ($this->extend($request, $params));
        if (!$response) {
            throw new ExchangeError($this->id . ' withdraw() error => ' . $this->json($response));
        }
        return $this->parse_transaction($response, $currency);
    }

    public function parse_ledger_entry_type($type) {
        $types = array(
            'transfer' => 'transfer', // Funds moved between portfolios
            'match' => 'trade',       // Funds moved result of a trade
            'fee' => 'fee',           // Fee result of a trade
            'rebate' => 'rebate',     // Fee rebate
            'conversion' => 'trade',  // Funds converted between fiat currency and a stablecoin
        );
        return $this->safe_string($types, $type, $type);
    }

    public function parse_ledger_entry(array $item, ?array $currency = null): array {
        //  {
        //      "id" => "12087495079",
        //      "amount" => "-0.0100000000000000",
        //      "balance" => "0.0645419900000000",
        //      "created_at" => "2021-10-28T17:14:32.593168Z",
        //      "type" => "transfer",
        //      "details" => array(
        //          "from" => "2f74edf7-1440-4586-86dc-ae58c5693691",
        //          "profile_transfer_id" => "3ef093ad-2482-40d1-8ede-2f89cff5099e",
        //          "to" => "dda99503-4980-4b60-9549-0b770ee51336"
        //      }
        //  ),
        //  {
        //     "id" => "11740725774",
        //     "amount" => "-1.7565669701255000",
        //     "balance" => "0.0016490047745000",
        //     "created_at" => "2021-10-22T03:47:34.764122Z",
        //     "type" => "fee",
        //     "details" => {
        //         "order_id" => "ad06abf4-95ab-432a-a1d8-059ef572e296",
        //         "product_id" => "ETH-DAI",
        //         "trade_id" => "1740617"
        //     }
        //  }
        $id = $this->safe_string($item, 'id');
        $amountString = $this->safe_string($item, 'amount');
        $direction = null;
        $afterString = $this->safe_string($item, 'balance');
        $beforeString = Precise::string_sub($afterString, $amountString);
        if (Precise::string_lt($amountString, '0')) {
            $direction = 'out';
            $amountString = Precise::string_abs($amountString);
        } else {
            $direction = 'in';
        }
        $amount = $this->parse_number($amountString);
        $after = $this->parse_number($afterString);
        $before = $this->parse_number($beforeString);
        $timestamp = $this->parse8601($this->safe_value($item, 'created_at'));
        $type = $this->parse_ledger_entry_type($this->safe_string($item, 'type'));
        $code = $this->safe_currency_code(null, $currency);
        $details = $this->safe_value($item, 'details', array());
        $account = null;
        $referenceAccount = null;
        $referenceId = null;
        if ($type === 'transfer') {
            $account = $this->safe_string($details, 'from');
            $referenceAccount = $this->safe_string($details, 'to');
            $referenceId = $this->safe_string($details, 'profile_transfer_id');
        } else {
            $referenceId = $this->safe_string($details, 'order_id');
        }
        $status = 'ok';
        return $this->safe_ledger_entry(array(
            'info' => $item,
            'id' => $id,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'direction' => $direction,
            'account' => $account,
            'referenceAccount' => $referenceAccount,
            'referenceId' => $referenceId,
            'type' => $type,
            'currency' => $code,
            'amount' => $amount,
            'before' => $before,
            'after' => $after,
            'status' => $status,
            'fee' => null,
        ), $currency);
    }

    public function fetch_ledger(?string $code = null, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         * fetch the history of changes, actions done by the user or operations that altered the balance of the user
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getaccountledger
         *
         * @param {string} $code unified $currency $code, default is null
         * @param {int} [$since] timestamp in ms of the earliest ledger entry, default is null
         * @param {int} [$limit] max number of ledger entries to return, default is null
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @param {int} [$params->until] the latest time in ms to fetch trades for
         * @return {array} a ~@link https://docs.ccxt.com/#/?id=ledger ledger structure~
         */
        // https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getaccountledger
        if ($code === null) {
            throw new ArgumentsRequired($this->id . ' fetchLedger() requires a $code param');
        }
        $this->load_markets();
        $this->load_accounts();
        $currency = $this->currency($code);
        $accountsByCurrencyCode = $this->index_by($this->accounts, 'code');
        $account = $this->safe_value($accountsByCurrencyCode, $code);
        if ($account === null) {
            throw new ExchangeError($this->id . ' fetchLedger() could not find $account id for ' . $code);
        }
        $request = array(
            'id' => $account['id'],
            // 'start_date' => $this->iso8601($since),
            // 'end_date' => $this->iso8601($this->milliseconds()),
            // 'before' => 'cursor', // sets start cursor to before date
            // 'after' => 'cursor', // sets end cursor to after date
            // 'limit' => $limit, // default 100
            // 'profile_id' => 'string'
        );
        if ($since !== null) {
            $request['start_date'] = $this->iso8601($since);
        }
        if ($limit !== null) {
            $request['limit'] = $limit; // default 100
        }
        $until = $this->safe_value_2($params, 'until', 'end_date');
        if ($until !== null) {
            $params = $this->omit($params, array( 'until' ));
            $request['end_date'] = $this->iso8601($until);
        }
        $response = $this->privateGetAccountsIdLedger ($this->extend($request, $params));
        for ($i = 0; $i < count($response); $i++) {
            $response[$i]['currency'] = $code;
        }
        return $this->parse_ledger($response, $currency, $since, $limit);
    }

    public function fetch_deposits_withdrawals(?string $code = null, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         * fetch history of deposits and withdrawals
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_gettransfers
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getaccounttransfers
         *
         * @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
         * @param {string} [$params->id] $account $id, when defined, the endpoint used is '/accounts/{$account_id}/transfers/' instead of '/transfers/'
         * @return {array} a list of ~@link https://docs.ccxt.com/#/?$id=transaction-structure transaction structure~
         */
        $this->load_markets();
        $this->load_accounts();
        $currency = null;
        $id = $this->safe_string($params, 'id'); // $account $id
        if ($id === null) {
            if ($code !== null) {
                $currency = $this->currency($code);
                $accountsByCurrencyCode = $this->index_by($this->accounts, 'code');
                $account = $this->safe_value($accountsByCurrencyCode, $code);
                if ($account === null) {
                    throw new ExchangeError($this->id . ' fetchDepositsWithdrawals() could not find $account $id for ' . $code);
                }
                $id = $account['id'];
            }
        }
        $request = array();
        if ($id !== null) {
            $request['id'] = $id;
        }
        if ($limit !== null) {
            $request['limit'] = $limit;
        }
        $response = null;
        if ($id === null) {
            $response = $this->privateGetTransfers ($this->extend($request, $params));
            //
            //    array(
            //        {
            //            "id" => "bee6fd7c-afb2-4e47-8298-671d09997d16",
            //            "type" => "deposit",
            //            "created_at" => "2022-12-21 00:48:45.477503+00",
            //            "completed_at" => null,
            //            "account_id" => "sal3802-36bd-46be-a7b8-alsjf383sldak",
            //            "user_id" => "6382048209f92as392039dlks2",
            //            "amount" => "0.01000000",
            //            "details" => array(
            //                "network" => "litecoin",
            //                "crypto_address" => "MKemtnCFUYKsNWaf5EMYMpwSszcXWFDtTY",
            //                "coinbase_account_id" => "fl2b6925-f6ba-403n-jj03-40fl435n430f",
            //                "coinbase_transaction_id" => "63a25bb13cb5cf0001d2cf17", // withdrawals only
            //                "crypto_transaction_hash" => "752f35570736341e2a253f7041a34cf1e196fc56128c900fd03d99da899d94c1",
            //                "tx_service_transaction_id" => "1873249104",
            //                "coinbase_payment_method_id" => ""
            //            ),
            //            "canceled_at" => null,
            //            "processed_at" => null,
            //            "user_nonce" => null,
            //            "idem" => "5e3201b0-e390-5k3k-a913-c32932049242",
            //            "profile_id" => "k3k302a8-c4dk-4f49-9d39-3203923wpk39",
            //            "currency" => "LTC"
            //        }
            //    )
            //
            for ($i = 0; $i < count($response); $i++) {
                $account_id = $this->safe_string($response[$i], 'account_id');
                $account = $this->safe_value($this->accountsById, $account_id);
                $codeInner = $this->safe_string($account, 'code');
                $response[$i]['currency'] = $codeInner;
            }
        } else {
            $response = $this->privateGetAccountsIdTransfers ($this->extend($request, $params));
            //
            //    array(
            //        {
            //            "id" => "bee6fd7c-afb2-4e47-8298-671d09997d16",
            //            "type" => "deposit",
            //            "created_at" => "2022-12-21 00:48:45.477503+00",
            //            "completed_at" => null,
            //            "amount" => "0.01000000",
            //            "details" => array(
            //                "network" => "litecoin",
            //                "crypto_address" => "MKemtnCFUYKsNWaf5EMYMpwSszcXWFDtTY",
            //                "coinbase_account_id" => "fl2b6925-f6ba-403n-jj03-40fl435n430f",
            //                "coinbase_transaction_id" => "63a25bb13cb5cf0001d2cf17", // withdrawals only
            //                "crypto_transaction_hash" => "752f35570736341e2a253f7041a34cf1e196fc56128c900fd03d99da899d94c1",
            //                "tx_service_transaction_id" => "1873249104",
            //                "coinbase_payment_method_id" => ""
            //            ),
            //            "canceled_at" => null,
            //            "processed_at" => null,
            //            "user_nonce" => null,
            //            "idem" => "5e3201b0-e390-5k3k-a913-c32932049242",
            //            "profile_id" => "k3k302a8-c4dk-4f49-9d39-3203923wpk39",
            //            "currency" => "LTC"
            //        }
            //    )
            //
            for ($i = 0; $i < count($response); $i++) {
                $response[$i]['currency'] = $code;
            }
        }
        return $this->parse_transactions($response, $currency, $since, $limit);
    }

    public function fetch_deposits(?string $code = null, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         * fetch all deposits made to an account
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_gettransfers
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getaccounttransfers
         *
         * @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 $this->fetch_deposits_withdrawals($code, $since, $limit, $this->extend(array( 'type' => 'deposit' ), $params));
    }

    public function fetch_withdrawals(?string $code = null, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         * fetch all withdrawals made from an account
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_gettransfers
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getaccounttransfers
         *
         * @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 $this->fetch_deposits_withdrawals($code, $since, $limit, $this->extend(array( 'type' => 'withdraw' ), $params));
    }

    public function parse_transaction_status($transaction) {
        $canceled = $this->safe_value($transaction, 'canceled_at');
        if ($canceled) {
            return 'canceled';
        }
        $processed = $this->safe_value($transaction, 'processed_at');
        $completed = $this->safe_value($transaction, 'completed_at');
        if ($completed) {
            return 'ok';
        } elseif ($processed && !$completed) {
            return 'failed';
        } else {
            return 'pending';
        }
    }

    public function parse_transaction(array $transaction, ?array $currency = null): array {
        //
        // privateGetTransfers
        //
        //    array(
        //        {
        //            "id" => "bee6fd7c-afb2-4e47-8298-671d09997d16",
        //            "type" => "deposit",
        //            "created_at" => "2022-12-21 00:48:45.477503+00",
        //            "completed_at" => null,
        //            "account_id" => "sal3802-36bd-46be-a7b8-alsjf383sldak",     // only from privateGetTransfers
        //            "user_id" => "6382048209f92as392039dlks2",                  // only from privateGetTransfers
        //            "amount" => "0.01000000",
        //            "details" => array(
        //                "network" => "litecoin",
        //                "crypto_address" => "MKemtnCFUYKsNWaf5EMYMpwSszcXWFDtTY",
        //                "coinbase_account_id" => "fl2b6925-f6ba-403n-jj03-40fl435n430f",
        //                "coinbase_transaction_id" => "63a25bb13cb5cf0001d2cf17", // withdrawals only
        //                "crypto_transaction_hash" => "752f35570736341e2a253f7041a34cf1e196fc56128c900fd03d99da899d94c1",
        //                "tx_service_transaction_id" => "1873249104",
        //                "coinbase_payment_method_id" => ""
        //            ),
        //            "canceled_at" => null,
        //            "processed_at" => null,
        //            "user_nonce" => null,
        //            "idem" => "5e3201b0-e390-5k3k-a913-c32932049242",
        //            "profile_id" => "k3k302a8-c4dk-4f49-9d39-3203923wpk39",
        //            "currency" => "LTC"
        //        }
        //    )
        //
        $details = $this->safe_value($transaction, 'details', array());
        $timestamp = $this->parse8601($this->safe_string($transaction, 'created_at'));
        $currencyId = $this->safe_string($transaction, 'currency');
        $code = $this->safe_currency_code($currencyId, $currency);
        $amount = $this->safe_number($transaction, 'amount');
        $type = $this->safe_string($transaction, 'type');
        $address = $this->safe_string($details, 'crypto_address');
        $address = $this->safe_string($transaction, 'crypto_address', $address);
        $fee = array(
            'currency' => null,
            'cost' => null,
            'rate' => null,
        );
        if ($type === 'withdraw') {
            $type = 'withdrawal';
            $address = $this->safe_string($details, 'sent_to_address', $address);
            $feeCost = $this->safe_number($details, 'fee');
            if ($feeCost !== null) {
                if ($amount !== null) {
                    $amount -= $feeCost;
                }
                $fee['cost'] = $feeCost;
                $fee['currency'] = $code;
            }
        }
        $networkId = $this->safe_string($details, 'network');
        return array(
            'info' => $transaction,
            'id' => $this->safe_string($transaction, 'id'),
            'txid' => $this->safe_string($details, 'crypto_transaction_hash'),
            'type' => $type,
            'currency' => $code,
            'network' => $this->network_id_to_code($networkId),
            'amount' => $amount,
            'status' => $this->parse_transaction_status($transaction),
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'address' => $address,
            'addressFrom' => null,
            'addressTo' => $this->safe_string($details, 'crypto_address'),
            'tag' => $this->safe_string($details, 'destination_tag'),
            'tagFrom' => null,
            'tagTo' => null,
            'updated' => $this->parse8601($this->safe_string($transaction, 'processed_at')),
            'comment' => null,
            'internal' => false,
            'fee' => $fee,
        );
    }

    public function create_deposit_address(string $code, $params = array ()): array {
        /**
         * create a $currency deposit $address
         *
         * @see https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_postcoinbaseaccountaddresses
         *
         * @param {string} $code unified $currency $code of the $currency for the deposit $address
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array} an ~@link https://docs.ccxt.com/#/?id=$address-structure $address structure~
         */
        $this->load_markets();
        $currency = $this->currency($code);
        $accounts = $this->safe_value($this->options, 'coinbaseAccounts');
        if ($accounts === null) {
            $accounts = $this->privateGetCoinbaseAccounts ();
            $this->options['coinbaseAccounts'] = $accounts; // cache it
            $this->options['coinbaseAccountsByCurrencyId'] = $this->index_by($accounts, 'currency');
        }
        $currencyId = $currency['id'];
        $account = $this->safe_value($this->options['coinbaseAccountsByCurrencyId'], $currencyId);
        if ($account === null) {
            // eslint-disable-next-line quotes
            throw new InvalidAddress($this->id . " createDepositAddress() could not find $currency $code " . $code . " with id = " . $currencyId . " in $this->options['coinbaseAccountsByCurrencyId']");
        }
        $request = array(
            'id' => $account['id'],
        );
        $response = $this->privatePostCoinbaseAccountsIdAddresses ($this->extend($request, $params));
        $address = $this->safe_string($response, 'address');
        $tag = $this->safe_string($response, 'destination_tag');
        return array(
            'currency' => $code,
            'address' => $this->check_address($address),
            'network' => null,
            'tag' => $tag,
            'info' => $response,
        );
    }

    public function sign($path, $api = 'public', $method = 'GET', $params = array (), $headers = null, $body = null) {
        $request = '/' . $this->implode_params($path, $params);
        $query = $this->omit($params, $this->extract_params($path));
        if ($method === 'GET') {
            if ($query) {
                $request .= '?' . $this->urlencode($query);
            }
        }
        $url = $this->implode_hostname($this->urls['api'][$api]) . $request;
        if ($api === 'private') {
            $this->check_required_credentials();
            $nonce = (string) $this->nonce();
            $payload = '';
            if ($method !== 'GET') {
                if ($query) {
                    $body = $this->json($query);
                    $payload = $body;
                }
            }
            $what = $nonce . $method . $request . $payload;
            $secret = null;
            try {
                $secret = base64_decode($this->secret);
            } catch (Exception $e) {
                throw new AuthenticationError($this->id . ' sign() invalid base64 secret');
            }
            $signature = $this->hmac($this->encode($what), $secret, 'sha256', 'base64');
            $headers = array(
                'CB-ACCESS-KEY' => $this->apiKey,
                'CB-ACCESS-SIGN' => $signature,
                'CB-ACCESS-TIMESTAMP' => $nonce,
                'CB-ACCESS-PASSPHRASE' => $this->password,
                'Content-Type' => 'application/json',
            );
        }
        return array( 'url' => $url, 'method' => $method, 'body' => $body, 'headers' => $headers );
    }

    public function handle_errors(int $code, string $reason, string $url, string $method, array $headers, string $body, $response, $requestHeaders, $requestBody) {
        if (($code === 400) || ($code === 404)) {
            if ($body[0] === '{') {
                $message = $this->safe_string($response, 'message');
                $feedback = $this->id . ' ' . $message;
                $this->throw_exactly_matched_exception($this->exceptions['exact'], $message, $feedback);
                $this->throw_broadly_matched_exception($this->exceptions['broad'], $message, $feedback);
                throw new ExchangeError($feedback); // unknown $message
            }
            throw new ExchangeError($this->id . ' ' . $body);
        }
        return null;
    }

    public function request($path, $api = 'public', $method = 'GET', $params = array (), $headers = null, $body = null, $config = array ()) {
        $response = $this->fetch2($path, $api, $method, $params, $headers, $body, $config);
        if (gettype($response) !== 'string') {
            if (is_array($response) && array_key_exists('message', $response)) {
                throw new ExchangeError($this->id . ' ' . $this->json($response));
            }
        }
        return $response;
    }
}
