# -*- 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.async_support.base.exchange import Exchange
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 ROUND
from ccxt.base.decimal_to_precision import TRUNCATE
from ccxt.base.decimal_to_precision import DECIMAL_PLACES
from ccxt.base.decimal_to_precision import SIGNIFICANT_DIGITS
from ccxt.base.precise import Precise


class bitvavo(Exchange):

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

    def currency_to_precision(self, currency, fee):
        return self.decimal_to_precision(fee, 0, self.currencies[currency]['precision'])

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

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

    async def fetch_time(self, params={}):
        response = await self.publicGetTime(params)
        #
        #     {"time": 1590379519148}
        #
        return self.safe_integer(response, 'time')

    async def fetch_markets(self, params={}):
        response = await self.publicGetMarkets(params)
        currencies = await self.fetch_currencies_from_cache(params)
        currenciesById = self.index_by(currencies, 'symbol')
        #
        #     [
        #         {
        #             "market":"ADA-BTC",
        #             "status":"trading",  # "trading" "halted" "auction"
        #             "base":"ADA",
        #             "quote":"BTC",
        #             "pricePrecision":5,
        #             "minOrderInBaseAsset":"100",
        #             "minOrderInQuoteAsset":"0.001",
        #             "orderTypes": ["market", "limit"]
        #         }
        #     ]
        #
        result = []
        for i in range(0, len(response)):
            market = response[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)
            symbol = base + '/' + quote
            status = self.safe_string(market, 'status')
            active = (status == 'trading')
            baseCurrency = self.safe_value(currenciesById, baseId)
            amountPrecision = None
            if baseCurrency is not None:
                amountPrecision = self.safe_integer(baseCurrency, 'decimals', 8)
            precision = {
                'price': self.safe_integer(market, 'pricePrecision'),
                'amount': amountPrecision,
            }
            result.append({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'info': market,
                'active': active,
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': self.safe_number(market, 'minOrderInBaseAsset'),
                        'max': None,
                    },
                    'price': {
                        'min': None,
                        'max': None,
                    },
                    'cost': {
                        'min': self.safe_number(market, 'minOrderInQuoteAsset'),
                        'max': None,
                    },
                },
            })
        return result

    async def fetch_currencies_from_cache(self, params={}):
        # self method is now redundant
        # currencies are now fetched before markets
        options = self.safe_value(self.options, 'fetchCurrencies', {})
        timestamp = self.safe_integer(options, 'timestamp')
        expires = self.safe_integer(options, 'expires', 1000)
        now = self.milliseconds()
        if (timestamp is None) or ((now - timestamp) > expires):
            response = await self.publicGetAssets(params)
            self.options['fetchCurrencies'] = self.extend(options, {
                'response': response,
                'timestamp': now,
            })
        return self.safe_value(self.options['fetchCurrencies'], 'response')

    async def fetch_currencies(self, params={}):
        response = await self.fetch_currencies_from_cache(params)
        #
        #     [
        #         {
        #             "symbol":"ADA",
        #             "name":"Cardano",
        #             "decimals":6,
        #             "depositFee":"0",
        #             "depositConfirmations":15,
        #             "depositStatus":"OK",  # "OK", "MAINTENANCE", "DELISTED"
        #             "withdrawalFee":"0.2",
        #             "withdrawalMinAmount":"0.2",
        #             "withdrawalStatus":"OK",  # "OK", "MAINTENANCE", "DELISTED"
        #             "networks": ["Mainnet"],  # "ETH", "NEO", "ONT", "SEPA", "VET"
        #             "message":"",
        #         },
        #     ]
        #
        result = {}
        for i in range(0, len(response)):
            currency = response[i]
            id = self.safe_string(currency, 'symbol')
            code = self.safe_currency_code(id)
            depositStatus = self.safe_value(currency, 'depositStatus')
            deposit = (depositStatus == 'OK')
            withdrawalStatus = self.safe_value(currency, 'withdrawalStatus')
            withdrawal = (withdrawalStatus == 'OK')
            active = deposit and withdrawal
            name = self.safe_string(currency, 'name')
            precision = self.safe_integer(currency, 'decimals', 8)
            result[code] = {
                'id': id,
                'info': currency,
                'code': code,
                'name': name,
                'active': active,
                'fee': self.safe_number(currency, 'withdrawalFee'),
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': None,
                        'max': None,
                    },
                    'withdraw': {
                        'min': self.safe_number(currency, 'withdrawalMinAmount'),
                        'max': None,
                    },
                },
            }
        return result

    async def fetch_ticker(self, symbol, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'market': market['id'],
        }
        response = await self.publicGetTicker24h(self.extend(request, params))
        #
        #     {
        #         "market":"ETH-BTC",
        #         "open":"0.022578",
        #         "high":"0.023019",
        #         "low":"0.022573",
        #         "last":"0.023019",
        #         "volume":"25.16366324",
        #         "volumeQuote":"0.57333305",
        #         "bid":"0.023039",
        #         "bidSize":"0.53500578",
        #         "ask":"0.023041",
        #         "askSize":"0.47859202",
        #         "timestamp":1590381666900
        #     }
        #
        return self.parse_ticker(response, market)

    def parse_ticker(self, ticker, market=None):
        #
        # 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_number(ticker, 'last')
        baseVolume = self.safe_number(ticker, 'volume')
        quoteVolume = self.safe_number(ticker, 'volumeQuote')
        vwap = self.vwap(baseVolume, quoteVolume)
        change = None
        percentage = None
        average = None
        open = self.safe_number(ticker, 'open')
        if (open is not None) and (last is not None):
            change = last - open
            if open > 0:
                percentage = change / open * 100
            average = self.sum(open, last) / 2
        result = {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': self.safe_number(ticker, 'high'),
            'low': self.safe_number(ticker, 'low'),
            'bid': self.safe_number(ticker, 'bid'),
            'bidVolume': self.safe_number(ticker, 'bidSize'),
            'ask': self.safe_number(ticker, 'ask'),
            'askVolume': self.safe_number(ticker, 'askSize'),
            'vwap': vwap,
            'open': open,
            'close': last,
            'last': last,
            'previousClose': None,  # previous day close
            'change': change,
            'percentage': percentage,
            'average': average,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }
        return result

    async def fetch_tickers(self, symbols=None, params={}):
        await self.load_markets()
        response = await 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)

    async def fetch_trades(self, symbol, since=None, limit=None, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            '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'] = limit
        if since is not None:
            request['start'] = since
        response = await 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, market=None):
        #
        # 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')
        price = self.parse_number(priceString)
        amount = self.parse_number(amountString)
        cost = self.parse_number(Precise.string_mul(priceString, amountString))
        timestamp = self.safe_integer(trade, 'timestamp')
        side = self.safe_string(trade, 'side')
        id = self.safe_string_2(trade, 'id', 'fillId')
        marketId = self.safe_integer(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'
        feeCost = self.safe_number(trade, 'fee')
        fee = None
        if feeCost is not None:
            feeCurrencyId = self.safe_string(trade, 'feeCurrency')
            feeCurrencyCode = self.safe_currency_code(feeCurrencyId)
            fee = {
                'cost': feeCost,
                'currency': feeCurrencyCode,
            }
        orderId = self.safe_string(trade, 'orderId')
        return {
            'info': trade,
            'id': id,
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'order': orderId,
            'type': None,
            'side': side,
            'takerOrMaker': takerOrMaker,
            'price': price,
            'amount': amount,
            'cost': cost,
            'fee': fee,
        }

    async def fetch_order_book(self, symbol, limit=None, params={}):
        await self.load_markets()
        request = {
            'market': self.market_id(symbol),
        }
        if limit is not None:
            request['depth'] = limit
        response = await 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, symbol)
        orderbook['nonce'] = self.safe_integer(response, 'nonce')
        return orderbook

    def parse_ohlcv(self, ohlcv, market=None):
        #
        #     [
        #         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),
        ]

    async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'market': market['id'],
            'interval': self.timeframes[timeframe],
            # 'limit': 1440,  # default 1440, max 1440
            # 'start': since,
            # 'end': self.milliseconds(),
        }
        if since is not None:
            request['start'] = since
        if limit is not None:
            request['limit'] = limit  # default 1440, max 1440
        response = await self.publicGetMarketCandles(self.extend(request, params))
        #
        #     [
        #         [1590383700000,"8088.5","8088.5","8088.5","8088.5","0.04788623"],
        #         [1590383580000,"8091.3","8091.5","8091.3","8091.5","0.04931221"],
        #         [1590383520000,"8090.3","8092.7","8090.3","8092.5","0.04001286"],
        #     ]
        #
        return self.parse_ohlcvs(response, market, timeframe, since, limit)

    async def fetch_balance(self, params={}):
        await self.load_markets()
        response = await self.privateGetBalance(params)
        #
        #     [
        #         {
        #             "symbol": "BTC",
        #             "available": "1.57593193",
        #             "inOrder": "0.74832374"
        #         }
        #     ]
        #
        result = {
            '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.parse_balance(result, False)

    async def fetch_deposit_address(self, code, params={}):
        await self.load_markets()
        currency = self.currency(code)
        request = {
            'symbol': currency['id'],
        }
        response = await 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 {
            'currency': code,
            'address': address,
            'tag': tag,
            'info': response,
        }

    async def create_order(self, symbol, type, side, amount, price=None, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'market': market['id'],
            'side': side,
            'orderType': type,  # 'market', 'limit', 'stopLoss', 'stopLossLimit', 'takeProfit', 'takeProfitLimit'
            # 'amount': self.amount_to_precision(symbol, amount),
            # 'price': self.price_to_precision(symbol, price),
            # 'amountQuote': self.cost_to_precision(symbol, cost),
            # 'timeInForce': 'GTC',  # 'GTC', 'IOC', 'FOK'
            # 'selfTradePrevention': 'decrementAndCancel',  # 'decrementAndCancel', 'cancelOldest', 'cancelNewest', 'cancelBoth'
            # 'postOnly': False,
            # 'disableMarketProtection': False,  # don't cancel if the next fill price is 10% worse than the best fill price
            # 'responseRequired': True,  # False is faster
        }
        isStopLimit = (type == 'stopLossLimit') or (type == 'takeProfitLimit')
        isStopMarket = (type == 'stopLoss') or (type == 'takeProfit')
        if type == 'market':
            cost = None
            if price is not None:
                cost = amount * price
            else:
                cost = self.safe_number_2(params, 'cost', 'amountQuote')
            if cost is not None:
                precision = market['precision']['price']
                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', 'amountQuote'])
        elif type == 'limit':
            request['price'] = self.price_to_precision(symbol, price)
            request['amount'] = self.amount_to_precision(symbol, amount)
        elif isStopMarket or isStopLimit:
            stopPrice = self.safe_number_2(params, 'stopPrice', 'triggerAmount')
            if stopPrice is None:
                if isStopLimit:
                    raise ArgumentsRequired(self.id + ' createOrder requires a stopPrice parameter for a ' + type + ' order')
                elif isStopMarket:
                    if price is None:
                        raise ArgumentsRequired(self.id + ' createOrder requires a price argument or a stopPrice parameter for a ' + type + ' order')
                    else:
                        stopPrice = price
            if isStopLimit:
                request['price'] = self.price_to_precision(symbol, price)
            params = self.omit(params, ['stopPrice', 'triggerAmount'])
            request['triggerAmount'] = self.price_to_precision(symbol, stopPrice)
            request['triggerType'] = 'price'
            request['amount'] = self.amount_to_precision(symbol, amount)
        response = await self.privatePostOrder(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)

    async def edit_order(self, id, symbol, type, side, amount=None, price=None, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request = {}
        amountRemaining = self.safe_number(params, 'amountRemaining')
        params = self.omit(params, 'amountRemaining')
        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)
        request = self.extend(request, params)
        if request:
            request['orderId'] = id
            request['market'] = market['id']
            response = await self.privatePutOrder(self.extend(request, params))
            return self.parse_order(response, market)
        else:
            raise ArgumentsRequired(self.id + ' editOrder() requires an amount argument, or a price argument, or non-empty params')

    async def cancel_order(self, id, symbol=None, params={}):
        if symbol is None:
            raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'orderId': id,
            'market': market['id'],
        }
        response = await self.privateDeleteOrder(self.extend(request, params))
        #
        #     {
        #         "orderId": "2e7ce7fc-44e2-4d80-a4a7-d079c4750b61"
        #     }
        #
        return self.parse_order(response, market)

    async def cancel_all_orders(self, symbol=None, params={}):
        await self.load_markets()
        request = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['market'] = market['id']
        response = await self.privateDeleteOrders(self.extend(request, params))
        #
        #     [
        #         {
        #             "orderId": "1be6d0df-d5dc-4b53-a250-3376f3b393e6"
        #         }
        #     ]
        #
        return self.parse_orders(response, market)

    async def fetch_order(self, id, symbol=None, params={}):
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchOrder() requires a symbol argument')
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'orderId': id,
            'market': market['id'],
        }
        response = await 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)

    async def fetch_orders(self, symbol=None, since=None, limit=None, params={}):
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchOrders() requires a symbol argument')
        await self.load_markets()
        market = self.market(symbol)
        request = {
            '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
        response = await self.privateGetOrders(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)

    async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
        await self.load_markets()
        request = {
            # '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 = await 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):
        statuses = {
            '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, market=None):
        #
        # 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')
        symbol = self.safe_symbol(marketId, market, '-')
        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_number(order, 'price')
        amount = self.safe_number(order, 'amount')
        remaining = self.safe_number(order, 'amountRemaining')
        filled = self.safe_number(order, 'filledAmount')
        cost = self.safe_number(order, 'filledAmountQuote')
        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', [])
        trades = self.parse_trades(rawTrades, market, None, None, {
            'symbol': symbol,
            'order': id,
            'side': side,
            'type': type,
        })
        timeInForce = self.safe_string(order, 'timeInForce')
        postOnly = self.safe_value(order, 'postOnly')
        # https://github.com/ccxt/ccxt/issues/8489
        stopPrice = self.safe_number(order, 'triggerPrice')
        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,
            'stopPrice': stopPrice,
            'amount': amount,
            'cost': cost,
            'average': None,
            'filled': filled,
            'remaining': remaining,
            'status': status,
            'fee': fee,
            'trades': trades,
        })

    async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchMyTrades() requires a symbol argument')
        await self.load_markets()
        market = self.market(symbol)
        request = {
            '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
        response = await self.privateGetTrades(self.extend(request, params))
        #
        #     [
        #         {
        #             "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)

    async def withdraw(self, code, amount, address, tag=None, params={}):
        self.check_address(address)
        await self.load_markets()
        currency = self.currency(code)
        request = {
            '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
        response = await self.privatePostWithdrawal(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #         "symbol": "BTC",
        #         "amount": "1.5"
        #     }
        #
        return self.parse_transaction(response, currency)

    async def fetch_withdrawals(self, code=None, since=None, limit=None, params={}):
        await self.load_markets()
        request = {
            # '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
        response = await self.privateGetWithdrawalHistory(self.extend(request, params))
        #
        #     [
        #         {
        #             "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)

    async def fetch_deposits(self, code=None, since=None, limit=None, params={}):
        await self.load_markets()
        request = {
            # '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
        response = await self.privateGetDepositHistory(self.extend(request, params))
        #
        #     [
        #         {
        #             "timestamp":1590492401000,
        #             "symbol":"ETH",
        #             "amount":"0.249825",
        #             "fee":"0",
        #             "status":"completed",
        #             "txId":"0x5167b473fd37811f9ef22364c3d54726a859ef9d98934b3a1e11d7baa8d2c2e2"
        #         }
        #     ]
        #
        return self.parse_transactions(response, currency, since, limit)

    def parse_transaction_status(self, status):
        statuses = {
            '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, currency=None):
        #
        # 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:
            type = 'withdrawal'
        else:
            type = 'deposit' if (status is None) else 'withdrawal'
        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,
        }

    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))
            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, reason, url, method, headers, body, response, requestHeaders, requestBody):
        if response is None:
            return  # 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
