# -*- coding: utf-8 -*-

# 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

from ccxt.base.exchange import Exchange
from ccxt.abstract.bitvavo import ImplicitAPI
import hashlib
from ccxt.base.types import Any, Balances, Currencies, Currency, DepositAddress, Int, Market, Num, Order, OrderBook, OrderSide, OrderType, Str, Strings, Ticker, Tickers, Trade, TradingFees, Transaction
from typing import List
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import AccountSuspended
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidAddress
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import OnMaintenance
from ccxt.base.decimal_to_precision import TRUNCATE
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class bitvavo(Exchange, ImplicitAPI):

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

    def fetch_time(self, params={}) -> Int:
        """
        fetches the current integer timestamp in milliseconds from the exchange server
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        """
        response = self.publicGetTime(params)
        #
        #     {"time": 1590379519148}
        #
        return self.safe_integer(response, 'time')

    def fetch_markets(self, params={}) -> List[Market]:
        """

        https://docs.bitvavo.com/#tag/General/paths/~1markets/get

        retrieves data on all markets for bitvavo
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = self.publicGetMarkets(params)
        #
        #    {
        #        "market": "BTC-EUR",
        #        "status": "trading",
        #        "base": "BTC",
        #        "quote": "EUR",
        #        "pricePrecision": "0",  # deprecated, self is mostly 0 across other markets too, which is abnormal, so we ignore self.
        #        "tickSize": "1.00",
        #        "minOrderInBaseAsset": "0.00006100",
        #        "minOrderInQuoteAsset": "5.00",
        #        "maxOrderInBaseAsset": "1000000000.00000000",
        #        "maxOrderInQuoteAsset": "1000000000.00",
        #        "quantityDecimals": "8",
        #        "notionalDecimals": "2",
        #        "maxOpenOrders": "100",
        #        "feeCategory": "A",
        #        "orderTypes": ["market", "limit", "stopLoss", "stopLossLimit", "takeProfit", "takeProfitLimit"]
        #    }
        #
        return self.parse_markets(response)

    def parse_markets(self, markets):
        result = []
        fees = self.fees
        for i in range(0, len(markets)):
            market = markets[i]
            id = self.safe_string(market, 'market')
            baseId = self.safe_string(market, 'base')
            quoteId = self.safe_string(market, 'quote')
            base = self.safe_currency_code(baseId)
            quote = self.safe_currency_code(quoteId)
            status = self.safe_string(market, 'status')
            result.append(self.safe_market_structure({
                'id': id,
                'symbol': base + '/' + quote,
                'base': base,
                'quote': quote,
                'settle': None,
                'baseId': baseId,
                'quoteId': quoteId,
                'settleId': None,
                'type': 'spot',
                'spot': True,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'active': (status == 'trading'),
                'contract': False,
                'linear': None,
                'inverse': None,
                'contractSize': None,
                'expiry': None,
                'expiryDatetime': None,
                'strike': None,
                'optionType': None,
                'taker': fees['trading']['taker'],
                'maker': fees['trading']['maker'],
                'precision': {
                    'amount': self.parse_number(self.parse_precision(self.safe_string(market, 'quantityDecimals'))),
                    'price': self.safe_number(market, 'tickSize'),
                    'cost': self.parse_number(self.parse_precision(self.safe_string(market, 'notionalDecimals'))),
                },
                'limits': {
                    'leverage': {
                        'min': None,
                        'max': None,
                    },
                    'amount': {
                        'min': self.safe_number(market, 'minOrderInBaseAsset'),
                        'max': self.safe_number(market, 'maxOrderInBaseAsset'),
                    },
                    'price': {
                        'min': None,
                        'max': None,
                    },
                    'cost': {
                        'min': self.safe_number(market, 'minOrderInQuoteAsset'),
                        'max': self.safe_number(market, 'maxOrderInQuoteAsset'),
                    },
                },
                'created': None,
                'info': market,
            }))
        return result

    def fetch_currencies(self, params={}) -> Currencies:
        """

        https://docs.bitvavo.com/#tag/General/paths/~1assets/get

        fetches all available currencies on an exchange
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        """
        response = self.publicGetAssets(params)
        #
        #     [
        #         {
        #             "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": [
        #               "ETH"
        #             ],
        #             "light": {
        #               "color": "#009393",
        #               "icon": {"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": {
        #               "color": "#009393",
        #               "icon": {"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 self.parse_currencies(response)

    def parse_currency(self, rawCurrency: dict) -> Currency:
        #
        #     [
        #         {
        #             "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": [
        #               "ETH"
        #             ],
        #             "light": {
        #               "color": "#009393",
        #               "icon": {"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": {
        #               "color": "#009393",
        #               "icon": {"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 = self.safe_list(self.options, 'fiatCurrencies', [])
        id = self.safe_string(rawCurrency, 'symbol')
        code = self.safe_currency_code(id)
        isFiat = self.in_array(code, fiatCurrencies)
        networks: dict = {}
        networksArray = self.safe_list(rawCurrency, 'networks', [])
        deposit = self.safe_string(rawCurrency, 'depositStatus') == 'OK'
        withdrawal = self.safe_string(rawCurrency, 'withdrawalStatus') == 'OK'
        active = deposit and withdrawal
        withdrawFee = self.safe_number(rawCurrency, 'withdrawalFee')
        precision = self.safe_string(rawCurrency, 'decimals', '8')
        minWithdraw = self.safe_number(rawCurrency, 'withdrawalMinAmount')
        # btw, absolutely all of them have 1 network atm
        for j in range(0, len(networksArray)):
            networkId = networksArray[j]
            networkCode = self.network_id_to_code(networkId)
            networks[networkCode] = {
                'info': rawCurrency,
                'id': networkId,
                'network': networkCode,
                'active': active,
                'deposit': deposit,
                'withdraw': withdrawal,
                'fee': withdrawFee,
                'precision': self.parse_number(self.parse_precision(precision)),
                'limits': {
                    'withdraw': {
                        'min': minWithdraw,
                        'max': None,
                    },
                },
            }
        return self.safe_currency_structure({
            'info': rawCurrency,
            'id': id,
            'code': code,
            'name': self.safe_string(rawCurrency, 'name'),
            'active': active,
            'deposit': deposit,
            'withdraw': withdrawal,
            'networks': networks,
            'fee': withdrawFee,
            'precision': None,
            'type': 'fiat' if isFiat else 'crypto',
            'limits': {
                'amount': {
                    'min': None,
                    'max': None,
                },
                'deposit': {
                    'min': None,
                    'max': None,
                },
                'withdraw': {
                    'min': minWithdraw,
                    'max': None,
                },
            },
        })

    def fetch_ticker(self, symbol: str, params={}) -> Ticker:
        """

        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 str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'market': market['id'],
        }
        response = self.publicGetTicker24h(self.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 self.parse_ticker(response, market)

    def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
        #
        # 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 = self.safe_string(ticker, 'market')
        symbol = self.safe_symbol(marketId, market, '-')
        timestamp = self.safe_integer(ticker, 'timestamp')
        last = self.safe_string(ticker, 'last')
        baseVolume = self.safe_string(ticker, 'volume')
        quoteVolume = self.safe_string(ticker, 'volumeQuote')
        open = self.safe_string(ticker, 'open')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': self.safe_string(ticker, 'high'),
            'low': self.safe_string(ticker, 'low'),
            'bid': self.safe_string(ticker, 'bid'),
            'bidVolume': self.safe_string(ticker, 'bidSize'),
            'ask': self.safe_string(ticker, 'ask'),
            'askVolume': self.safe_string(ticker, 'askSize'),
            'vwap': None,
            'open': open,
            'close': last,
            'last': last,
            'previousClose': None,  # previous day close
            'change': None,
            'percentage': None,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market)

    def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
        """
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/?id=ticker-structure>`
        """
        self.load_markets()
        response = self.publicGetTicker24h(params)
        #
        #     [
        #         {
        #             "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 self.parse_tickers(response, symbols)

    def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
        """

        https://docs.bitvavo.com/#tag/Market-Data/paths/~1{market}~1trades/get

        get the list of most recent trades for a particular symbol
        :param str 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 dict [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 self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/?id=public-trades>`
        """
        self.load_markets()
        market = self.market(symbol)
        paginate = False
        paginate, params = self.handle_option_and_params(params, 'fetchTrades', 'paginate')
        if paginate:
            return self.fetch_paginated_call_dynamic('fetchTrades', symbol, since, limit, params)
        request: dict = {
            'market': market['id'],
            # "limit": 500,  # default 500, max 1000
            # "start": since,
            # "end": self.milliseconds(),
            # "tradeIdFrom": "57b1159b-6bf5-4cde-9e2c-6bd6a5678baf",
            # "tradeIdTo": "57b1159b-6bf5-4cde-9e2c-6bd6a5678baf",
        }
        if limit is not None:
            request['limit'] = min(limit, 1000)
        if since is not None:
            request['start'] = since
        request, params = self.handle_until_option('end', request, params)
        response = self.publicGetMarketTrades(self.extend(request, params))
        #
        #     [
        #         {
        #             "id":"94154c98-6e8b-4e33-92a8-74e33fc05650",
        #             "timestamp":1590382761859,
        #             "amount":"0.06026079",
        #             "price":"8095.3",
        #             "side":"buy"
        #         }
        #     ]
        #
        return self.parse_trades(response, market, since, limit)

    def parse_trade(self, trade: dict, market: Market = None) -> Trade:
        #
        # 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 = self.safe_string(trade, 'price')
        amountString = self.safe_string(trade, 'amount')
        timestamp = self.safe_integer(trade, 'timestamp')
        side = self.safe_string(trade, 'side')
        id = self.safe_string_2(trade, 'id', 'fillId')
        marketId = self.safe_string(trade, 'market')
        symbol = self.safe_symbol(marketId, market, '-')
        taker = self.safe_value(trade, 'taker')
        takerOrMaker = None
        if taker is not None:
            takerOrMaker = 'taker' if taker else 'maker'
        feeCostString = self.safe_string(trade, 'fee')
        fee = None
        if feeCostString is not None:
            feeCurrencyId = self.safe_string(trade, 'feeCurrency')
            feeCurrencyCode = self.safe_currency_code(feeCurrencyId)
            fee = {
                'cost': feeCostString,
                'currency': feeCurrencyCode,
            }
        orderId = self.safe_string(trade, 'orderId')
        return self.safe_trade({
            'info': trade,
            'id': id,
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'order': orderId,
            'type': None,
            'side': side,
            'takerOrMaker': takerOrMaker,
            'price': priceString,
            'amount': amountString,
            'cost': None,
            'fee': fee,
        }, market)

    def fetch_trading_fees(self, params={}) -> TradingFees:
        """

        https://docs.bitvavo.com/#tag/Account/paths/~1account/get

        fetch the trading fees for multiple markets
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/?id=fee-structure>` indexed by market symbols
        """
        self.load_markets()
        response = self.privateGetAccount(params)
        #
        #     {
        #         "fees": {
        #           "taker": "0.0025",
        #           "maker": "0.0015",
        #           "volume": "10000.00"
        #         }
        #     }
        #
        return self.parse_trading_fees(response)

    def parse_trading_fees(self, fees, market=None):
        #
        #     {
        #         "fees": {
        #           "taker": "0.0025",
        #           "maker": "0.0015",
        #           "volume": "10000.00"
        #         }
        #     }
        #
        feesValue = self.safe_value(fees, 'fees')
        maker = self.safe_number(feesValue, 'maker')
        taker = self.safe_number(feesValue, 'taker')
        result: dict = {}
        for i in range(0, len(self.symbols)):
            symbol = self.symbols[i]
            result[symbol] = {
                'info': fees,
                'symbol': symbol,
                'maker': maker,
                'taker': taker,
                'percentage': True,
                'tierBased': True,
            }
        return result

    def fetch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
        """

        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 str 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 dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'market': market['id'],
        }
        if limit is not None:
            request['depth'] = limit
        response = self.publicGetMarketBook(self.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 = self.parse_order_book(response, market['symbol'])
        orderbook['nonce'] = self.safe_integer(response, 'nonce')
        return orderbook

    def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
        #
        #     [
        #         1590383700000,
        #         "8088.5",
        #         "8088.5",
        #         "8088.5",
        #         "8088.5",
        #         "0.04788623"
        #     ]
        #
        return [
            self.safe_integer(ohlcv, 0),
            self.safe_number(ohlcv, 1),
            self.safe_number(ohlcv, 2),
            self.safe_number(ohlcv, 3),
            self.safe_number(ohlcv, 4),
            self.safe_number(ohlcv, 5),
        ]

    def fetch_ohlcv_request(self, symbol: Str, timeframe='1m', since: Int = None, limit: Int = None, params={}):
        market = self.market(symbol)
        request: dict = {
            'market': market['id'],
            'interval': self.safe_string(self.timeframes, timeframe, timeframe),
            # "limit": 1440,  # default 1440, max 1440
            # "start": since,
            # "end": self.milliseconds(),
        }
        if since is not None:
            # https://github.com/ccxt/ccxt/issues/9227
            duration = self.parse_timeframe(timeframe)
            request['start'] = since
            if limit is None:
                limit = 1440
            else:
                limit = min(limit, 1440)
            request['end'] = self.sum(since, limit * duration * 1000)
        request, params = self.handle_until_option('end', request, params)
        if limit is not None:
            request['limit'] = limit  # default 1440, max 1440
        return self.extend(request, params)

    def fetch_ohlcv(self, symbol: Str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
        """

        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 str symbol: unified symbol of the market to fetch OHLCV data for
        :param str 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 dict [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 self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        self.load_markets()
        market = self.market(symbol)
        paginate = False
        paginate, params = self.handle_option_and_params(params, 'fetchOHLCV', 'paginate')
        if paginate:
            return self.fetch_paginated_call_deterministic('fetchOHLCV', symbol, since, limit, timeframe, params, 1440)
        request = self.fetch_ohlcv_request(symbol, timeframe, since, limit, params)
        response = self.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 self.parse_ohlcvs(response, market, timeframe, since, limit)

    def parse_balance(self, response) -> Balances:
        result: dict = {
            'info': response,
            'timestamp': None,
            'datetime': None,
        }
        for i in range(0, len(response)):
            balance = response[i]
            currencyId = self.safe_string(balance, 'symbol')
            code = self.safe_currency_code(currencyId)
            account = self.account()
            account['free'] = self.safe_string(balance, 'available')
            account['used'] = self.safe_string(balance, 'inOrder')
            result[code] = account
        return self.safe_balance(result)

    def fetch_balance(self, params={}) -> Balances:
        """

        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 dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/?id=balance-structure>`
        """
        self.load_markets()
        response = self.privateGetBalance(params)
        #
        #     [
        #         {
        #             "symbol": "BTC",
        #             "available": "1.57593193",
        #             "inOrder": "0.74832374"
        #         }
        #     ]
        #
        return self.parse_balance(response)

    def fetch_deposit_address(self, code: str, params={}) -> DepositAddress:
        """
        fetch the deposit address for a currency associated with self account
        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/?id=address-structure>`
        """
        self.load_markets()
        currency = self.currency(code)
        request: dict = {
            'symbol': currency['id'],
        }
        response = self.privateGetDeposit(self.extend(request, params))
        #
        #     {
        #         "address": "0x449889e3234514c45d57f7c5a571feba0c7ad567",
        #         "paymentId": "10002653"
        #     }
        #
        address = self.safe_string(response, 'address')
        tag = self.safe_string(response, 'paymentId')
        self.check_address(address)
        return {
            'info': response,
            'currency': code,
            'network': None,
            'address': address,
            'tag': tag,
        }

    def create_order_request(self, symbol: Str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
        market = self.market(symbol)
        request: dict = {
            'market': market['id'],
            'side': side,
            'orderType': type,
        }
        isMarketOrder = (type == 'market') or (type == 'stopLoss') or (type == 'takeProfit')
        isLimitOrder = (type == 'limit') or (type == 'stopLossLimit') or (type == 'takeProfitLimit')
        timeInForce = self.safe_string(params, 'timeInForce')
        triggerPrice = self.safe_string_n(params, ['triggerPrice', 'stopPrice', 'triggerAmount'])
        postOnly = self.is_post_only(isMarketOrder, False, params)
        stopLossPrice = self.safe_value(params, 'stopLossPrice')  # trigger when price crosses from above to below self value
        takeProfitPrice = self.safe_value(params, 'takeProfitPrice')  # trigger when price crosses from below to above self value
        params = self.omit(params, ['timeInForce', 'triggerPrice', 'stopPrice', 'stopLossPrice', 'takeProfitPrice'])
        if isMarketOrder:
            cost = None
            if price is not None:
                priceString = self.number_to_string(price)
                amountString = self.number_to_string(amount)
                quoteAmount = Precise.string_mul(amountString, priceString)
                cost = self.parse_number(quoteAmount)
            else:
                cost = self.safe_number(params, 'cost')
            if cost is not None:
                precision = self.currency(market['quote'])['precision']
                request['amountQuote'] = self.decimal_to_precision(cost, TRUNCATE, precision, self.precisionMode)
            else:
                request['amount'] = self.amount_to_precision(symbol, amount)
            params = self.omit(params, ['cost'])
        elif isLimitOrder:
            request['price'] = self.price_to_precision(symbol, price)
            request['amount'] = self.amount_to_precision(symbol, amount)
        isTakeProfit = (takeProfitPrice is not None) or (type == 'takeProfit') or (type == 'takeProfitLimit')
        isStopLoss = (stopLossPrice is not None) or (triggerPrice is not None) and (not isTakeProfit) or (type == 'stopLoss') or (type == 'stopLossLimit')
        if isStopLoss:
            if stopLossPrice is not None:
                triggerPrice = stopLossPrice
            request['orderType'] = 'stopLoss' if isMarketOrder else 'stopLossLimit'
        elif isTakeProfit:
            if takeProfitPrice is not None:
                triggerPrice = takeProfitPrice
            request['orderType'] = 'takeProfit' if isMarketOrder else 'takeProfitLimit'
        if triggerPrice is not None:
            request['triggerAmount'] = self.price_to_precision(symbol, triggerPrice)
            request['triggerType'] = 'price'
            request['triggerReference'] = 'lastTrade'  # 'bestBid', 'bestAsk', 'midPrice'
        if (timeInForce is not None) and (timeInForce != 'PO'):
            request['timeInForce'] = timeInForce
        if postOnly:
            request['postOnly'] = True
        operatorId = None
        operatorId, params = self.handle_option_and_params(params, 'createOrder', 'operatorId')
        if operatorId is not None:
            request['operatorId'] = self.parse_to_int(operatorId)
        else:
            raise ArgumentsRequired(self.id + ' createOrder() requires an operatorId in params or options, eg: exchange.options[\'operatorId\'] = 1234567890')
        selfTradePrevention = None
        selfTradePrevention, params = self.handle_option_and_params(params, 'createOrder', 'selfTradePrevention')
        if selfTradePrevention is not None:
            if selfTradePrevention == 'EXPIRE_BOTH':
                request['selfTradePrevention'] = 'cancelBoth'
            else:
                request['selfTradePrevention'] = selfTradePrevention
        return self.extend(request, params)

    def create_order(self, symbol: Str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
        """
        create a trade order

        https://docs.bitvavo.com/#tag/Trading-endpoints/paths/~1order/post

        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str 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 dict [params]: extra parameters specific to the bitvavo api endpoint
        :param str [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 str [params.triggerType]: "price"
        :param str [params.triggerReference]: "lastTrade", "bestBid", "bestAsk", "midPrice" Only for stop orders: Use self to determine which parameter will trigger the order
        :param str [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 self to 'false' when only an acknowledgement of success or failure is required, self is faster.
        :returns dict: an `order structure <https://docs.ccxt.com/?id=order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = self.create_order_request(symbol, type, side, amount, price, params)
        response = self.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":[ # 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 self.parse_order(response, market)

    def edit_order_request(self, id: str, symbol, type, side, amount=None, price=None, params={}):
        request: dict = {}
        market = self.market(symbol)
        amountRemaining = self.safe_number(params, 'amountRemaining')
        triggerPrice = self.safe_string_n(params, ['triggerPrice', 'stopPrice', 'triggerAmount'])
        params = self.omit(params, ['amountRemaining', 'triggerPrice', 'stopPrice', 'triggerAmount'])
        if price is not None:
            request['price'] = self.price_to_precision(symbol, price)
        if amount is not None:
            request['amount'] = self.amount_to_precision(symbol, amount)
        if amountRemaining is not None:
            request['amountRemaining'] = self.amount_to_precision(symbol, amountRemaining)
        if triggerPrice is not None:
            request['triggerAmount'] = self.price_to_precision(symbol, triggerPrice)
        request = self.extend(request, params)
        if self.is_empty(request):
            raise ArgumentsRequired(self.id + ' editOrder() requires an amount argument, or a price argument, or non-empty params')
        clientOrderId = self.safe_string(params, 'clientOrderId')
        if clientOrderId is None:
            request['orderId'] = id
        operatorId = None
        operatorId, params = self.handle_option_and_params(params, 'editOrder', 'operatorId')
        if operatorId is not None:
            request['operatorId'] = self.parse_to_int(operatorId)
        else:
            raise ArgumentsRequired(self.id + ' editOrder() requires an operatorId in params or options, eg: exchange.options[\'operatorId\'] = 1234567890')
        request['market'] = market['id']
        return request

    def edit_order(self, id: str, symbol: str, type: OrderType, side: OrderSide, amount: Num = None, price: Num = None, params={}):
        """
        edit a trade order

        https://docs.bitvavo.com/#tag/Orders/paths/~1order/put

        :param str id: cancel order id
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str 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 dict [params]: extra parameters specific to the bitvavo api endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/?id=order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = self.edit_order_request(id, symbol, type, side, amount, price, params)
        response = self.privatePutOrder(request)
        return self.parse_order(response, market)

    def cancel_order_request(self, id: Str, symbol: Str = None, params={}):
        if symbol is None:
            raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
        market = self.market(symbol)
        request: dict = {
            'market': market['id'],
        }
        clientOrderId = self.safe_string(params, 'clientOrderId')
        if clientOrderId is None:
            request['orderId'] = id
        operatorId = None
        operatorId, params = self.handle_option_and_params(params, 'cancelOrder', 'operatorId')
        if operatorId is not None:
            request['operatorId'] = self.parse_to_int(operatorId)
        else:
            raise ArgumentsRequired(self.id + ' cancelOrder() requires an operatorId in params or options, eg: exchange.options[\'operatorId\'] = 1234567890')
        return self.extend(request, params)

    def cancel_order(self, id: str, symbol: Str = None, params={}):
        """

        https://docs.bitvavo.com/#tag/Orders/paths/~1order/delete

        cancels an open order

        https://docs.bitvavo.com/#tag/Trading-endpoints/paths/~1order/delete

        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/?id=order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = self.cancel_order_request(id, symbol, params)
        response = self.privateDeleteOrder(request)
        #
        #     {
        #         "orderId": "2e7ce7fc-44e2-4d80-a4a7-d079c4750b61"
        #     }
        #
        return self.parse_order(response, market)

    def cancel_all_orders(self, symbol: Str = None, params={}):
        """

        https://docs.bitvavo.com/#tag/Orders/paths/~1orders/delete

        cancel all open orders
        :param str symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        """
        self.load_markets()
        request: dict = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['market'] = market['id']
        operatorId = None
        operatorId, params = self.handle_option_and_params(params, 'cancelAllOrders', 'operatorId')
        if operatorId is not None:
            request['operatorId'] = self.parse_to_int(operatorId)
        else:
            raise ArgumentsRequired(self.id + ' canceAllOrders() requires an operatorId in params or options, eg: exchange.options[\'operatorId\'] = 1234567890')
        response = self.privateDeleteOrders(self.extend(request, params))
        #
        #     [
        #         {
        #             "orderId": "1be6d0df-d5dc-4b53-a250-3376f3b393e6"
        #         }
        #     ]
        #
        return self.parse_orders(response, market)

    def fetch_order(self, id: str, symbol: Str = None, params={}):
        """
        fetches information on an order made by the user

        https://docs.bitvavo.com/#tag/Trading-endpoints/paths/~1order/get

        :param str id: the order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/?id=order-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchOrder() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'market': market['id'],
        }
        clientOrderId = self.safe_string(params, 'clientOrderId')
        if clientOrderId is None:
            request['orderId'] = id
        response = self.privateGetOrder(self.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":[
        #             {
        #                 "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 self.parse_order(response, market)

    def fetch_orders_request(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        market = self.market(symbol)
        request: dict = {
            'market': market['id'],
            # "limit": 500,
            # "start": since,
            # "end": self.milliseconds(),
            # "orderIdFrom": "af76d6ce-9f7c-4006-b715-bb5d430652d0",
            # "orderIdTo": "af76d6ce-9f7c-4006-b715-bb5d430652d0",
        }
        if since is not None:
            request['start'] = since
        if limit is not None:
            request['limit'] = limit  # default 500, max 1000
        request, params = self.handle_until_option('end', request, params)
        return self.extend(request, params)

    def fetch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """

        https://docs.bitvavo.com/#tag/Trading-endpoints/paths/~1orders/get

        fetches information on multiple orders made by the user
        :param str 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 dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self 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
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchOrders() requires a symbol argument')
        self.load_markets()
        paginate = False
        paginate, params = self.handle_option_and_params(params, 'fetchOrders', 'paginate')
        if paginate:
            return self.fetch_paginated_call_dynamic('fetchOrders', symbol, since, limit, params)
        market = self.market(symbol)
        request = self.fetch_orders_request(symbol, since, limit, params)
        response = self.privateGetOrders(request)
        #
        #     [
        #         {
        #             "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":[
        #                 {
        #                     "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 self.parse_orders(response, market, since, limit)

    def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """

        https://docs.bitvavo.com/#tag/Trading-endpoints/paths/~1ordersOpen/get

        fetch all unfilled currently open orders
        :param str 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 dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        """
        self.load_markets()
        request: dict = {
            # "market": market["id"],  # rate limit 25 without a market, 1 with market specified
        }
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['market'] = market['id']
        response = self.privateGetOrdersOpen(self.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":[
        #                 {
        #                     "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 self.parse_orders(response, market, since, limit)

    def parse_order_status(self, status: Str):
        statuses: dict = {
            '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 self.safe_string(statuses, status, status)

    def parse_order(self, order: dict, market: Market = None) -> Order:
        #
        # 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":[
        #             {
        #                 "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 = self.safe_string(order, 'orderId')
        timestamp = self.safe_integer(order, 'created')
        marketId = self.safe_string(order, 'market')
        market = self.safe_market(marketId, market, '-')
        symbol = market['symbol']
        status = self.parse_order_status(self.safe_string(order, 'status'))
        side = self.safe_string(order, 'side')
        type = self.safe_string(order, 'orderType')
        price = self.safe_string(order, 'price')
        amount = self.safe_string(order, 'amount')
        remaining = self.safe_string(order, 'amountRemaining')
        filled = self.safe_string(order, 'filledAmount')
        cost = self.safe_string(order, 'filledAmountQuote')
        if cost is None:
            amountQuote = self.safe_string(order, 'amountQuote')
            amountQuoteRemaining = self.safe_string(order, 'amountQuoteRemaining')
            cost = Precise.string_sub(amountQuote, amountQuoteRemaining)
        fee = None
        feeCost = self.safe_number(order, 'feePaid')
        if feeCost is not None:
            feeCurrencyId = self.safe_string(order, 'feeCurrency')
            feeCurrencyCode = self.safe_currency_code(feeCurrencyId)
            fee = {
                'cost': feeCost,
                'currency': feeCurrencyCode,
            }
        rawTrades = self.safe_value(order, 'fills', [])
        timeInForce = self.safe_string(order, 'timeInForce')
        postOnly = self.safe_value(order, 'postOnly')
        # https://github.com/ccxt/ccxt/issues/8489
        return self.safe_order({
            'info': order,
            'id': id,
            'clientOrderId': None,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'symbol': symbol,
            'type': type,
            'timeInForce': timeInForce,
            'postOnly': postOnly,
            'side': side,
            'price': price,
            'triggerPrice': self.safe_number(order, 'triggerPrice'),
            'amount': amount,
            'cost': cost,
            'average': None,
            'filled': filled,
            'remaining': remaining,
            'status': status,
            'fee': fee,
            'trades': rawTrades,
        }, market)

    def fetch_my_trades_request(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        market = self.market(symbol)
        request: dict = {
            'market': market['id'],
            # "limit": 500,
            # "start": since,
            # "end": self.milliseconds(),
            # "tradeIdFrom": "af76d6ce-9f7c-4006-b715-bb5d430652d0",
            # "tradeIdTo": "af76d6ce-9f7c-4006-b715-bb5d430652d0",
        }
        if since is not None:
            request['start'] = since
        if limit is not None:
            request['limit'] = limit  # default 500, max 1000
        request, params = self.handle_until_option('end', request, params)
        return self.extend(request, params)

    def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
        """

        https://docs.bitvavo.com/#tag/Trading-endpoints/paths/~1trades/get

        fetch all trades made by the user
        :param str 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 dict [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 self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchMyTrades() requires a symbol argument')
        self.load_markets()
        paginate = False
        paginate, params = self.handle_option_and_params(params, 'fetchMyTrades', 'paginate')
        if paginate:
            return self.fetch_paginated_call_dynamic('fetchMyTrades', symbol, since, limit, params)
        market = self.market(symbol)
        request = self.fetch_my_trades_request(symbol, since, limit, params)
        response = self.privateGetTrades(request)
        #
        #     [
        #         {
        #             "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 self.parse_trades(response, market, since, limit)

    def withdraw_request(self, code: Str, amount, address, tag=None, params={}):
        currency = self.currency(code)
        request: dict = {
            'symbol': currency['id'],
            'amount': self.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 is not None:
            request['paymentId'] = tag
        return self.extend(request, params)

    def withdraw(self, code: str, amount: float, address: str, tag: Str = None, params={}) -> Transaction:
        """
        make a withdrawal
        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/?id=transaction-structure>`
        """
        tag, params = self.handle_withdraw_tag_and_params(tag, params)
        self.check_address(address)
        self.load_markets()
        currency = self.currency(code)
        request = self.withdraw_request(code, amount, address, tag, params)
        response = self.privatePostWithdrawal(request)
        #
        #     {
        #         "success": True,
        #         "symbol": "BTC",
        #         "amount": "1.5"
        #     }
        #
        return self.parse_transaction(response, currency)

    def fetch_withdrawals_request(self, code: Str = None, since: Int = None, limit: Int = None, params={}):
        request: dict = {
            # 'symbol': currency['id'],
            # 'limit': 500,  # default 500, max 1000
            # 'start': since,
            # 'end': self.milliseconds(),
        }
        currency = None
        if code is not None:
            currency = self.currency(code)
            request['symbol'] = currency['id']
        if since is not None:
            request['start'] = since
        if limit is not None:
            request['limit'] = limit  # default 500, max 1000
        return self.extend(request, params)

    def fetch_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
        """

        https://docs.bitvavo.com/#tag/Account/paths/~1withdrawalHistory/get

        fetch all withdrawals made from an account
        :param str 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 dict [params]: extra parameters specific to the bitvavo api endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/?id=transaction-structure>`
        """
        self.load_markets()
        request = self.fetch_withdrawals_request(code, since, limit, params)
        currency = None
        if code is not None:
            currency = self.currency(code)
        response = self.privateGetWithdrawalHistory(request)
        #
        #     [
        #         {
        #             "timestamp":1590531212000,
        #             "symbol":"ETH",
        #             "amount":"0.091",
        #             "fee":"0.009",
        #             "status":"awaiting_bitvavo_inspection",
        #             "address":"0xe42b309f1eE9F0cbf7f54CcF3bc2159eBfA6735b",
        #             "paymentId": "10002653",
        #             "txId": "927b3ea50c5bb52c6854152d305dfa1e27fc01d10464cf10825d96d69d235eb3",
        #         }
        #     ]
        #
        return self.parse_transactions(response, currency, since, limit, {'type': 'withdrawal'})

    def fetch_deposits_request(self, code: Str = None, since: Int = None, limit: Int = None, params={}):
        request: dict = {
            # 'symbol': currency['id'],
            # 'limit': 500,  # default 500, max 1000
            # 'start': since,
            # 'end': self.milliseconds(),
        }
        currency = None
        if code is not None:
            currency = self.currency(code)
            request['symbol'] = currency['id']
        if since is not None:
            request['start'] = since
        if limit is not None:
            request['limit'] = limit  # default 500, max 1000
        return self.extend(request, params)

    def fetch_deposits(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
        """

        https://docs.bitvavo.com/#tag/Account/paths/~1depositHistory/get

        fetch all deposits made to an account
        :param str 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 dict [params]: extra parameters specific to the bitvavo api endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/?id=transaction-structure>`
        """
        self.load_markets()
        request = self.fetch_deposits_request(code, since, limit, params)
        currency = None
        if code is not None:
            currency = self.currency(code)
        response = self.privateGetDepositHistory(request)
        #
        #     [
        #         {
        #             "timestamp":1590492401000,
        #             "symbol":"ETH",
        #             "amount":"0.249825",
        #             "fee":"0",
        #             "status":"completed",
        #             "txId":"0x5167b473fd37811f9ef22364c3d54726a859ef9d98934b3a1e11d7baa8d2c2e2"
        #         }
        #     ]
        #
        return self.parse_transactions(response, currency, since, limit, {'type': 'deposit'})

    def parse_transaction_status(self, status: Str):
        statuses: dict = {
            '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 self.safe_string(statuses, status, status)

    def parse_transaction(self, transaction: dict, currency: Currency = None) -> Transaction:
        #
        # 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 = None
        timestamp = self.safe_integer(transaction, 'timestamp')
        currencyId = self.safe_string(transaction, 'symbol')
        code = self.safe_currency_code(currencyId, currency)
        status = self.parse_transaction_status(self.safe_string(transaction, 'status'))
        amount = self.safe_number(transaction, 'amount')
        address = self.safe_string(transaction, 'address')
        txid = self.safe_string(transaction, 'txId')
        fee = None
        feeCost = self.safe_number(transaction, 'fee')
        if feeCost is not None:
            fee = {
                'cost': feeCost,
                'currency': code,
            }
        type = None
        if ('success' in transaction) or ('address' in transaction):
            type = 'withdrawal'
        else:
            type = 'deposit'
        tag = self.safe_string(transaction, 'paymentId')
        return {
            'info': transaction,
            'id': id,
            'txid': txid,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'addressFrom': None,
            'address': address,
            'addressTo': address,
            'tagFrom': None,
            'tag': tag,
            'tagTo': tag,
            'type': type,
            'amount': amount,
            'currency': code,
            'status': status,
            'updated': None,
            'fee': fee,
            'network': None,
            'comment': None,
            'internal': None,
        }

    def parse_deposit_withdraw_fee(self, fee, currency: Currency = None):
        #
        #   {
        #       "symbol": "1INCH",
        #       "name": "1inch",
        #       "decimals": 8,
        #       "depositFee": "0",
        #       "depositConfirmations": 64,
        #       "depositStatus": "OK",
        #       "withdrawalFee": "6.1",
        #       "withdrawalMinAmount": "6.1",
        #       "withdrawalStatus": "OK",
        #       "networks": [
        #         "ETH"
        #       ],
        #       "message": ""
        #   }
        #
        result: dict = {
            'info': fee,
            'withdraw': {
                'fee': self.safe_number(fee, 'withdrawalFee'),
                'percentage': False,
            },
            'deposit': {
                'fee': self.safe_number(fee, 'depositFee'),
                'percentage': False,
            },
            'networks': {},
        }
        networks = self.safe_value(fee, 'networks')
        networkId = self.safe_value(networks, 0)  # Bitvavo currently only supports one network per currency
        currencyCode = self.safe_string(currency, 'code')
        if networkId == 'Mainnet':
            networkId = currencyCode
        networkCode = self.network_id_to_code(networkId, currencyCode)
        result['networks'][networkCode] = {
            'deposit': result['deposit'],
            'withdraw': result['withdraw'],
        }
        return result

    def fetch_deposit_withdraw_fees(self, codes: Strings = None, params={}):
        """
        fetch deposit and withdraw fees

        https://docs.bitvavo.com/#tag/General/paths/~1assets/get

        :param str[]|None codes: list of unified currency codes
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `fee structures <https://docs.ccxt.com/?id=fee-structure>`
        """
        self.load_markets()
        response = self.publicGetAssets(params)
        #
        #   [
        #       {
        #           "symbol": "1INCH",
        #           "name": "1inch",
        #           "decimals": 8,
        #           "depositFee": "0",
        #           "depositConfirmations": 64,
        #           "depositStatus": "OK",
        #           "withdrawalFee": "6.1",
        #           "withdrawalMinAmount": "6.1",
        #           "withdrawalStatus": "OK",
        #           "networks": [
        #             "ETH"
        #           ],
        #           "message": ""
        #       },
        #   ]
        #
        return self.parse_deposit_withdraw_fees(response, codes, 'symbol')

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        query = self.omit(params, self.extract_params(path))
        url = '/' + self.version + '/' + self.implode_params(path, params)
        getOrDelete = (method == 'GET') or (method == 'DELETE')
        if getOrDelete:
            if query:
                url += '?' + self.urlencode(query)
        if api == 'private':
            self.check_required_credentials()
            payload = ''
            if not getOrDelete:
                if query:
                    body = self.json(query)
                    payload = body
            timestamp = str(self.milliseconds())
            auth = timestamp + method + url + payload
            signature = self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha256)
            accessWindow = self.safe_string(self.options, 'BITVAVO-ACCESS-WINDOW', '10000')
            headers = {
                'BITVAVO-ACCESS-KEY': self.apiKey,
                'BITVAVO-ACCESS-SIGNATURE': signature,
                'BITVAVO-ACCESS-TIMESTAMP': timestamp,
                'BITVAVO-ACCESS-WINDOW': accessWindow,
            }
            if not getOrDelete:
                headers['Content-Type'] = 'application/json'
        url = self.urls['api'][api] + url
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, httpCode: int, reason: str, url: str, method: str, headers: dict, body: str, response, requestHeaders, requestBody):
        if response is None:
            return None  # fallback to default error handler
        #
        #     {"errorCode":308,"error":"The signature length is invalid(HMAC-SHA256 should return a 64 length hexadecimal string)."}
        #     {"errorCode":203,"error":"symbol parameter is required."}
        #     {"errorCode":205,"error":"symbol parameter is invalid."}
        #
        errorCode = self.safe_string(response, 'errorCode')
        error = self.safe_string(response, 'error')
        if errorCode is not None:
            feedback = self.id + ' ' + body
            self.throw_broadly_matched_exception(self.exceptions['broad'], error, feedback)
            self.throw_exactly_matched_exception(self.exceptions['exact'], errorCode, feedback)
            raise ExchangeError(feedback)  # unknown message
        return None

    def calculate_rate_limiter_cost(self, api, method, path, params, config={}):
        if ('noMarket' in config) and not ('market' in params):
            return config['noMarket']
        return self.safe_value(config, 'cost', 1)
