<?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\ExchangeError;
use \ccxt\ArgumentsRequired;

class bitvavo extends Exchange {

    public function describe() {
        return $this->deep_extend(parent::describe (), array(
            'id' => 'bitvavo',
            'name' => 'Bitvavo',
            'countries' => array( 'NL' ), // Netherlands
            'rateLimit' => 500,
            'version' => 'v2',
            'certified' => true,
            'pro' => true,
            'has' => array(
                'CORS' => false,
                'publicAPI' => true,
                'privateAPI' => true,
                'cancelAllOrders' => true,
                'cancelOrder' => true,
                'createOrder' => true,
                'editOrder' => true,
                'fetchBalance' => true,
                'fetchCurrencies' => true,
                'fetchDepositAddress' => true,
                'fetchDeposits' => true,
                'fetchMyTrades' => true,
                'fetchOHLCV' => true,
                'fetchOpenOrders' => true,
                'fetchOrder' => true,
                'fetchOrders' => true,
                'fetchOrderBook' => true,
                'fetchMarkets' => true,
                'fetchTicker' => true,
                'fetchTickers' => true,
                'fetchTime' => true,
                'fetchTrades' => true,
                'fetchWithdrawals' => true,
                '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://user-images.githubusercontent.com/1294454/83165440-2f1cf200-a116-11ea-9046-a255d09fb2ed.jpg',
                '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',
                        'markets',
                        'assets',
                        '{market}/book',
                        '{market}/trades',
                        '{market}/candles',
                        'ticker/price',
                        'ticker/book',
                        'ticker/24h',
                    ),
                ),
                'private' => array(
                    'get' => array(
                        'order',
                        'orders',
                        'ordersOpen',
                        'trades',
                        'balance',
                        'deposit',
                        'depositHistory',
                        'withdrawalHistory',
                    ),
                    'post' => array(
                        'order',
                        'withdrawal',
                    ),
                    'put' => array(
                        'order',
                    ),
                    'delete' => array(
                        'order',
                        'orders',
                    ),
                ),
            ),
            'fees' => array(
                'trading' => array(
                    'tierBased' => true,
                    'percentage' => true,
                    'taker' => 0.25 / 100,
                    'maker' => 0.20 / 100,
                    'tiers' => array(
                        'taker' => array(
                            array( 0, 0.0025 ),
                            array( 50000, 0.0024 ),
                            array( 100000, 0.0022 ),
                            array( 250000, 0.0020 ),
                            array( 500000, 0.0018 ),
                            array( 1000000, 0.0016 ),
                            array( 2500000, 0.0014 ),
                            array( 5000000, 0.0012 ),
                            array( 10000000, 0.0010 ),
                        ),
                        'maker' => array(
                            array( 0, 0.0020 ),
                            array( 50000, 0.0015 ),
                            array( 100000, 0.0010 ),
                            array( 250000, 0.0006 ),
                            array( 500000, 0.0003 ),
                            array( 1000000, 0.0001 ),
                            array( 2500000, -0.0001 ),
                            array( 5000000, -0.0003 ),
                            array( 10000000, -0.0005 ),
                        ),
                    ),
                ),
            ),
            'requiredCredentials' => array(
                'apiKey' => true,
                'secret' => true,
            ),
            '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(
                'BITVAVO-ACCESS-WINDOW' => 10000, // default 10 sec
                'fetchCurrencies' => array(
                    'expires' => 1000, // 1 second
                ),
            ),
            'precisionMode' => SIGNIFICANT_DIGITS,
            'commonCurrencies' => array(
                'MIOTA' => 'IOTA', // https://github.com/ccxt/ccxt/issues/7487
            ),
        ));
    }

    public function currency_to_precision($currency, $fee) {
        return $this->decimal_to_precision($fee, 0, $this->currencies[$currency]['precision']);
    }

    public function amount_to_precision($symbol, $amount) {
        // https://docs.bitfinex.com/docs/introduction#$amount-precision
        // The $amount field allows up to 8 decimals.
        // Anything exceeding this will be rounded to the 8th decimal.
        return $this->decimal_to_precision($amount, TRUNCATE, $this->markets[$symbol]['precision']['amount'], DECIMAL_PLACES);
    }

    public function price_to_precision($symbol, $price) {
        $price = $this->decimal_to_precision($price, ROUND, $this->markets[$symbol]['precision']['price'], $this->precisionMode);
        // https://docs.bitfinex.com/docs/introduction#$price-precision
        // The precision level of all trading prices is based on significant figures.
        // All pairs on Bitfinex use up to 5 significant digits and up to 8 decimals (e.g. 1.2345, 123.45, 1234.5, 0.00012345).
        // Prices submit with a precision larger than 5 will be cut by the API.
        return $this->decimal_to_precision($price, TRUNCATE, 8, DECIMAL_PLACES);
    }

    public function fetch_time($params = array ()) {
        $response = $this->publicGetTime ($params);
        //
        //     array( "time" => 1590379519148 )
        //
        return $this->safe_integer($response, 'time');
    }

    public function fetch_markets($params = array ()) {
        $response = $this->publicGetMarkets ($params);
        $currencies = $this->fetch_currencies_from_cache($params);
        $currenciesById = $this->index_by($currencies, 'symbol');
        //
        //     array(
        //         {
        //             "$market":"ADA-BTC",
        //             "$status":"trading", // "trading" "halted" "auction"
        //             "$base":"ADA",
        //             "$quote":"BTC",
        //             "pricePrecision":5,
        //             "minOrderInBaseAsset":"100",
        //             "minOrderInQuoteAsset":"0.001",
        //             "orderTypes" => array( "$market", "limit" )
        //         }
        //     )
        //
        $result = array();
        for ($i = 0; $i < count($response); $i++) {
            $market = $response[$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);
            $symbol = $base . '/' . $quote;
            $status = $this->safe_string($market, 'status');
            $active = ($status === 'trading');
            $baseCurrency = $this->safe_value($currenciesById, $baseId);
            $amountPrecision = null;
            if ($baseCurrency !== null) {
                $amountPrecision = $this->safe_integer($baseCurrency, 'decimals', 8);
            }
            $precision = array(
                'price' => $this->safe_integer($market, 'pricePrecision'),
                'amount' => $amountPrecision,
            );
            $result[] = array(
                'id' => $id,
                'symbol' => $symbol,
                'base' => $base,
                'quote' => $quote,
                'baseId' => $baseId,
                'quoteId' => $quoteId,
                'info' => $market,
                'active' => $active,
                'precision' => $precision,
                'limits' => array(
                    'amount' => array(
                        'min' => $this->safe_float($market, 'minOrderInBaseAsset'),
                        'max' => null,
                    ),
                    'price' => array(
                        'min' => null,
                        'max' => null,
                    ),
                    'cost' => array(
                        'min' => $this->safe_float($market, 'minOrderInQuoteAsset'),
                        'max' => null,
                    ),
                ),
            );
        }
        return $result;
    }

    public function fetch_currencies_from_cache($params = array ()) {
        // this method is $now redundant
        // currencies are $now fetched before markets
        $options = $this->safe_value($this->options, 'fetchCurrencies', array());
        $timestamp = $this->safe_integer($options, 'timestamp');
        $expires = $this->safe_integer($options, 'expires', 1000);
        $now = $this->milliseconds();
        if (($timestamp === null) || (($now - $timestamp) > $expires)) {
            $response = $this->publicGetAssets ($params);
            $this->options['fetchCurrencies'] = array_merge($options, array(
                'response' => $response,
                'timestamp' => $now,
            ));
        }
        return $this->safe_value($this->options['fetchCurrencies'], 'response');
    }

    public function fetch_currencies($params = array ()) {
        $response = $this->fetch_currencies_from_cache($params);
        //
        //     array(
        //         array(
        //             "symbol":"ADA",
        //             "$name":"Cardano",
        //             "decimals":6,
        //             "depositFee":"0",
        //             "depositConfirmations":15,
        //             "$depositStatus":"OK", // "OK", "MAINTENANCE", "DELISTED"
        //             "withdrawalFee":"0.2",
        //             "withdrawalMinAmount":"0.2",
        //             "$withdrawalStatus":"OK", // "OK", "MAINTENANCE", "DELISTED"
        //             "networks" => array( "Mainnet" ), // "ETH", "NEO", "ONT", "SEPA", "VET"
        //             "message":"",
        //         ),
        //     )
        //
        $result = array();
        for ($i = 0; $i < count($response); $i++) {
            $currency = $response[$i];
            $id = $this->safe_string($currency, 'symbol');
            $code = $this->safe_currency_code($id);
            $depositStatus = $this->safe_value($currency, 'depositStatus');
            $deposit = ($depositStatus === 'OK');
            $withdrawalStatus = $this->safe_value($currency, 'withdrawalStatus');
            $withdrawal = ($withdrawalStatus === 'OK');
            $active = $deposit && $withdrawal;
            $name = $this->safe_string($currency, 'name');
            $precision = $this->safe_integer($currency, 'decimals', 8);
            $result[$code] = array(
                'id' => $id,
                'info' => $currency,
                'code' => $code,
                'name' => $name,
                'active' => $active,
                'fee' => $this->safe_float($currency, 'withdrawalFee'),
                'precision' => $precision,
                'limits' => array(
                    'amount' => array(
                        'min' => null,
                        'max' => null,
                    ),
                    'price' => array(
                        'min' => null,
                        'max' => null,
                    ),
                    'cost' => array(
                        'min' => null,
                        'max' => null,
                    ),
                    'withdraw' => array(
                        'min' => $this->safe_float($currency, 'withdrawalMinAmount'),
                        'max' => null,
                    ),
                ),
            );
        }
        return $result;
    }

    public function fetch_ticker($symbol, $params = array ()) {
        $this->load_markets();
        $market = $this->market($symbol);
        $request = array(
            'market' => $market['id'],
        );
        $response = $this->publicGetTicker24h (array_merge($request, $params));
        //
        //     {
        //         "$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
        //     }
        //
        return $this->parse_ticker($response, $market);
    }

    public function parse_ticker($ticker, $market = null) {
        //
        // 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_float($ticker, 'last');
        $baseVolume = $this->safe_float($ticker, 'volume');
        $quoteVolume = $this->safe_float($ticker, 'volumeQuote');
        $vwap = $this->vwap($baseVolume, $quoteVolume);
        $change = null;
        $percentage = null;
        $average = null;
        $open = $this->safe_float($ticker, 'open');
        if (($open !== null) && ($last !== null)) {
            $change = $last - $open;
            if ($open > 0) {
                $percentage = $change / $open * 100;
            }
            $average = $this->sum($open, $last) / 2;
        }
        $result = array(
            'symbol' => $symbol,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'high' => $this->safe_float($ticker, 'high'),
            'low' => $this->safe_float($ticker, 'low'),
            'bid' => $this->safe_float($ticker, 'bid'),
            'bidVolume' => $this->safe_float($ticker, 'bidSize'),
            'ask' => $this->safe_float($ticker, 'ask'),
            'askVolume' => $this->safe_float($ticker, 'askSize'),
            'vwap' => $vwap,
            'open' => $open,
            'close' => $last,
            'last' => $last,
            'previousClose' => null, // previous day close
            'change' => $change,
            'percentage' => $percentage,
            'average' => $average,
            'baseVolume' => $baseVolume,
            'quoteVolume' => $quoteVolume,
            'info' => $ticker,
        );
        return $result;
    }

    public function parse_tickers($tickers, $symbols = null) {
        $result = array();
        for ($i = 0; $i < count($tickers); $i++) {
            $result[] = $this->parse_ticker($tickers[$i]);
        }
        return $this->filter_by_array($result, 'symbol', $symbols);
    }

    public function fetch_tickers($symbols = null, $params = array ()) {
        $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($symbol, $since = null, $limit = null, $params = array ()) {
        $this->load_markets();
        $market = $this->market($symbol);
        $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'] = $limit;
        }
        if ($since !== null) {
            $request['start'] = $since;
        }
        $response = $this->publicGetMarketTrades (array_merge($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($trade, $market = null) {
        //
        // 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'
        //     }
        //
        $price = $this->safe_float($trade, 'price');
        $amount = $this->safe_float($trade, 'amount');
        $cost = null;
        if (($price !== null) && ($amount !== null)) {
            $cost = $price * $amount;
        }
        $timestamp = $this->safe_integer($trade, 'timestamp');
        $side = $this->safe_string($trade, 'side');
        $id = $this->safe_string_2($trade, 'id', 'fillId');
        $marketId = $this->safe_integer($trade, 'market');
        $symbol = $this->safe_symbol($marketId, $market, '-');
        $taker = $this->safe_value($trade, 'taker');
        $takerOrMaker = null;
        if ($taker !== null) {
            $takerOrMaker = $taker ? 'taker' : 'maker';
        }
        $feeCost = $this->safe_float($trade, 'fee');
        $fee = null;
        if ($feeCost !== null) {
            $feeCurrencyId = $this->safe_string($trade, 'feeCurrency');
            $feeCurrencyCode = $this->safe_currency_code($feeCurrencyId);
            $fee = array(
                'cost' => $feeCost,
                'currency' => $feeCurrencyCode,
            );
        }
        $orderId = $this->safe_string($trade, 'orderId');
        return array(
            'info' => $trade,
            'id' => $id,
            'symbol' => $symbol,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'order' => $orderId,
            'type' => null,
            'side' => $side,
            'takerOrMaker' => $takerOrMaker,
            'price' => $price,
            'amount' => $amount,
            'cost' => $cost,
            'fee' => $fee,
        );
    }

    public function fetch_order_book($symbol, $limit = null, $params = array ()) {
        $this->load_markets();
        $request = array(
            'market' => $this->market_id($symbol),
        );
        if ($limit !== null) {
            $request['depth'] = $limit;
        }
        $response = $this->publicGetMarketBook (array_merge($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);
        $orderbook['nonce'] = $this->safe_integer($response, 'nonce');
        return $orderbook;
    }

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

    public function fetch_ohlcv($symbol, $timeframe = '1m', $since = null, $limit = null, $params = array ()) {
        $this->load_markets();
        $market = $this->market($symbol);
        $request = array(
            'market' => $market['id'],
            'interval' => $this->timeframes[$timeframe],
            // 'limit' => 1440, // default 1440, max 1440
            // 'start' => $since,
            // 'end' => $this->milliseconds(),
        );
        if ($since !== null) {
            $request['start'] = $since;
        }
        if ($limit !== null) {
            $request['limit'] = $limit; // default 1440, max 1440
        }
        $response = $this->publicGetMarketCandles (array_merge($request, $params));
        //
        //     [
        //         [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 fetch_balance($params = array ()) {
        $this->load_markets();
        $response = $this->privateGetBalance ($params);
        //
        //     array(
        //         {
        //             "symbol" => "BTC",
        //             "available" => "1.57593193",
        //             "inOrder" => "0.74832374"
        //         }
        //     )
        //
        $result = array( 'info' => $response );
        for ($i = 0; $i < count($response); $i++) {
            $balance = $response[$i];
            $currencyId = $this->safe_string($balance, 'symbol');
            $code = $this->safe_currency_code($currencyId);
            $account = array(
                'free' => $this->safe_float($balance, 'available'),
                'used' => $this->safe_float($balance, 'inOrder'),
            );
            $result[$code] = $account;
        }
        return $this->parse_balance($result);
    }

    public function fetch_deposit_address($code, $params = array ()) {
        $this->load_markets();
        $currency = $this->currency($code);
        $request = array(
            'symbol' => $currency['id'],
        );
        $response = $this->privateGetDeposit (array_merge($request, $params));
        //
        //     {
        //         "$address" => "0x449889e3234514c45d57f7c5a571feba0c7ad567",
        //         "paymentId" => "10002653"
        //     }
        //
        $address = $this->safe_string($response, 'address');
        $tag = $this->safe_string($response, 'paymentId');
        $this->check_address($address);
        return array(
            'currency' => $code,
            'address' => $address,
            'tag' => $tag,
            'info' => $response,
        );
    }

    public function create_order($symbol, $type, $side, $amount, $price = null, $params = array ()) {
        $this->load_markets();
        $market = $this->market($symbol);
        $request = array(
            'market' => $market['id'],
            'side' => $side,
            'orderType' => $type,
            // 'amount' => $this->amount_to_precision($symbol, $amount),
            // 'price' => $this->price_to_precision($symbol, $price),
            // 'amountQuote' => $this->cost_to_precision($symbol, $cost),
            // 'timeInForce' => 'GTC', // "GTC" "IOC" "FOK"
            // 'selfTradePrevention' => "decrementAndCancel", // "decrementAndCancel" "cancelOldest" "cancelNewest" "cancelBoth"
            // 'postOnly' => false,
            // 'disableMarketProtection' => false, // don't cancel if the next fill $price is 10% worse than the best fill $price
            // 'responseRequired' => true, // false is faster
        );
        if ($type === 'market') {
            $cost = null;
            if ($price !== null) {
                $cost = $amount * $price;
            } else {
                $cost = $this->safe_float_2($params, 'cost', 'amountQuote');
            }
            if ($cost !== null) {
                $precision = $market['precision']['price'];
                $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', 'amountQuote' ));
        } else if ($type === 'limit') {
            $request['price'] = $this->price_to_precision($symbol, $price);
            $request['amount'] = $this->amount_to_precision($symbol, $amount);
        }
        $response = $this->privatePostOrder (array_merge($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 edit_order($id, $symbol, $type, $side, $amount = null, $price = null, $params = array ()) {
        $this->load_markets();
        $market = $this->market($symbol);
        $request = array();
        $amountRemaining = $this->safe_float($params, 'amountRemaining');
        $params = $this->omit($params, 'amountRemaining');
        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);
        }
        $request = array_merge($request, $params);
        if ($request) {
            $request['orderId'] = $id;
            $request['market'] = $market['id'];
            $response = $this->privatePutOrder (array_merge($request, $params));
            return $this->parse_order($response, $market);
        } else {
            throw new ArgumentsRequired($this->id . ' editOrder() requires an $amount argument, or a $price argument, or non-empty params');
        }
    }

    public function cancel_order($id, $symbol = null, $params = array ()) {
        if ($symbol === null) {
            throw new ArgumentsRequired($this->id . ' cancelOrder() requires a $symbol argument');
        }
        $this->load_markets();
        $market = $this->market($symbol);
        $request = array(
            'orderId' => $id,
            'market' => $market['id'],
        );
        $response = $this->privateDeleteOrder (array_merge($request, $params));
        //
        //     {
        //         "orderId" => "2e7ce7fc-44e2-4d80-a4a7-d079c4750b61"
        //     }
        //
        return $this->parse_order($response, $market);
    }

    public function cancel_all_orders($symbol = null, $params = array ()) {
        $this->load_markets();
        $request = array();
        $market = null;
        if ($symbol !== null) {
            $market = $this->market($symbol);
            $request['market'] = $market['id'];
        }
        $response = $this->privateDeleteOrders (array_merge($request, $params));
        //
        //     array(
        //         {
        //             "orderId" => "1be6d0df-d5dc-4b53-a250-3376f3b393e6"
        //         }
        //     )
        //
        return $this->parse_orders($response, $market);
    }

    public function fetch_order($id, $symbol = null, $params = array ()) {
        if ($symbol === null) {
            throw new ArgumentsRequired($this->id . ' fetchOrder() requires a $symbol argument');
        }
        $this->load_markets();
        $this->load_markets();
        $market = $this->market($symbol);
        $request = array(
            'orderId' => $id,
            'market' => $market['id'],
        );
        $response = $this->privateGetOrder (array_merge($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($symbol = null, $since = null, $limit = null, $params = array ()) {
        if ($symbol === null) {
            throw new ArgumentsRequired($this->id . ' fetchOrders() requires a $symbol argument');
        }
        $this->load_markets();
        $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
        }
        $response = $this->privateGetOrders (array_merge($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 fetch_open_orders($symbol = null, $since = null, $limit = null, $params = array ()) {
        $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 (array_merge($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($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',
        );
        return $this->safe_string($statuses, $status, $status);
    }

    public function parse_order($order, $market = null) {
        //
        // 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');
        $symbol = $this->safe_symbol($marketId, $market, '-');
        $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_float($order, 'price');
        $amount = $this->safe_float($order, 'amount');
        $remaining = $this->safe_float($order, 'amountRemaining');
        $filled = $this->safe_float($order, 'filledAmount');
        $remainingCost = $this->safe_float($order, 'remainingCost');
        if (($remainingCost !== null) && ($remainingCost === 0.0)) {
            $remaining = 0;
        }
        if (($amount !== null) && ($remaining !== null)) {
            $filled = max (0, $amount - $remaining);
        }
        $cost = $this->safe_float($order, 'filledAmountQuote');
        $average = null;
        if ($cost !== null) {
            if ($filled) {
                $average = $cost / $filled;
            }
        }
        $fee = null;
        $feeCost = $this->safe_float($order, 'feePaid');
        if ($feeCost !== null) {
            $feeCurrencyId = $this->safe_string($order, 'feeCurrency');
            $feeCurrencyCode = $this->safe_currency_code($feeCurrencyId);
            $fee = array(
                'cost' => $feeCost,
                'currency' => $feeCurrencyCode,
            );
        }
        $lastTradeTimestamp = null;
        $rawTrades = $this->safe_value($order, 'fills');
        $trades = null;
        if ($rawTrades !== null) {
            $trades = $this->parse_trades($rawTrades, $market, null, null, array(
                'symbol' => $symbol,
                'order' => $id,
                'side' => $side,
            ));
            $numTrades = is_array($trades) ? count($trades) : 0;
            if ($numTrades > 0) {
                $lastTrade = $this->safe_value($trades, $numTrades - 1);
                $lastTradeTimestamp = $lastTrade['timestamp'];
            }
        }
        $timeInForce = $this->safe_string($order, 'timeInForce');
        $postOnly = $this->safe_value($order, 'postOnly');
        return array(
            'info' => $order,
            'id' => $id,
            'clientOrderId' => null,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'lastTradeTimestamp' => $lastTradeTimestamp,
            'symbol' => $symbol,
            'type' => $type,
            'timeInForce' => $timeInForce,
            'postOnly' => $postOnly,
            'side' => $side,
            'price' => $price,
            'stopPrice' => null,
            'amount' => $amount,
            'cost' => $cost,
            'average' => $average,
            'filled' => $filled,
            'remaining' => $remaining,
            'status' => $status,
            'fee' => $fee,
            'trades' => $trades,
        );
    }

    public function fetch_my_trades($symbol = null, $since = null, $limit = null, $params = array ()) {
        if ($symbol === null) {
            throw new ArgumentsRequired($this->id . ' fetchMyTrades() requires a $symbol argument');
        }
        $this->load_markets();
        $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
        }
        $response = $this->privateGetTrades (array_merge($request, $params));
        //
        //     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($code, $amount, $address, $tag = null, $params = array ()) {
        $this->check_address($address);
        $this->load_markets();
        $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;
        }
        $response = $this->privatePostWithdrawal (array_merge($request, $params));
        //
        //     {
        //         "success" => true,
        //         "symbol" => "BTC",
        //         "$amount" => "1.5"
        //     }
        //
        return $this->parse_transaction($response, $currency);
    }

    public function fetch_withdrawals($code = null, $since = null, $limit = null, $params = array ()) {
        $this->load_markets();
        $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
        }
        $response = $this->privateGetWithdrawalHistory (array_merge($request, $params));
        //
        //     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);
    }

    public function fetch_deposits($code = null, $since = null, $limit = null, $params = array ()) {
        $this->load_markets();
        $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
        }
        $response = $this->privateGetDepositHistory (array_merge($request, $params));
        //
        //     array(
        //         {
        //             "timestamp":1590492401000,
        //             "symbol":"ETH",
        //             "amount":"0.249825",
        //             "fee":"0",
        //             "status":"completed",
        //             "txId":"0x5167b473fd37811f9ef22364c3d54726a859ef9d98934b3a1e11d7baa8d2c2e2"
        //         }
        //     )
        //
        return $this->parse_transactions($response, $currency, $since, $limit);
    }

    public function parse_transaction_status($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($transaction, $currency = null) {
        //
        // 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_float($transaction, 'amount');
        $address = $this->safe_string($transaction, 'address');
        $txid = $this->safe_string($transaction, 'txId');
        $fee = null;
        $feeCost = $this->safe_float($transaction, 'fee');
        if ($feeCost !== null) {
            $fee = array(
                'cost' => $feeCost,
                'currency' => $code,
            );
        }
        $type = null;
        if (is_array($transaction) && array_key_exists('success', $transaction)) {
            $type = 'withdrawal';
        } else {
            $type = ($status === null) ? 'deposit' : 'withdrawal';
        }
        $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,
        );
    }

    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));
            $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($httpCode, $reason, $url, $method, $headers, $body, $response, $requestHeaders, $requestBody) {
        if ($response === null) {
            return; // 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
        }
    }
}
