<?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\bitvavo as Exchange;

class bitvavo extends Exchange {

    public function describe(): mixed {
        return $this->deep_extend(parent::describe(), array(
            'id' => 'bitvavo',
            'name' => 'Bitvavo',
            'countries' => array( 'NL' ), // Netherlands
            'rateLimit' => 60, // 1000 requests per minute
            'version' => 'v2',
            'certified' => false,
            'pro' => true,
            'has' => array(
                'CORS' => null,
                'spot' => true,
                'margin' => false,
                'swap' => false,
                'future' => false,
                'option' => false,
                'addMargin' => false,
                'borrowCrossMargin' => false,
                'borrowIsolatedMargin' => false,
                'borrowMargin' => false,
                'cancelAllOrders' => true,
                'cancelOrder' => true,
                'closeAllPositions' => false,
                'closePosition' => false,
                'createOrder' => true,
                'createOrderWithTakeProfitAndStopLoss' => false,
                'createOrderWithTakeProfitAndStopLossWs' => false,
                'createPostOnlyOrder' => false,
                'createReduceOnlyOrder' => false,
                'createStopLimitOrder' => true,
                'createStopMarketOrder' => true,
                'createStopOrder' => true,
                'editOrder' => true,
                'fetchBalance' => true,
                'fetchBorrowInterest' => false,
                'fetchBorrowRate' => false,
                'fetchBorrowRateHistories' => false,
                'fetchBorrowRateHistory' => false,
                'fetchBorrowRates' => false,
                'fetchBorrowRatesPerSymbol' => false,
                'fetchCrossBorrowRate' => false,
                'fetchCrossBorrowRates' => false,
                'fetchCurrencies' => true,
                'fetchDepositAddress' => true,
                'fetchDepositAddresses' => false,
                'fetchDepositAddressesByNetwork' => false,
                'fetchDeposits' => true,
                'fetchDepositWithdrawFee' => 'emulated',
                'fetchDepositWithdrawFees' => true,
                'fetchFundingHistory' => false,
                'fetchFundingInterval' => false,
                'fetchFundingIntervals' => false,
                'fetchFundingRate' => false,
                'fetchFundingRateHistory' => false,
                'fetchFundingRates' => false,
                'fetchGreeks' => false,
                'fetchIndexOHLCV' => false,
                'fetchIsolatedBorrowRate' => false,
                'fetchIsolatedBorrowRates' => false,
                'fetchIsolatedPositions' => false,
                'fetchLeverage' => false,
                'fetchLeverages' => false,
                'fetchLeverageTiers' => false,
                'fetchLiquidations' => false,
                'fetchLongShortRatio' => false,
                'fetchLongShortRatioHistory' => false,
                'fetchMarginAdjustmentHistory' => false,
                'fetchMarginMode' => false,
                'fetchMarginModes' => false,
                'fetchMarketLeverageTiers' => false,
                'fetchMarkets' => true,
                'fetchMarkOHLCV' => false,
                'fetchMarkPrices' => false,
                'fetchMyLiquidations' => false,
                'fetchMySettlementHistory' => false,
                'fetchMyTrades' => true,
                'fetchOHLCV' => true,
                'fetchOpenInterest' => false,
                'fetchOpenInterestHistory' => false,
                'fetchOpenInterests' => false,
                'fetchOpenOrders' => true,
                'fetchOption' => false,
                'fetchOptionChain' => false,
                'fetchOrder' => true,
                'fetchOrderBook' => true,
                'fetchOrders' => 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,
                'fetchTransfer' => false,
                'fetchTransfers' => false,
                'fetchVolatilityHistory' => false,
                'fetchWithdrawals' => true,
                'reduceMargin' => false,
                'repayCrossMargin' => false,
                'repayIsolatedMargin' => false,
                'repayMargin' => false,
                'setLeverage' => false,
                'setMargin' => false,
                'setMarginMode' => false,
                'setPositionMode' => false,
                'transfer' => false,
                'withdraw' => true,
            ),
            'timeframes' => array(
                '1m' => '1m',
                '5m' => '5m',
                '15m' => '15m',
                '30m' => '30m',
                '1h' => '1h',
                '2h' => '2h',
                '4h' => '4h',
                '6h' => '6h',
                '8h' => '8h',
                '12h' => '12h',
                '1d' => '1d',
            ),
            'urls' => array(
                'logo' => 'https://github.com/user-attachments/assets/d213155c-8c71-4701-9bd5-45351febc2a8',
                'api' => array(
                    'public' => 'https://api.bitvavo.com',
                    'private' => 'https://api.bitvavo.com',
                ),
                'www' => 'https://bitvavo.com/',
                'doc' => 'https://docs.bitvavo.com/',
                'fees' => 'https://bitvavo.com/en/fees',
                'referral' => 'https://bitvavo.com/?a=24F34952F7',
            ),
            'api' => array(
                'public' => array(
                    'get' => array(
                        'time' => 1,
                        'markets' => 1,
                        'assets' => 1,
                        '{market}/book' => 1,
                        '{market}/trades' => 5,
                        '{market}/candles' => 1,
                        'ticker/price' => 1,
                        'ticker/book' => 1,
                        'ticker/24h' => array( 'cost' => 1, 'noMarket' => 25 ),
                    ),
                ),
                'private' => array(
                    'get' => array(
                        'account' => 1,
                        'order' => 1,
                        'orders' => 5,
                        'ordersOpen' => array( 'cost' => 1, 'noMarket' => 25 ),
                        'trades' => 5,
                        'balance' => 5,
                        'deposit' => 1,
                        'depositHistory' => 5,
                        'withdrawalHistory' => 5,
                    ),
                    'post' => array(
                        'order' => 1,
                        'withdrawal' => 1,
                    ),
                    'put' => array(
                        'order' => 1,
                    ),
                    'delete' => array(
                        'order' => 1,
                        'orders' => 1,
                    ),
                ),
            ),
            'fees' => array(
                'trading' => array(
                    'tierBased' => true,
                    'percentage' => true,
                    'taker' => $this->parse_number('0.0025'),
                    'maker' => $this->parse_number('0.002'),
                    'tiers' => array(
                        'taker' => array(
                            array( $this->parse_number('0'), $this->parse_number('0.0025') ),
                            array( $this->parse_number('100000'), $this->parse_number('0.0020') ),
                            array( $this->parse_number('250000'), $this->parse_number('0.0016') ),
                            array( $this->parse_number('500000'), $this->parse_number('0.0012') ),
                            array( $this->parse_number('1000000'), $this->parse_number('0.0010') ),
                            array( $this->parse_number('2500000'), $this->parse_number('0.0008') ),
                            array( $this->parse_number('5000000'), $this->parse_number('0.0006') ),
                            array( $this->parse_number('10000000'), $this->parse_number('0.0005') ),
                            array( $this->parse_number('25000000'), $this->parse_number('0.0004') ),
                        ),
                        'maker' => array(
                            array( $this->parse_number('0'), $this->parse_number('0.0015') ),
                            array( $this->parse_number('100000'), $this->parse_number('0.0010') ),
                            array( $this->parse_number('250000'), $this->parse_number('0.0008') ),
                            array( $this->parse_number('500000'), $this->parse_number('0.0006') ),
                            array( $this->parse_number('1000000'), $this->parse_number('0.0005') ),
                            array( $this->parse_number('2500000'), $this->parse_number('0.0004') ),
                            array( $this->parse_number('5000000'), $this->parse_number('0.0004') ),
                            array( $this->parse_number('10000000'), $this->parse_number('0.0003') ),
                            array( $this->parse_number('25000000'), $this->parse_number('0.0003') ),
                        ),
                    ),
                ),
            ),
            'requiredCredentials' => array(
                'apiKey' => true,
                'secret' => true,
            ),
            'features' => array(
                'spot' => array(
                    'sandbox' => false,
                    'createOrder' => array(
                        'marginMode' => false,
                        'triggerPrice' => true,
                        'triggerPriceType' => null,
                        'triggerDirection' => null,
                        'stopLossPrice' => true,
                        'takeProfitPrice' => true,
                        'attachedStopLossTakeProfit' => null,
                        'timeInForce' => array(
                            'IOC' => true,
                            'FOK' => true,
                            'PO' => true,
                            'GTD' => false,
                        ),
                        'hedged' => false,
                        'trailing' => false,
                        'leverage' => false,
                        'marketBuyRequiresPrice' => false,
                        'marketBuyByCost' => true,
                        'selfTradePrevention' => array(
                            'EXPIRE_MAKER' => false,
                            'EXPIRE_TAKER' => false,
                            'EXPIRE_BOTH' => true,
                            'NONE' => false,
                        ),
                        'iceberg' => false,
                    ),
                    'createOrders' => null,
                    'fetchMyTrades' => array(
                        'marginMode' => false,
                        'limit' => 1000,
                        'daysBack' => 100000,
                        'untilDays' => 100000,
                        'symbolRequired' => true,
                    ),
                    'fetchOrder' => array(
                        'marginMode' => false,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => true,
                    ),
                    'fetchOpenOrders' => array(
                        'marginMode' => false,
                        'limit' => null,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => true,
                    ),
                    'fetchOrders' => array(
                        'marginMode' => true,
                        'limit' => 1000,
                        'daysBack' => 100000,
                        'untilDays' => 100000,
                        'trigger' => false,
                        'trailing' => false,
                        'symbolRequired' => true,
                    ),
                    'fetchClosedOrders' => null,
                    'fetchOHLCV' => array(
                        'limit' => 1440,
                    ),
                ),
                'swap' => array(
                    'linear' => null,
                    'inverse' => null,
                ),
                'future' => array(
                    'linear' => null,
                    'inverse' => null,
                ),
            ),
            'exceptions' => array(
                'exact' => array(
                    '101' => '\\ccxt\\ExchangeError', // Unknown error. Operation may or may not have succeeded.
                    '102' => '\\ccxt\\BadRequest', // Invalid JSON.
                    '103' => '\\ccxt\\RateLimitExceeded', // You have been rate limited. Please observe the Bitvavo-Ratelimit-AllowAt header to see when you can send requests again. Failure to respect this limit will result in an IP ban. The default value is 1000 weighted requests per minute. Please contact support if you wish to increase this limit.
                    '104' => '\\ccxt\\RateLimitExceeded', // You have been rate limited by the number of new orders. The default value is 100 new orders per second or 100.000 new orders per day. Please update existing orders instead of cancelling and creating orders. Please contact support if you wish to increase this limit.
                    '105' => '\\ccxt\\PermissionDenied', // Your IP or API key has been banned for not respecting the rate limit. The ban expires at ${expiryInMs}.
                    '107' => '\\ccxt\\ExchangeNotAvailable', // The matching engine is overloaded. Please wait 500ms and resubmit your order.
                    '108' => '\\ccxt\\ExchangeNotAvailable', // The matching engine could not process your order in time. Please consider increasing the access window or resubmit your order.
                    '109' => '\\ccxt\\ExchangeNotAvailable', // The matching engine did not respond in time. Operation may or may not have succeeded.
                    '110' => '\\ccxt\\BadRequest', // Invalid endpoint. Please check url and HTTP method.
                    '200' => '\\ccxt\\BadRequest', // ${param} url parameter is not supported. Please note that parameters are case-sensitive and use body parameters for PUT and POST requests.
                    '201' => '\\ccxt\\BadRequest', // ${param} body parameter is not supported. Please note that parameters are case-sensitive and use url parameters for GET and DELETE requests.
                    '202' => '\\ccxt\\BadRequest', // ${param} order parameter is not supported. Please note that certain parameters are only allowed for market or limit orders.
                    '203' => '\\ccxt\\BadSymbol', // array("errorCode":203,"error":"symbol parameter is required.")
                    '204' => '\\ccxt\\BadRequest', // ${param} parameter is not supported.
                    '205' => '\\ccxt\\BadRequest', // ${param} parameter is invalid.
                    '206' => '\\ccxt\\BadRequest', // Use either ${paramA} or ${paramB}. The usage of both parameters at the same time is not supported.
                    '210' => '\\ccxt\\InvalidOrder', // Amount exceeds the maximum allowed amount (1000000000).
                    '211' => '\\ccxt\\InvalidOrder', // Price exceeds the maximum allowed amount (100000000000).
                    '212' => '\\ccxt\\InvalidOrder', // Amount is below the minimum allowed amount for this asset.
                    '213' => '\\ccxt\\InvalidOrder', // Price is below the minimum allowed amount (0.000000000000001).
                    '214' => '\\ccxt\\InvalidOrder', // Price is too detailed
                    '215' => '\\ccxt\\InvalidOrder', // Price is too detailed. A maximum of 15 digits behind the decimal point are allowed.
                    '216' => '\\ccxt\\InsufficientFunds', // array("errorCode":216,"error":"You do not have sufficient balance to complete this operation.")
                    '217' => '\\ccxt\\InvalidOrder', // array("errorCode":217,"error":"Minimum order size in quote currency is 5 EUR or 0.001 BTC.")
                    '230' => '\\ccxt\\ExchangeError', // The order is rejected by the matching engine.
                    '231' => '\\ccxt\\ExchangeError', // The order is rejected by the matching engine. TimeInForce must be GTC when markets are paused.
                    '232' => '\\ccxt\\BadRequest', // You must change at least one of amount, amountRemaining, price, timeInForce, selfTradePrevention or postOnly.
                    '233' => '\\ccxt\\InvalidOrder', // array("errorCode":233,"error":"Order must be active (status new or partiallyFilled) to allow updating/cancelling.")
                    '234' => '\\ccxt\\InvalidOrder', // Market orders cannot be updated.
                    '235' => '\\ccxt\\ExchangeError', // You can only have 100 open orders on each book.
                    '236' => '\\ccxt\\BadRequest', // You can only update amount or amountRemaining, not both.
                    '240' => '\\ccxt\\OrderNotFound', // array("errorCode":240,"error":"No order found. Please be aware that simultaneously updating the same order may return this error.")
                    '300' => '\\ccxt\\AuthenticationError', // Authentication is required for this endpoint.
                    '301' => '\\ccxt\\AuthenticationError', // array("errorCode":301,"error":"API Key must be of length 64.")
                    '302' => '\\ccxt\\AuthenticationError', // Timestamp is invalid. This must be a timestamp in ms. See Bitvavo-Access-Timestamp header or timestamp parameter for websocket.
                    '303' => '\\ccxt\\AuthenticationError', // Window must be between 100 and 60000 ms.
                    '304' => '\\ccxt\\AuthenticationError', // Request was not received within acceptable window (default 30s, or custom with Bitvavo-Access-Window header) of Bitvavo-Access-Timestamp header (or timestamp parameter for websocket).
                    // "304" => '\\ccxt\\AuthenticationError', // Authentication is required for this endpoint.
                    '305' => '\\ccxt\\AuthenticationError', // array("errorCode":305,"error":"No active API key found.")
                    '306' => '\\ccxt\\AuthenticationError', // No active API key found. Please ensure that you have confirmed the API key by e-mail.
                    '307' => '\\ccxt\\PermissionDenied', // This key does not allow access from this IP.
                    '308' => '\\ccxt\\AuthenticationError', // array("errorCode":308,"error":"The signature length is invalid (HMAC-SHA256 should return a 64 length hexadecimal string).")
                    '309' => '\\ccxt\\AuthenticationError', // array("errorCode":309,"error":"The signature is invalid.")
                    '310' => '\\ccxt\\PermissionDenied', // This key does not allow trading actions.
                    '311' => '\\ccxt\\PermissionDenied', // This key does not allow showing account information.
                    '312' => '\\ccxt\\PermissionDenied', // This key does not allow withdrawal of funds.
                    '315' => '\\ccxt\\BadRequest', // Websocket connections may not be used in a browser. Please use REST requests for $this->
                    '317' => '\\ccxt\\AccountSuspended', // This account is locked. Please contact support.
                    '400' => '\\ccxt\\ExchangeError', // Unknown error. Please contact support with a copy of your request.
                    '401' => '\\ccxt\\ExchangeError', // Deposits for this asset are not available at this time.
                    '402' => '\\ccxt\\PermissionDenied', // You need to verify your identitiy before you can deposit and withdraw digital assets.
                    '403' => '\\ccxt\\PermissionDenied', // You need to verify your phone number before you can deposit and withdraw digital assets.
                    '404' => '\\ccxt\\OnMaintenance', // Could not complete this operation, because our node cannot be reached. Possibly under maintenance.
                    '405' => '\\ccxt\\ExchangeError', // You cannot withdraw digital assets during a cooldown period. This is the result of newly added bank accounts.
                    '406' => '\\ccxt\\BadRequest', // array("errorCode":406,"error":"Your withdrawal is too small.")
                    '407' => '\\ccxt\\ExchangeError', // Internal transfer is not possible.
                    '408' => '\\ccxt\\InsufficientFunds', // array("errorCode":408,"error":"You do not have sufficient balance to complete this operation.")
                    '409' => '\\ccxt\\InvalidAddress', // array("errorCode":409,"error":"This is not a verified bank account.")
                    '410' => '\\ccxt\\ExchangeError', // Withdrawals for this asset are not available at this time.
                    '411' => '\\ccxt\\BadRequest', // You can not transfer assets to yourself.
                    '412' => '\\ccxt\\InvalidAddress', // array("errorCode":412,"error":"eth_address_invalid.")
                    '413' => '\\ccxt\\InvalidAddress', // This address violates the whitelist.
                    '414' => '\\ccxt\\ExchangeError', // You cannot withdraw assets within 2 minutes of logging in.
                ),
                'broad' => array(
                    'start parameter is invalid' => '\\ccxt\\BadRequest', // array("errorCode":205,"error":"start parameter is invalid.")
                    'symbol parameter is invalid' => '\\ccxt\\BadSymbol', // array("errorCode":205,"error":"symbol parameter is invalid.")
                    'amount parameter is invalid' => '\\ccxt\\InvalidOrder', // array("errorCode":205,"error":"amount parameter is invalid.")
                    'orderId parameter is invalid' => '\\ccxt\\InvalidOrder', // array("errorCode":205,"error":"orderId parameter is invalid.")
                ),
            ),
            'options' => array(
                'currencyToPrecisionRoundingMode' => TRUNCATE,
                'BITVAVO-ACCESS-WINDOW' => 10000, // default 10 sec
                'networks' => array(
                    'ERC20' => 'ETH',
                    'TRC20' => 'TRX',
                ),
                'operatorId' => null, // this will be required soon for order-related endpoints
                'fiatCurrencies' => array( 'EUR' ), // only fiat atm
            ),
            'precisionMode' => TICK_SIZE,
            'commonCurrencies' => array(
                'MIOTA' => 'IOTA', // https://github.com/ccxt/ccxt/issues/7487
            ),
        ));
    }

    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);
        //
        //     array( "time" => 1590379519148 )
        //
        return $this->safe_integer($response, 'time');
    }

    public function fetch_markets($params = array ()): array {
        /**
         *
         * @see https://docs.bitvavo.com/#tag/General/paths/~1markets/get
         *
         * retrieves data on all markets for bitvavo
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array[]} an array of objects representing market data
         */
        $response = $this->publicGetMarkets ($params);
        //
        //    {
        //        "market" => "BTC-EUR",
        //        "status" => "trading",
        //        "base" => "BTC",
        //        "quote" => "EUR",
        //        "pricePrecision" => "0", // deprecated, this is mostly 0 across other markets too, which is abnormal, so we ignore $this->
        //        "tickSize" => "1.00",
        //        "minOrderInBaseAsset" => "0.00006100",
        //        "minOrderInQuoteAsset" => "5.00",
        //        "maxOrderInBaseAsset" => "1000000000.00000000",
        //        "maxOrderInQuoteAsset" => "1000000000.00",
        //        "quantityDecimals" => "8",
        //        "notionalDecimals" => "2",
        //        "maxOpenOrders" => "100",
        //        "feeCategory" => "A",
        //        "orderTypes" => array( "market", "limit", "stopLoss", "stopLossLimit", "takeProfit", "takeProfitLimit" )
        //    }
        //
        return $this->parse_markets($response);
    }

    public function parse_markets($markets) {
        $result = array();
        $fees = $this->fees;
        for ($i = 0; $i < count($markets); $i++) {
            $market = $markets[$i];
            $id = $this->safe_string($market, 'market');
            $baseId = $this->safe_string($market, 'base');
            $quoteId = $this->safe_string($market, 'quote');
            $base = $this->safe_currency_code($baseId);
            $quote = $this->safe_currency_code($quoteId);
            $status = $this->safe_string($market, 'status');
            $result[] = $this->safe_market_structure(array(
                'id' => $id,
                'symbol' => $base . '/' . $quote,
                'base' => $base,
                'quote' => $quote,
                'settle' => null,
                'baseId' => $baseId,
                'quoteId' => $quoteId,
                'settleId' => null,
                'type' => 'spot',
                'spot' => true,
                'margin' => false,
                'swap' => false,
                'future' => false,
                'option' => false,
                'active' => ($status === 'trading'),
                'contract' => false,
                'linear' => null,
                'inverse' => null,
                'contractSize' => null,
                'expiry' => null,
                'expiryDatetime' => null,
                'strike' => null,
                'optionType' => null,
                'taker' => $fees['trading']['taker'],
                'maker' => $fees['trading']['maker'],
                'precision' => array(
                    'amount' => $this->parse_number($this->parse_precision($this->safe_string($market, 'quantityDecimals'))),
                    'price' => $this->safe_number($market, 'tickSize'),
                    'cost' => $this->parse_number($this->parse_precision($this->safe_string($market, 'notionalDecimals'))),
                ),
                'limits' => array(
                    'leverage' => array(
                        'min' => null,
                        'max' => null,
                    ),
                    'amount' => array(
                        'min' => $this->safe_number($market, 'minOrderInBaseAsset'),
                        'max' => $this->safe_number($market, 'maxOrderInBaseAsset'),
                    ),
                    'price' => array(
                        'min' => null,
                        'max' => null,
                    ),
                    'cost' => array(
                        'min' => $this->safe_number($market, 'minOrderInQuoteAsset'),
                        'max' => $this->safe_number($market, 'maxOrderInQuoteAsset'),
                    ),
                ),
                'created' => null,
                'info' => $market,
            ));
        }
        return $result;
    }

    public function fetch_currencies($params = array ()): ?array {
        /**
         *
         * @see https://docs.bitvavo.com/#tag/General/paths/~1assets/get
         *
         * fetches all available currencies on an exchange
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array} an associative dictionary of currencies
         */
        $response = $this->publicGetAssets ($params);
        //
        //     array(
        //         {
        //             "symbol" => "USDT",
        //             "displayTicker" => "USDT",
        //             "name" => "Tether",
        //             "slug" => "tether",
        //             "popularity" => -1,
        //             "decimals" => 6,
        //             "depositFee" => "0",
        //             "depositConfirmations" => 64,
        //             "depositStatus" => "OK",
        //             "withdrawalFee" => "3.2",
        //             "withdrawalMinAmount" => "3.2",
        //             "withdrawalStatus" => "OK",
        //             "networks" => array(
        //               "ETH"
        //             ),
        //             "light" => {
        //               "color" => "#009393",
        //               "icon" => array( "hash" => "4ad7c699", "svg" => "https://...", "webp16" => "https://...", "webp32" => "https://...", "webp64" => "https://...", "webp128" => "https://...", "webp256" => "https://...", "png16" => "https://...", "png32" => "https://...", "png64" => "https://...", "png128" => "https://...", "png256" => "https://..."
        //               }
        //             ),
        //             "dark" => array(
        //               "color" => "#009393",
        //               "icon" => array( "hash" => "4ad7c699", "svg" => "https://...", "webp16" => "https://...", "webp32" => "https://...", "webp64" => "https://...", "webp128" => "https://...", "webp256" => "https://...", "png16" => "https://...", "png32" => "https://...", "png64" => "https://...", "png128" => "https://...", "png256" => "https://..."
        //               }
        //             ),
        //             "visibility" => "PUBLIC",
        //             "message" => ""
        //         ),
        //     )
        //
        return $this->parse_currencies_custom($response);
    }

    public function parse_currencies_custom($currencies) {
        //
        //     array(
        //         {
        //             "symbol" => "USDT",
        //             "displayTicker" => "USDT",
        //             "name" => "Tether",
        //             "slug" => "tether",
        //             "popularity" => -1,
        //             "decimals" => 6,
        //             "depositFee" => "0",
        //             "depositConfirmations" => 64,
        //             "depositStatus" => "OK",
        //             "withdrawalFee" => "3.2",
        //             "withdrawalMinAmount" => "3.2",
        //             "withdrawalStatus" => "OK",
        //             "networks" => array(
        //               "ETH"
        //             ),
        //             "light" => {
        //               "color" => "#009393",
        //               "icon" => array( "hash" => "4ad7c699", "svg" => "https://...", "webp16" => "https://...", "webp32" => "https://...", "webp64" => "https://...", "webp128" => "https://...", "webp256" => "https://...", "png16" => "https://...", "png32" => "https://...", "png64" => "https://...", "png128" => "https://...", "png256" => "https://..."
        //               }
        //             ),
        //             "dark" => array(
        //               "color" => "#009393",
        //               "icon" => array( "hash" => "4ad7c699", "svg" => "https://...", "webp16" => "https://...", "webp32" => "https://...", "webp64" => "https://...", "webp128" => "https://...", "webp256" => "https://...", "png16" => "https://...", "png32" => "https://...", "png64" => "https://...", "png128" => "https://...", "png256" => "https://..."
        //               }
        //             ),
        //             "visibility" => "PUBLIC",
        //             "message" => ""
        //         ),
        //     )
        //
        $fiatCurrencies = $this->safe_list($this->options, 'fiatCurrencies', array());
        $result = array();
        for ($i = 0; $i < count($currencies); $i++) {
            $currency = $currencies[$i];
            $id = $this->safe_string($currency, 'symbol');
            $code = $this->safe_currency_code($id);
            $isFiat = $this->in_array($code, $fiatCurrencies);
            $networks = array();
            $networksArray = $this->safe_list($currency, 'networks', array());
            $deposit = $this->safe_string($currency, 'depositStatus') === 'OK';
            $withdrawal = $this->safe_string($currency, 'withdrawalStatus') === 'OK';
            $active = $deposit && $withdrawal;
            $withdrawFee = $this->safe_number($currency, 'withdrawalFee');
            $precision = $this->safe_string($currency, 'decimals', '8');
            $minWithdraw = $this->safe_number($currency, 'withdrawalMinAmount');
            // btw, absolutely all of them have 1 network atm
            for ($j = 0; $j < count($networksArray); $j++) {
                $networkId = $networksArray[$j];
                $networkCode = $this->network_id_to_code($networkId);
                $networks[$networkCode] = array(
                    'info' => $currency,
                    'id' => $networkId,
                    'network' => $networkCode,
                    'active' => $active,
                    'deposit' => $deposit,
                    'withdraw' => $withdrawal,
                    'fee' => $withdrawFee,
                    'precision' => $this->parse_number($this->parse_precision($precision)),
                    'limits' => array(
                        'withdraw' => array(
                            'min' => $minWithdraw,
                            'max' => null,
                        ),
                    ),
                );
            }
            $result[$code] = $this->safe_currency_structure(array(
                'info' => $currency,
                'id' => $id,
                'code' => $code,
                'name' => $this->safe_string($currency, 'name'),
                'active' => $active,
                'deposit' => $deposit,
                'withdraw' => $withdrawal,
                'networks' => $networks,
                'fee' => $withdrawFee,
                'precision' => null,
                'type' => $isFiat ? 'fiat' : 'crypto',
                'limits' => array(
                    'amount' => array(
                        'min' => null,
                        'max' => null,
                    ),
                    'deposit' => array(
                        'min' => null,
                        'max' => null,
                    ),
                    'withdraw' => array(
                        'min' => $minWithdraw,
                        'max' => null,
                    ),
                ),
            ));
        }
        return $result;
    }

    public function fetch_ticker(string $symbol, $params = array ()): array {
        /**
         *
         * @see https://docs.bitvavo.com/#tag/Market-Data/paths/{1ticker}124h/get
         *
         * 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(
            'market' => $market['id'],
        );
        $response = $this->publicGetTicker24h ($this->extend($request, $params));
        //
        //     {
        //         "market":"ETH-BTC",
        //         "open":"0.022578",
        //         "high":"0.023019",
        //         "low":"0.022572",
        //         "last":"0.023019",
        //         "volume":"25.16366324",
        //         "volumeQuote":"0.57333305",
        //         "bid":"0.023039",
        //         "bidSize":"0.53500578",
        //         "ask":"0.023041",
        //         "askSize":"0.47859202",
        //         "timestamp":1590381666900
        //     }
        //
        return $this->parse_ticker($response, $market);
    }

    public function parse_ticker(array $ticker, ?array $market = null): array {
        //
        // fetchTicker
        //
        //     {
        //         "market":"ETH-BTC",
        //         "open":"0.022578",
        //         "high":"0.023019",
        //         "low":"0.022573",
        //         "last":"0.023019",
        //         "volume":"25.16366324",
        //         "volumeQuote":"0.57333305",
        //         "bid":"0.023039",
        //         "bidSize":"0.53500578",
        //         "ask":"0.023041",
        //         "askSize":"0.47859202",
        //         "timestamp":1590381666900
        //     }
        //
        $marketId = $this->safe_string($ticker, 'market');
        $symbol = $this->safe_symbol($marketId, $market, '-');
        $timestamp = $this->safe_integer($ticker, 'timestamp');
        $last = $this->safe_string($ticker, 'last');
        $baseVolume = $this->safe_string($ticker, 'volume');
        $quoteVolume = $this->safe_string($ticker, 'volumeQuote');
        $open = $this->safe_string($ticker, 'open');
        return $this->safe_ticker(array(
            'symbol' => $symbol,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'high' => $this->safe_string($ticker, 'high'),
            'low' => $this->safe_string($ticker, 'low'),
            'bid' => $this->safe_string($ticker, 'bid'),
            'bidVolume' => $this->safe_string($ticker, 'bidSize'),
            'ask' => $this->safe_string($ticker, 'ask'),
            'askVolume' => $this->safe_string($ticker, 'askSize'),
            'vwap' => null,
            'open' => $open,
            'close' => $last,
            'last' => $last,
            'previousClose' => null, // previous day close
            'change' => null,
            'percentage' => null,
            'average' => null,
            'baseVolume' => $baseVolume,
            'quoteVolume' => $quoteVolume,
            '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
         * @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();
        $response = $this->publicGetTicker24h ($params);
        //
        //     array(
        //         {
        //             "market":"ADA-BTC",
        //             "open":"0.0000059595",
        //             "high":"0.0000059765",
        //             "low":"0.0000059595",
        //             "last":"0.0000059765",
        //             "volume":"2923.172",
        //             "volumeQuote":"0.01743483",
        //             "bid":"0.0000059515",
        //             "bidSize":"1117.630919",
        //             "ask":"0.0000059585",
        //             "askSize":"809.999739",
        //             "timestamp":1590382266324
        //         }
        //     )
        //
        return $this->parse_tickers($response, $symbols);
    }

    public function fetch_trades(string $symbol, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         *
         * @see https://docs.bitvavo.com/#tag/Market-Data/paths/{1}$market~~1trades/get
         *
         * 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
         * @param {int} [$params->until] the latest time in ms to fetch entries 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=public-trades trade structures~
         */
        $this->load_markets();
        $market = $this->market($symbol);
        $paginate = false;
        list($paginate, $params) = $this->handle_option_and_params($params, 'fetchTrades', 'paginate');
        if ($paginate) {
            return $this->fetch_paginated_call_dynamic('fetchTrades', $symbol, $since, $limit, $params);
        }
        $request = array(
            'market' => $market['id'],
            // "limit" => 500, // default 500, max 1000
            // "start" => $since,
            // "end" => $this->milliseconds(),
            // "tradeIdFrom" => "57b1159b-6bf5-4cde-9e2c-6bd6a5678baf",
            // "tradeIdTo" => "57b1159b-6bf5-4cde-9e2c-6bd6a5678baf",
        );
        if ($limit !== null) {
            $request['limit'] = min ($limit, 1000);
        }
        if ($since !== null) {
            $request['start'] = $since;
        }
        list($request, $params) = $this->handle_until_option('end', $request, $params);
        $response = $this->publicGetMarketTrades ($this->extend($request, $params));
        //
        //     array(
        //         {
        //             "id":"94154c98-6e8b-4e33-92a8-74e33fc05650",
        //             "timestamp":1590382761859,
        //             "amount":"0.06026079",
        //             "price":"8095.3",
        //             "side":"buy"
        //         }
        //     )
        //
        return $this->parse_trades($response, $market, $since, $limit);
    }

    public function parse_trade(array $trade, ?array $market = null): array {
        //
        // fetchTrades (public)
        //
        //     {
        //         "id":"94154c98-6e8b-4e33-92a8-74e33fc05650",
        //         "timestamp":1590382761859,
        //         "amount":"0.06026079",
        //         "price":"8095.3",
        //         "side":"buy"
        //     }
        //
        // createOrder, fetchOpenOrders, fetchOrders, editOrder (private)
        //
        //     {
        //         "id":"b0c86aa5-6ed3-4a2d-ba3a-be9a964220f4",
        //         "timestamp":1590505649245,
        //         "amount":"0.249825",
        //         "price":"183.49",
        //         "taker":true,
        //         "fee":"0.12038925",
        //         "feeCurrency":"EUR",
        //         "settled":true
        //     }
        //
        // fetchMyTrades (private)
        //
        //     {
        //         "id":"b0c86aa5-6ed3-4a2d-ba3a-be9a964220f4",
        //         "orderId":"af76d6ce-9f7c-4006-b715-bb5d430652d0",
        //         "timestamp":1590505649245,
        //         "market":"ETH-EUR",
        //         "side":"sell",
        //         "amount":"0.249825",
        //         "price":"183.49",
        //         "taker":true,
        //         "fee":"0.12038925",
        //         "feeCurrency":"EUR",
        //         "settled":true
        //     }
        //
        // watchMyTrades (private)
        //
        //     {
        //         "event" => "fill",
        //         "timestamp" => 1590964470132,
        //         "market" => "ETH-EUR",
        //         "orderId" => "85d082e1-eda4-4209-9580-248281a29a9a",
        //         "fillId" => "861d2da5-aa93-475c-8d9a-dce431bd4211",
        //         "side" => "sell",
        //         "amount" => "0.1",
        //         "price" => "211.46",
        //         "taker" => true,
        //         "fee" => "0.056",
        //         "feeCurrency" => "EUR"
        //     }
        //
        $priceString = $this->safe_string($trade, 'price');
        $amountString = $this->safe_string($trade, 'amount');
        $timestamp = $this->safe_integer($trade, 'timestamp');
        $side = $this->safe_string($trade, 'side');
        $id = $this->safe_string_2($trade, 'id', 'fillId');
        $marketId = $this->safe_string($trade, 'market');
        $symbol = $this->safe_symbol($marketId, $market, '-');
        $taker = $this->safe_value($trade, 'taker');
        $takerOrMaker = null;
        if ($taker !== null) {
            $takerOrMaker = $taker ? 'taker' : 'maker';
        }
        $feeCostString = $this->safe_string($trade, 'fee');
        $fee = null;
        if ($feeCostString !== null) {
            $feeCurrencyId = $this->safe_string($trade, 'feeCurrency');
            $feeCurrencyCode = $this->safe_currency_code($feeCurrencyId);
            $fee = array(
                'cost' => $feeCostString,
                'currency' => $feeCurrencyCode,
            );
        }
        $orderId = $this->safe_string($trade, 'orderId');
        return $this->safe_trade(array(
            'info' => $trade,
            'id' => $id,
            'symbol' => $symbol,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'order' => $orderId,
            'type' => null,
            'side' => $side,
            'takerOrMaker' => $takerOrMaker,
            'price' => $priceString,
            'amount' => $amountString,
            'cost' => null,
            'fee' => $fee,
        ), $market);
    }

    public function fetch_trading_fees($params = array ()): array {
        /**
         *
         * @see https://docs.bitvavo.com/#tag/Account/paths/~1account/get
         *
         * fetch the trading fees for multiple markets
         * @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->privateGetAccount ($params);
        //
        //     {
        //         "fees" => {
        //           "taker" => "0.0025",
        //           "maker" => "0.0015",
        //           "volume" => "10000.00"
        //         }
        //     }
        //
        return $this->parse_trading_fees($response);
    }

    public function parse_trading_fees($fees, $market = null) {
        //
        //     {
        //         "fees" => {
        //           "taker" => "0.0025",
        //           "maker" => "0.0015",
        //           "volume" => "10000.00"
        //         }
        //     }
        //
        $feesValue = $this->safe_value($fees, 'fees');
        $maker = $this->safe_number($feesValue, 'maker');
        $taker = $this->safe_number($feesValue, 'taker');
        $result = array();
        for ($i = 0; $i < count($this->symbols); $i++) {
            $symbol = $this->symbols[$i];
            $result[$symbol] = array(
                'info' => $fees,
                'symbol' => $symbol,
                'maker' => $maker,
                'taker' => $taker,
                'percentage' => true,
                'tierBased' => true,
            );
        }
        return $result;
    }

    public function fetch_order_book(string $symbol, ?int $limit = null, $params = array ()): array {
        /**
         *
         * @see https://docs.bitvavo.com/#tag/Market-Data/paths/{1}$market~~1book/get
         *
         * 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();
        $market = $this->market($symbol);
        $request = array(
            'market' => $market['id'],
        );
        if ($limit !== null) {
            $request['depth'] = $limit;
        }
        $response = $this->publicGetMarketBook ($this->extend($request, $params));
        //
        //     {
        //         "market":"BTC-EUR",
        //         "nonce":35883831,
        //         "bids":[
        //             ["8097.4","0.6229099"],
        //             ["8097.2","0.64151283"],
        //             ["8097.1","0.24966294"],
        //         ],
        //         "asks":[
        //             ["8097.5","1.36916911"],
        //             ["8098.8","0.33462248"],
        //             ["8099.3","1.12908646"],
        //         ]
        //     }
        //
        $orderbook = $this->parse_order_book($response, $market['symbol']);
        $orderbook['nonce'] = $this->safe_integer($response, 'nonce');
        return $orderbook;
    }

    public function parse_ohlcv($ohlcv, ?array $market = null): array {
        //
        //     array(
        //         1590383700000,
        //         "8088.5",
        //         "8088.5",
        //         "8088.5",
        //         "8088.5",
        //         "0.04788623"
        //     )
        //
        return array(
            $this->safe_integer($ohlcv, 0),
            $this->safe_number($ohlcv, 1),
            $this->safe_number($ohlcv, 2),
            $this->safe_number($ohlcv, 3),
            $this->safe_number($ohlcv, 4),
            $this->safe_number($ohlcv, 5),
        );
    }

    public function fetch_ohlcv_request(?string $symbol, $timeframe = '1m', ?int $since = null, ?int $limit = null, $params = array ()) {
        $market = $this->market($symbol);
        $request = array(
            'market' => $market['id'],
            'interval' => $this->safe_string($this->timeframes, $timeframe, $timeframe),
            // "limit" => 1440, // default 1440, max 1440
            // "start" => $since,
            // "end" => $this->milliseconds(),
        );
        if ($since !== null) {
            // https://github.com/ccxt/ccxt/issues/9227
            $duration = $this->parse_timeframe($timeframe);
            $request['start'] = $since;
            if ($limit === null) {
                $limit = 1440;
            } else {
                $limit = min ($limit, 1440);
            }
            $request['end'] = $this->sum($since, $limit * $duration * 1000);
        }
        list($request, $params) = $this->handle_until_option('end', $request, $params);
        if ($limit !== null) {
            $request['limit'] = $limit; // default 1440, max 1440
        }
        return $this->extend($request, $params);
    }

    public function fetch_ohlcv(?string $symbol, $timeframe = '1m', ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         *
         * @see https://docs.bitvavo.com/#tag/Market-Data/paths/{1}$market~~1candles/get
         *
         * 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 entries 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();
        $market = $this->market($symbol);
        $paginate = false;
        list($paginate, $params) = $this->handle_option_and_params($params, 'fetchOHLCV', 'paginate');
        if ($paginate) {
            return $this->fetch_paginated_call_deterministic('fetchOHLCV', $symbol, $since, $limit, $timeframe, $params, 1440);
        }
        $request = $this->fetch_ohlcv_request($symbol, $timeframe, $since, $limit, $params);
        $response = $this->publicGetMarketCandles ($request);
        //
        //     [
        //         [1590383700000,"8088.5","8088.5","8088.5","8088.5","0.04788623"],
        //         [1590383580000,"8091.3","8091.5","8091.3","8091.5","0.04931221"],
        //         [1590383520000,"8090.3","8092.7","8090.3","8092.5","0.04001286"],
        //     ]
        //
        return $this->parse_ohlcvs($response, $market, $timeframe, $since, $limit);
    }

    public function parse_balance($response): array {
        $result = array(
            'info' => $response,
            'timestamp' => null,
            'datetime' => null,
        );
        for ($i = 0; $i < count($response); $i++) {
            $balance = $response[$i];
            $currencyId = $this->safe_string($balance, 'symbol');
            $code = $this->safe_currency_code($currencyId);
            $account = $this->account();
            $account['free'] = $this->safe_string($balance, 'available');
            $account['used'] = $this->safe_string($balance, 'inOrder');
            $result[$code] = $account;
        }
        return $this->safe_balance($result);
    }

    public function fetch_balance($params = array ()): array {
        /**
         *
         * @see https://docs.bitvavo.com/#tag/Account/paths/~1balance/get
         *
         * query for balance and get the amount of funds available for trading or funds locked in orders
         * @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->privateGetBalance ($params);
        //
        //     array(
        //         {
        //             "symbol" => "BTC",
        //             "available" => "1.57593193",
        //             "inOrder" => "0.74832374"
        //         }
        //     )
        //
        return $this->parse_balance($response);
    }

    public function fetch_deposit_address(string $code, $params = array ()): array {
        /**
         * fetch the deposit $address for a $currency associated with this account
         * @param {string} $code unified $currency $code
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array} an ~@link https://docs.ccxt.com/#/?id=$address-structure $address structure~
         */
        $this->load_markets();
        $currency = $this->currency($code);
        $request = array(
            'symbol' => $currency['id'],
        );
        $response = $this->privateGetDeposit ($this->extend($request, $params));
        //
        //     {
        //         "address" => "0x449889e3234514c45d57f7c5a571feba0c7ad567",
        //         "paymentId" => "10002653"
        //     }
        //
        $address = $this->safe_string($response, 'address');
        $tag = $this->safe_string($response, 'paymentId');
        $this->check_address($address);
        return array(
            'info' => $response,
            'currency' => $code,
            'network' => null,
            'address' => $address,
            'tag' => $tag,
        );
    }

    public function create_order_request(?string $symbol, string $type, string $side, float $amount, ?float $price = null, $params = array ()) {
        $market = $this->market($symbol);
        $request = array(
            'market' => $market['id'],
            'side' => $side,
            'orderType' => $type,
        );
        $isMarketOrder = ($type === 'market') || ($type === 'stopLoss') || ($type === 'takeProfit');
        $isLimitOrder = ($type === 'limit') || ($type === 'stopLossLimit') || ($type === 'takeProfitLimit');
        $timeInForce = $this->safe_string($params, 'timeInForce');
        $triggerPrice = $this->safe_string_n($params, array( 'triggerPrice', 'stopPrice', 'triggerAmount' ));
        $postOnly = $this->is_post_only($isMarketOrder, false, $params);
        $stopLossPrice = $this->safe_value($params, 'stopLossPrice'); // trigger when $price crosses from above to below this value
        $takeProfitPrice = $this->safe_value($params, 'takeProfitPrice'); // trigger when $price crosses from below to above this value
        $params = $this->omit($params, array( 'timeInForce', 'triggerPrice', 'stopPrice', 'stopLossPrice', 'takeProfitPrice' ));
        if ($isMarketOrder) {
            $cost = null;
            if ($price !== null) {
                $priceString = $this->number_to_string($price);
                $amountString = $this->number_to_string($amount);
                $quoteAmount = Precise::string_mul($amountString, $priceString);
                $cost = $this->parse_number($quoteAmount);
            } else {
                $cost = $this->safe_number($params, 'cost');
            }
            if ($cost !== null) {
                $precision = $this->currency($market['quote'])['precision'];
                $request['amountQuote'] = $this->decimal_to_precision($cost, TRUNCATE, $precision, $this->precisionMode);
            } else {
                $request['amount'] = $this->amount_to_precision($symbol, $amount);
            }
            $params = $this->omit($params, array( 'cost' ));
        } elseif ($isLimitOrder) {
            $request['price'] = $this->price_to_precision($symbol, $price);
            $request['amount'] = $this->amount_to_precision($symbol, $amount);
        }
        $isTakeProfit = ($takeProfitPrice !== null) || ($type === 'takeProfit') || ($type === 'takeProfitLimit');
        $isStopLoss = ($stopLossPrice !== null) || ($triggerPrice !== null) && (!$isTakeProfit) || ($type === 'stopLoss') || ($type === 'stopLossLimit');
        if ($isStopLoss) {
            if ($stopLossPrice !== null) {
                $triggerPrice = $stopLossPrice;
            }
            $request['orderType'] = $isMarketOrder ? 'stopLoss' : 'stopLossLimit';
        } elseif ($isTakeProfit) {
            if ($takeProfitPrice !== null) {
                $triggerPrice = $takeProfitPrice;
            }
            $request['orderType'] = $isMarketOrder ? 'takeProfit' : 'takeProfitLimit';
        }
        if ($triggerPrice !== null) {
            $request['triggerAmount'] = $this->price_to_precision($symbol, $triggerPrice);
            $request['triggerType'] = 'price';
            $request['triggerReference'] = 'lastTrade'; // 'bestBid', 'bestAsk', 'midPrice'
        }
        if (($timeInForce !== null) && ($timeInForce !== 'PO')) {
            $request['timeInForce'] = $timeInForce;
        }
        if ($postOnly) {
            $request['postOnly'] = true;
        }
        $operatorId = null;
        list($operatorId, $params) = $this->handle_option_and_params($params, 'createOrder', 'operatorId');
        if ($operatorId !== null) {
            $request['operatorId'] = $this->parse_to_int($operatorId);
        } else {
            throw new ArgumentsRequired($this->id . ' createOrder() requires an $operatorId in $params or options, eg => exchange.options[\'operatorId\'] = 1234567890');
        }
        $selfTradePrevention = null;
        list($selfTradePrevention, $params) = $this->handle_option_and_params($params, 'createOrder', 'selfTradePrevention');
        if ($selfTradePrevention !== null) {
            if ($selfTradePrevention === 'EXPIRE_BOTH') {
                $request['selfTradePrevention'] = 'cancelBoth';
            } else {
                $request['selfTradePrevention'] = $selfTradePrevention;
            }
        }
        return $this->extend($request, $params);
    }

    public function create_order(?string $symbol, string $type, string $side, float $amount, ?float $price = null, $params = array ()) {
        /**
         * create a trade order
         *
         * @see https://docs.bitvavo.com/#tag/Trading-endpoints/paths/~1order/post
         *
         * @param {string} $symbol unified $symbol of the $market to create an order in
         * @param {string} $type 'market' or 'limit'
         * @param {string} $side 'buy' or 'sell'
         * @param {float} $amount how much of currency you want to trade in units of base currency
         * @param {float} $price the $price at which the order is to be fulfilled, in units of the quote currency, ignored in $market orders
         * @param {array} [$params] extra parameters specific to the bitvavo api endpoint
         * @param {string} [$params->timeInForce] "GTC", "IOC", or "PO"
         * @param {float} [$params->stopPrice] Alias for triggerPrice
         * @param {float} [$params->triggerPrice] The $price at which a trigger order is triggered at
         * @param {bool} [$params->postOnly] If true, the order will only be posted to the order book and not executed immediately
         * @param {float} [$params->stopLossPrice] The $price at which a stop loss order is triggered at
         * @param {float} [$params->takeProfitPrice] The $price at which a take profit order is triggered at
         * @param {string} [$params->triggerType] "price"
         * @param {string} [$params->triggerReference] "lastTrade", "bestBid", "bestAsk", "midPrice" Only for stop orders => Use this to determine which parameter will trigger the order
         * @param {string} [$params->selfTradePrevention] one of EXPIRE_BOTH, cancelOldest, cancelNewest or decrementAndCancel
         * @param {bool} [$params->disableMarketProtection] don't cancel if the next fill $price is 10% worse than the best fill $price
         * @param {bool} [$params->responseRequired] Set this to 'false' when only an acknowledgement of success or failure is required, this is faster.
         * @return {array} an ~@link https://docs.ccxt.com/#/?id=order-structure order structure~
         */
        $this->load_markets();
        $market = $this->market($symbol);
        $request = $this->create_order_request($symbol, $type, $side, $amount, $price, $params);
        $response = $this->privatePostOrder ($request);
        //
        //      {
        //          "orderId":"dec6a640-5b4c-45bc-8d22-3b41c6716630",
        //          "market":"DOGE-EUR",
        //          "created":1654789135146,
        //          "updated":1654789135153,
        //          "status":"new",
        //          "side":"buy",
        //          "orderType":"stopLossLimit",
        //          "amount":"200",
        //          "amountRemaining":"200",
        //          "price":"0.07471",
        //          "triggerPrice":"0.0747",
        //          "triggerAmount":"0.0747",
        //          "triggerType":"price",
        //          "triggerReference":"lastTrade",
        //          "onHold":"14.98",
        //          "onHoldCurrency":"EUR",
        //          "filledAmount":"0",
        //          "filledAmountQuote":"0",
        //          "feePaid":"0",
        //          "feeCurrency":"EUR",
        //          "fills":array( // filled with $market orders only
        //             {
        //                 "id":"b0c86aa5-6ed3-4a2d-ba3a-be9a964220f4",
        //                 "timestamp":1590505649245,
        //                 "amount":"0.249825",
        //                 "price":"183.49",
        //                 "taker":true,
        //                 "fee":"0.12038925",
        //                 "feeCurrency":"EUR",
        //                 "settled":true
        //             }
        //          ),
        //          "selfTradePrevention":"decrementAndCancel",
        //          "visible":true,
        //          "timeInForce":"GTC",
        //          "postOnly":false
        //      }
        //
        return $this->parse_order($response, $market);
    }

    public function edit_order_request(string $id, $symbol, $type, $side, $amount = null, $price = null, $params = array ()) {
        $request = array();
        $market = $this->market($symbol);
        $amountRemaining = $this->safe_number($params, 'amountRemaining');
        $triggerPrice = $this->safe_string_n($params, array( 'triggerPrice', 'stopPrice', 'triggerAmount' ));
        $params = $this->omit($params, array( 'amountRemaining', 'triggerPrice', 'stopPrice', 'triggerAmount' ));
        if ($price !== null) {
            $request['price'] = $this->price_to_precision($symbol, $price);
        }
        if ($amount !== null) {
            $request['amount'] = $this->amount_to_precision($symbol, $amount);
        }
        if ($amountRemaining !== null) {
            $request['amountRemaining'] = $this->amount_to_precision($symbol, $amountRemaining);
        }
        if ($triggerPrice !== null) {
            $request['triggerAmount'] = $this->price_to_precision($symbol, $triggerPrice);
        }
        $request = $this->extend($request, $params);
        if ($this->is_empty($request)) {
            throw new ArgumentsRequired($this->id . ' editOrder() requires an $amount argument, or a $price argument, or non-empty params');
        }
        $clientOrderId = $this->safe_string($params, 'clientOrderId');
        if ($clientOrderId === null) {
            $request['orderId'] = $id;
        }
        $operatorId = null;
        list($operatorId, $params) = $this->handle_option_and_params($params, 'editOrder', 'operatorId');
        if ($operatorId !== null) {
            $request['operatorId'] = $this->parse_to_int($operatorId);
        } else {
            throw new ArgumentsRequired($this->id . ' editOrder() requires an $operatorId in $params or options, eg => exchange.options[\'operatorId\'] = 1234567890');
        }
        $request['market'] = $market['id'];
        return $request;
    }

    public function edit_order(string $id, string $symbol, string $type, string $side, ?float $amount = null, ?float $price = null, $params = array ()) {
        /**
         * edit a trade order
         *
         * @see https://docs.bitvavo.com/#tag/Orders/paths/~1order/put
         *
         * @param {string} $id cancel order $id
         * @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 bitvavo api endpoint
         * @return {array} an ~@link https://docs.ccxt.com/#/?$id=order-structure order structure~
         */
        $this->load_markets();
        $market = $this->market($symbol);
        $request = $this->edit_order_request($id, $symbol, $type, $side, $amount, $price, $params);
        $response = $this->privatePutOrder ($request);
        return $this->parse_order($response, $market);
    }

    public function cancel_order_request(?string $id, ?string $symbol = null, $params = array ()) {
        if ($symbol === null) {
            throw new ArgumentsRequired($this->id . ' cancelOrder() requires a $symbol argument');
        }
        $market = $this->market($symbol);
        $request = array(
            'market' => $market['id'],
        );
        $clientOrderId = $this->safe_string($params, 'clientOrderId');
        if ($clientOrderId === null) {
            $request['orderId'] = $id;
        }
        $operatorId = null;
        list($operatorId, $params) = $this->handle_option_and_params($params, 'cancelOrder', 'operatorId');
        if ($operatorId !== null) {
            $request['operatorId'] = $this->parse_to_int($operatorId);
        } else {
            throw new ArgumentsRequired($this->id . ' cancelOrder() requires an $operatorId in $params or options, eg => exchange.options[\'operatorId\'] = 1234567890');
        }
        return $this->extend($request, $params);
    }

    public function cancel_order(string $id, ?string $symbol = null, $params = array ()) {
        /**
         *
         * @see https://docs.bitvavo.com/#tag/Orders/paths/~1order/delete
         *
         * cancels an open order
         *
         * @see https://docs.bitvavo.com/#tag/Trading-endpoints/paths/~1order/delete
         *
         * @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();
        $market = $this->market($symbol);
        $request = $this->cancel_order_request($id, $symbol, $params);
        $response = $this->privateDeleteOrder ($request);
        //
        //     {
        //         "orderId" => "2e7ce7fc-44e2-4d80-a4a7-d079c4750b61"
        //     }
        //
        return $this->parse_order($response, $market);
    }

    public function cancel_all_orders(?string $symbol = null, $params = array ()) {
        /**
         *
         * @see https://docs.bitvavo.com/#tag/Orders/paths/~1orders/delete
         *
         * 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['market'] = $market['id'];
        }
        $operatorId = null;
        list($operatorId, $params) = $this->handle_option_and_params($params, 'cancelAllOrders', 'operatorId');
        if ($operatorId !== null) {
            $request['operatorId'] = $this->parse_to_int($operatorId);
        } else {
            throw new ArgumentsRequired($this->id . ' canceAllOrders() requires an $operatorId in $params or options, eg => exchange.options[\'operatorId\'] = 1234567890');
        }
        $response = $this->privateDeleteOrders ($this->extend($request, $params));
        //
        //     array(
        //         {
        //             "orderId" => "1be6d0df-d5dc-4b53-a250-3376f3b393e6"
        //         }
        //     )
        //
        return $this->parse_orders($response, $market);
    }

    public function fetch_order(string $id, ?string $symbol = null, $params = array ()) {
        /**
         * fetches information on an order made by the user
         *
         * @see https://docs.bitvavo.com/#tag/Trading-endpoints/paths/~1order/get
         *
         * @param {string} $id the order $id
         * @param {string} $symbol unified $symbol of the $market the order was made in
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array} An ~@link https://docs.ccxt.com/#/?$id=order-structure order structure~
         */
        if ($symbol === null) {
            throw new ArgumentsRequired($this->id . ' fetchOrder() requires a $symbol argument');
        }
        $this->load_markets();
        $market = $this->market($symbol);
        $request = array(
            'market' => $market['id'],
        );
        $clientOrderId = $this->safe_string($params, 'clientOrderId');
        if ($clientOrderId === null) {
            $request['orderId'] = $id;
        }
        $response = $this->privateGetOrder ($this->extend($request, $params));
        //
        //     {
        //         "orderId":"af76d6ce-9f7c-4006-b715-bb5d430652d0",
        //         "market":"ETH-EUR",
        //         "created":1590505649241,
        //         "updated":1590505649241,
        //         "status":"filled",
        //         "side":"sell",
        //         "orderType":"market",
        //         "amount":"0.249825",
        //         "amountRemaining":"0",
        //         "onHold":"0",
        //         "onHoldCurrency":"ETH",
        //         "filledAmount":"0.249825",
        //         "filledAmountQuote":"45.84038925",
        //         "feePaid":"0.12038925",
        //         "feeCurrency":"EUR",
        //         "fills":array(
        //             {
        //                 "id":"b0c86aa5-6ed3-4a2d-ba3a-be9a964220f4",
        //                 "timestamp":1590505649245,
        //                 "amount":"0.249825",
        //                 "price":"183.49",
        //                 "taker":true,
        //                 "fee":"0.12038925",
        //                 "feeCurrency":"EUR",
        //                 "settled":true
        //             }
        //         ),
        //         "selfTradePrevention":"decrementAndCancel",
        //         "visible":false,
        //         "disableMarketProtection":false
        //     }
        //
        return $this->parse_order($response, $market);
    }

    public function fetch_orders_request(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()) {
        $market = $this->market($symbol);
        $request = array(
            'market' => $market['id'],
            // "limit" => 500,
            // "start" => $since,
            // "end" => $this->milliseconds(),
            // "orderIdFrom" => "af76d6ce-9f7c-4006-b715-bb5d430652d0",
            // "orderIdTo" => "af76d6ce-9f7c-4006-b715-bb5d430652d0",
        );
        if ($since !== null) {
            $request['start'] = $since;
        }
        if ($limit !== null) {
            $request['limit'] = $limit; // default 500, max 1000
        }
        list($request, $params) = $this->handle_until_option('end', $request, $params);
        return $this->extend($request, $params);
    }

    public function fetch_orders(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         *
         * @see https://docs.bitvavo.com/#tag/Trading-endpoints/paths/~1orders/get
         *
         * 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 {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)
         * @param {int} [$params->until] the latest time in ms to fetch entries for
         * @return {Order[]} a list of ~@link https://docs.ccxt.com/#/?id=order-structure order structures~
         */
        if ($symbol === null) {
            throw new ArgumentsRequired($this->id . ' fetchOrders() requires a $symbol argument');
        }
        $this->load_markets();
        $paginate = false;
        list($paginate, $params) = $this->handle_option_and_params($params, 'fetchOrders', 'paginate');
        if ($paginate) {
            return $this->fetch_paginated_call_dynamic('fetchOrders', $symbol, $since, $limit, $params);
        }
        $market = $this->market($symbol);
        $request = $this->fetch_orders_request($symbol, $since, $limit, $params);
        $response = $this->privateGetOrders ($request);
        //
        //     array(
        //         {
        //             "orderId":"af76d6ce-9f7c-4006-b715-bb5d430652d0",
        //             "market":"ETH-EUR",
        //             "created":1590505649241,
        //             "updated":1590505649241,
        //             "status":"filled",
        //             "side":"sell",
        //             "orderType":"market",
        //             "amount":"0.249825",
        //             "amountRemaining":"0",
        //             "onHold":"0",
        //             "onHoldCurrency":"ETH",
        //             "filledAmount":"0.249825",
        //             "filledAmountQuote":"45.84038925",
        //             "feePaid":"0.12038925",
        //             "feeCurrency":"EUR",
        //             "fills":array(
        //                 {
        //                     "id":"b0c86aa5-6ed3-4a2d-ba3a-be9a964220f4",
        //                     "timestamp":1590505649245,
        //                     "amount":"0.249825",
        //                     "price":"183.49",
        //                     "taker":true,
        //                     "fee":"0.12038925",
        //                     "feeCurrency":"EUR",
        //                     "settled":true
        //                 }
        //             ),
        //             "selfTradePrevention":"decrementAndCancel",
        //             "visible":false,
        //             "disableMarketProtection":false
        //         }
        //     )
        //
        return $this->parse_orders($response, $market, $since, $limit);
    }

    public function fetch_open_orders(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         *
         * @see https://docs.bitvavo.com/#tag/Trading-endpoints/paths/~1ordersOpen/get
         *
         * 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
         * @return {Order[]} a list of ~@link https://docs.ccxt.com/#/?id=order-structure order structures~
         */
        $this->load_markets();
        $request = array(
            // "market" => $market["id"], // rate $limit 25 without a $market, 1 with $market specified
        );
        $market = null;
        if ($symbol !== null) {
            $market = $this->market($symbol);
            $request['market'] = $market['id'];
        }
        $response = $this->privateGetOrdersOpen ($this->extend($request, $params));
        //
        //     array(
        //         {
        //             "orderId":"af76d6ce-9f7c-4006-b715-bb5d430652d0",
        //             "market":"ETH-EUR",
        //             "created":1590505649241,
        //             "updated":1590505649241,
        //             "status":"filled",
        //             "side":"sell",
        //             "orderType":"market",
        //             "amount":"0.249825",
        //             "amountRemaining":"0",
        //             "onHold":"0",
        //             "onHoldCurrency":"ETH",
        //             "filledAmount":"0.249825",
        //             "filledAmountQuote":"45.84038925",
        //             "feePaid":"0.12038925",
        //             "feeCurrency":"EUR",
        //             "fills":array(
        //                 {
        //                     "id":"b0c86aa5-6ed3-4a2d-ba3a-be9a964220f4",
        //                     "timestamp":1590505649245,
        //                     "amount":"0.249825",
        //                     "price":"183.49",
        //                     "taker":true,
        //                     "fee":"0.12038925",
        //                     "feeCurrency":"EUR",
        //                     "settled":true
        //                 }
        //             ),
        //             "selfTradePrevention":"decrementAndCancel",
        //             "visible":false,
        //             "disableMarketProtection":false
        //         }
        //     )
        //
        return $this->parse_orders($response, $market, $since, $limit);
    }

    public function parse_order_status(?string $status) {
        $statuses = array(
            'new' => 'open',
            'canceled' => 'canceled',
            'canceledAuction' => 'canceled',
            'canceledSelfTradePrevention' => 'canceled',
            'canceledIOC' => 'canceled',
            'canceledFOK' => 'canceled',
            'canceledMarketProtection' => 'canceled',
            'canceledPostOnly' => 'canceled',
            'filled' => 'closed',
            'partiallyFilled' => 'open',
            'expired' => 'canceled',
            'rejected' => 'canceled',
            'awaitingTrigger' => 'open', // https://github.com/ccxt/ccxt/issues/8489
        );
        return $this->safe_string($statuses, $status, $status);
    }

    public function parse_order(array $order, ?array $market = null): array {
        //
        // cancelOrder, cancelAllOrders
        //
        //     {
        //         "orderId" => "2e7ce7fc-44e2-4d80-a4a7-d079c4750b61"
        //     }
        //
        // createOrder, fetchOrder, fetchOpenOrders, fetchOrders, editOrder
        //
        //     {
        //         "orderId":"af76d6ce-9f7c-4006-b715-bb5d430652d0",
        //         "market":"ETH-EUR",
        //         "created":1590505649241,
        //         "updated":1590505649241,
        //         "status":"filled",
        //         "side":"sell",
        //         "orderType":"market",
        //         "amount":"0.249825",
        //         "amountRemaining":"0",
        //         "price" => "183.49", // limit orders only
        //         "onHold":"0",
        //         "onHoldCurrency":"ETH",
        //         "filledAmount":"0.249825",
        //         "filledAmountQuote":"45.84038925",
        //         "feePaid":"0.12038925",
        //         "feeCurrency":"EUR",
        //         "fills":array(
        //             {
        //                 "id":"b0c86aa5-6ed3-4a2d-ba3a-be9a964220f4",
        //                 "timestamp":1590505649245,
        //                 "amount":"0.249825",
        //                 "price":"183.49",
        //                 "taker":true,
        //                 "fee":"0.12038925",
        //                 "feeCurrency":"EUR",
        //                 "settled":true
        //             }
        //         ),
        //         "selfTradePrevention":"decrementAndCancel",
        //         "visible":false,
        //         "disableMarketProtection":false
        //         "timeInForce" => "GTC",
        //         "postOnly" => true,
        //     }
        //
        $id = $this->safe_string($order, 'orderId');
        $timestamp = $this->safe_integer($order, 'created');
        $marketId = $this->safe_string($order, 'market');
        $market = $this->safe_market($marketId, $market, '-');
        $symbol = $market['symbol'];
        $status = $this->parse_order_status($this->safe_string($order, 'status'));
        $side = $this->safe_string($order, 'side');
        $type = $this->safe_string($order, 'orderType');
        $price = $this->safe_string($order, 'price');
        $amount = $this->safe_string($order, 'amount');
        $remaining = $this->safe_string($order, 'amountRemaining');
        $filled = $this->safe_string($order, 'filledAmount');
        $cost = $this->safe_string($order, 'filledAmountQuote');
        if ($cost === null) {
            $amountQuote = $this->safe_string($order, 'amountQuote');
            $amountQuoteRemaining = $this->safe_string($order, 'amountQuoteRemaining');
            $cost = Precise::string_sub($amountQuote, $amountQuoteRemaining);
        }
        $fee = null;
        $feeCost = $this->safe_number($order, 'feePaid');
        if ($feeCost !== null) {
            $feeCurrencyId = $this->safe_string($order, 'feeCurrency');
            $feeCurrencyCode = $this->safe_currency_code($feeCurrencyId);
            $fee = array(
                'cost' => $feeCost,
                'currency' => $feeCurrencyCode,
            );
        }
        $rawTrades = $this->safe_value($order, 'fills', array());
        $timeInForce = $this->safe_string($order, 'timeInForce');
        $postOnly = $this->safe_value($order, 'postOnly');
        // https://github.com/ccxt/ccxt/issues/8489
        return $this->safe_order(array(
            'info' => $order,
            'id' => $id,
            'clientOrderId' => null,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'lastTradeTimestamp' => null,
            'symbol' => $symbol,
            'type' => $type,
            'timeInForce' => $timeInForce,
            'postOnly' => $postOnly,
            'side' => $side,
            'price' => $price,
            'triggerPrice' => $this->safe_number($order, 'triggerPrice'),
            'amount' => $amount,
            'cost' => $cost,
            'average' => null,
            'filled' => $filled,
            'remaining' => $remaining,
            'status' => $status,
            'fee' => $fee,
            'trades' => $rawTrades,
        ), $market);
    }

    public function fetch_my_trades_request(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()) {
        $market = $this->market($symbol);
        $request = array(
            'market' => $market['id'],
            // "limit" => 500,
            // "start" => $since,
            // "end" => $this->milliseconds(),
            // "tradeIdFrom" => "af76d6ce-9f7c-4006-b715-bb5d430652d0",
            // "tradeIdTo" => "af76d6ce-9f7c-4006-b715-bb5d430652d0",
        );
        if ($since !== null) {
            $request['start'] = $since;
        }
        if ($limit !== null) {
            $request['limit'] = $limit; // default 500, max 1000
        }
        list($request, $params) = $this->handle_until_option('end', $request, $params);
        return $this->extend($request, $params);
    }

    public function fetch_my_trades(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         *
         * @see https://docs.bitvavo.com/#tag/Trading-endpoints/paths/~1trades/get
         *
         * 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 entries 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');
        }
        $this->load_markets();
        $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);
        }
        $market = $this->market($symbol);
        $request = $this->fetch_my_trades_request($symbol, $since, $limit, $params);
        $response = $this->privateGetTrades ($request);
        //
        //     array(
        //         {
        //             "id":"b0c86aa5-6ed3-4a2d-ba3a-be9a964220f4",
        //             "orderId":"af76d6ce-9f7c-4006-b715-bb5d430652d0",
        //             "timestamp":1590505649245,
        //             "market":"ETH-EUR",
        //             "side":"sell",
        //             "amount":"0.249825",
        //             "price":"183.49",
        //             "taker":true,
        //             "fee":"0.12038925",
        //             "feeCurrency":"EUR",
        //             "settled":true
        //         }
        //     )
        //
        return $this->parse_trades($response, $market, $since, $limit);
    }

    public function withdraw_request(?string $code, $amount, $address, $tag = null, $params = array ()) {
        $currency = $this->currency($code);
        $request = array(
            'symbol' => $currency['id'],
            'amount' => $this->currency_to_precision($code, $amount),
            'address' => $address, // $address or IBAN
            // 'internal' => false, // transfer to another Bitvavo user $address, no fees
            // 'addWithdrawalFee' => false, // true = add the fee on top, otherwise the fee is subtracted from the $amount
        );
        if ($tag !== null) {
            $request['paymentId'] = $tag;
        }
        return $this->extend($request, $params);
    }

    public function withdraw(string $code, float $amount, string $address, ?string $tag = null, $params = array ()): array {
        /**
         * make a withdrawal
         * @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 = $this->withdraw_request($code, $amount, $address, $tag, $params);
        $response = $this->privatePostWithdrawal ($request);
        //
        //     {
        //         "success" => true,
        //         "symbol" => "BTC",
        //         "amount" => "1.5"
        //     }
        //
        return $this->parse_transaction($response, $currency);
    }

    public function fetch_withdrawals_request(?string $code = null, ?int $since = null, ?int $limit = null, $params = array ()) {
        $request = array(
            // 'symbol' => $currency['id'],
            // 'limit' => 500, // default 500, max 1000
            // 'start' => $since,
            // 'end' => $this->milliseconds(),
        );
        $currency = null;
        if ($code !== null) {
            $currency = $this->currency($code);
            $request['symbol'] = $currency['id'];
        }
        if ($since !== null) {
            $request['start'] = $since;
        }
        if ($limit !== null) {
            $request['limit'] = $limit; // default 500, max 1000
        }
        return $this->extend($request, $params);
    }

    public function fetch_withdrawals(?string $code = null, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         *
         * @see https://docs.bitvavo.com/#tag/Account/paths/~1withdrawalHistory/get
         *
         * fetch all withdrawals made from an account
         * @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 bitvavo api endpoint
         * @return {array[]} a list of ~@link https://docs.ccxt.com/#/?id=transaction-structure transaction structures~
         */
        $this->load_markets();
        $request = $this->fetch_withdrawals_request($code, $since, $limit, $params);
        $currency = null;
        if ($code !== null) {
            $currency = $this->currency($code);
        }
        $response = $this->privateGetWithdrawalHistory ($request);
        //
        //     array(
        //         {
        //             "timestamp":1590531212000,
        //             "symbol":"ETH",
        //             "amount":"0.091",
        //             "fee":"0.009",
        //             "status":"awaiting_bitvavo_inspection",
        //             "address":"0xe42b309f1eE9F0cbf7f54CcF3bc2159eBfA6735b",
        //             "paymentId" => "10002653",
        //             "txId" => "927b3ea50c5bb52c6854152d305dfa1e27fc01d10464cf10825d96d69d235eb3",
        //         }
        //     )
        //
        return $this->parse_transactions($response, $currency, $since, $limit, array( 'type' => 'withdrawal' ));
    }

    public function fetch_deposits_request(?string $code = null, ?int $since = null, ?int $limit = null, $params = array ()) {
        $request = array(
            // 'symbol' => $currency['id'],
            // 'limit' => 500, // default 500, max 1000
            // 'start' => $since,
            // 'end' => $this->milliseconds(),
        );
        $currency = null;
        if ($code !== null) {
            $currency = $this->currency($code);
            $request['symbol'] = $currency['id'];
        }
        if ($since !== null) {
            $request['start'] = $since;
        }
        if ($limit !== null) {
            $request['limit'] = $limit; // default 500, max 1000
        }
        return $this->extend($request, $params);
    }

    public function fetch_deposits(?string $code = null, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         *
         * @see https://docs.bitvavo.com/#tag/Account/paths/~1depositHistory/get
         *
         * fetch all deposits made to an account
         * @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 bitvavo api endpoint
         * @return {array[]} a list of ~@link https://docs.ccxt.com/#/?id=transaction-structure transaction structures~
         */
        $this->load_markets();
        $request = $this->fetch_deposits_request($code, $since, $limit, $params);
        $currency = null;
        if ($code !== null) {
            $currency = $this->currency($code);
        }
        $response = $this->privateGetDepositHistory ($request);
        //
        //     array(
        //         {
        //             "timestamp":1590492401000,
        //             "symbol":"ETH",
        //             "amount":"0.249825",
        //             "fee":"0",
        //             "status":"completed",
        //             "txId":"0x5167b473fd37811f9ef22364c3d54726a859ef9d98934b3a1e11d7baa8d2c2e2"
        //         }
        //     )
        //
        return $this->parse_transactions($response, $currency, $since, $limit, array( 'type' => 'deposit' ));
    }

    public function parse_transaction_status(?string $status) {
        $statuses = array(
            'awaiting_processing' => 'pending',
            'awaiting_email_confirmation' => 'pending',
            'awaiting_bitvavo_inspection' => 'pending',
            'approved' => 'pending',
            'sending' => 'pending',
            'in_mempool' => 'pending',
            'processed' => 'pending',
            'completed' => 'ok',
            'canceled' => 'canceled',
        );
        return $this->safe_string($statuses, $status, $status);
    }

    public function parse_transaction(array $transaction, ?array $currency = null): array {
        //
        // withdraw
        //
        //     {
        //         "success" => true,
        //         "symbol" => "BTC",
        //         "amount" => "1.5"
        //     }
        //
        // fetchWithdrawals
        //
        //     {
        //         "timestamp" => 1542967486256,
        //         "symbol" => "BTC",
        //         "amount" => "0.99994",
        //         "address" => "BitcoinAddress",
        //         "paymentId" => "10002653",
        //         "txId" => "927b3ea50c5bb52c6854152d305dfa1e27fc01d10464cf10825d96d69d235eb3",
        //         "fee" => "0.00006",
        //         "status" => "awaiting_processing"
        //     }
        //
        // fetchDeposits
        //
        //     {
        //         "timestamp":1590492401000,
        //         "symbol":"ETH",
        //         "amount":"0.249825",
        //         "fee":"0",
        //         "status":"completed",
        //         "txId":"0x5167b473fd37811f9ef22364c3d54726a859ef9d98934b3a1e11d7baa8d2c2e2"
        //     }
        //
        $id = null;
        $timestamp = $this->safe_integer($transaction, 'timestamp');
        $currencyId = $this->safe_string($transaction, 'symbol');
        $code = $this->safe_currency_code($currencyId, $currency);
        $status = $this->parse_transaction_status($this->safe_string($transaction, 'status'));
        $amount = $this->safe_number($transaction, 'amount');
        $address = $this->safe_string($transaction, 'address');
        $txid = $this->safe_string($transaction, 'txId');
        $fee = null;
        $feeCost = $this->safe_number($transaction, 'fee');
        if ($feeCost !== null) {
            $fee = array(
                'cost' => $feeCost,
                'currency' => $code,
            );
        }
        $type = null;
        if ((is_array($transaction) && array_key_exists('success', $transaction)) || (is_array($transaction) && array_key_exists('address', $transaction))) {
            $type = 'withdrawal';
        } else {
            $type = 'deposit';
        }
        $tag = $this->safe_string($transaction, 'paymentId');
        return array(
            'info' => $transaction,
            'id' => $id,
            'txid' => $txid,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'addressFrom' => null,
            'address' => $address,
            'addressTo' => $address,
            'tagFrom' => null,
            'tag' => $tag,
            'tagTo' => $tag,
            'type' => $type,
            'amount' => $amount,
            'currency' => $code,
            'status' => $status,
            'updated' => null,
            'fee' => $fee,
            'network' => null,
            'comment' => null,
            'internal' => null,
        );
    }

    public function parse_deposit_withdraw_fee($fee, ?array $currency = null) {
        //
        //   {
        //       "symbol" => "1INCH",
        //       "name" => "1inch",
        //       "decimals" => 8,
        //       "depositFee" => "0",
        //       "depositConfirmations" => 64,
        //       "depositStatus" => "OK",
        //       "withdrawalFee" => "6.1",
        //       "withdrawalMinAmount" => "6.1",
        //       "withdrawalStatus" => "OK",
        //       "networks" => array(
        //         "ETH"
        //       ),
        //       "message" => ""
        //   }
        //
        $result = array(
            'info' => $fee,
            'withdraw' => array(
                'fee' => $this->safe_number($fee, 'withdrawalFee'),
                'percentage' => false,
            ),
            'deposit' => array(
                'fee' => $this->safe_number($fee, 'depositFee'),
                'percentage' => false,
            ),
            'networks' => array(),
        );
        $networks = $this->safe_value($fee, 'networks');
        $networkId = $this->safe_value($networks, 0); // Bitvavo currently only supports one network per $currency
        $currencyCode = $this->safe_string($currency, 'code');
        if ($networkId === 'Mainnet') {
            $networkId = $currencyCode;
        }
        $networkCode = $this->network_id_to_code($networkId, $currencyCode);
        $result['networks'][$networkCode] = array(
            'deposit' => $result['deposit'],
            'withdraw' => $result['withdraw'],
        );
        return $result;
    }

    public function fetch_deposit_withdraw_fees(?array $codes = null, $params = array ()) {
        /**
         * fetch deposit and withdraw fees
         *
         * @see https://docs.bitvavo.com/#tag/General/paths/~1assets/get
         *
         * @param {string[]|null} $codes list of unified currency $codes
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array} a list of ~@link https://docs.ccxt.com/#/?id=fee-structure fee structures~
         */
        $this->load_markets();
        $response = $this->publicGetAssets ($params);
        //
        //   array(
        //       array(
        //           "symbol" => "1INCH",
        //           "name" => "1inch",
        //           "decimals" => 8,
        //           "depositFee" => "0",
        //           "depositConfirmations" => 64,
        //           "depositStatus" => "OK",
        //           "withdrawalFee" => "6.1",
        //           "withdrawalMinAmount" => "6.1",
        //           "withdrawalStatus" => "OK",
        //           "networks" => array(
        //             "ETH"
        //           ),
        //           "message" => ""
        //       ),
        //   )
        //
        return $this->parse_deposit_withdraw_fees($response, $codes, 'symbol');
    }

    public function sign($path, $api = 'public', $method = 'GET', $params = array (), $headers = null, $body = null) {
        $query = $this->omit($params, $this->extract_params($path));
        $url = '/' . $this->version . '/' . $this->implode_params($path, $params);
        $getOrDelete = ($method === 'GET') || ($method === 'DELETE');
        if ($getOrDelete) {
            if ($query) {
                $url .= '?' . $this->urlencode($query);
            }
        }
        if ($api === 'private') {
            $this->check_required_credentials();
            $payload = '';
            if (!$getOrDelete) {
                if ($query) {
                    $body = $this->json($query);
                    $payload = $body;
                }
            }
            $timestamp = (string) $this->milliseconds();
            $auth = $timestamp . $method . $url . $payload;
            $signature = $this->hmac($this->encode($auth), $this->encode($this->secret), 'sha256');
            $accessWindow = $this->safe_string($this->options, 'BITVAVO-ACCESS-WINDOW', '10000');
            $headers = array(
                'BITVAVO-ACCESS-KEY' => $this->apiKey,
                'BITVAVO-ACCESS-SIGNATURE' => $signature,
                'BITVAVO-ACCESS-TIMESTAMP' => $timestamp,
                'BITVAVO-ACCESS-WINDOW' => $accessWindow,
            );
            if (!$getOrDelete) {
                $headers['Content-Type'] = 'application/json';
            }
        }
        $url = $this->urls['api'][$api] . $url;
        return array( 'url' => $url, 'method' => $method, 'body' => $body, 'headers' => $headers );
    }

    public function handle_errors(int $httpCode, string $reason, string $url, string $method, array $headers, string $body, $response, $requestHeaders, $requestBody) {
        if ($response === null) {
            return null; // fallback to default $error handler
        }
        //
        //     array("errorCode":308,"error":"The signature length is invalid (HMAC-SHA256 should return a 64 length hexadecimal string).")
        //     array("errorCode":203,"error":"symbol parameter is required.")
        //     array("errorCode":205,"error":"symbol parameter is invalid.")
        //
        $errorCode = $this->safe_string($response, 'errorCode');
        $error = $this->safe_string($response, 'error');
        if ($errorCode !== null) {
            $feedback = $this->id . ' ' . $body;
            $this->throw_broadly_matched_exception($this->exceptions['broad'], $error, $feedback);
            $this->throw_exactly_matched_exception($this->exceptions['exact'], $errorCode, $feedback);
            throw new ExchangeError($feedback); // unknown message
        }
        return null;
    }

    public function calculate_rate_limiter_cost($api, $method, $path, $params, $config = array ()) {
        if ((is_array($config) && array_key_exists('noMarket', $config)) && !(is_array($params) && array_key_exists('market', $params))) {
            return $config['noMarket'];
        }
        return $this->safe_value($config, 'cost', 1);
    }
}
