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

# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt_zagrava/ccxt_zagrava/blob/master/CONTRIBUTING.md#how-to-contribute-code

from ccxt_zagrava.base.exchange import Exchange
from ccxt_zagrava.abstract.zonda import ImplicitAPI
import hashlib
from ccxt_zagrava.base.types import Balances, Currency, Int, Market, Num, Order, OrderBook, OrderSide, OrderType, Str, Strings, Ticker, Tickers, Trade, Transaction, TransferEntry
from typing import List
from ccxt_zagrava.base.errors import ExchangeError
from ccxt_zagrava.base.errors import AuthenticationError
from ccxt_zagrava.base.errors import PermissionDenied
from ccxt_zagrava.base.errors import AccountSuspended
from ccxt_zagrava.base.errors import BadRequest
from ccxt_zagrava.base.errors import BadSymbol
from ccxt_zagrava.base.errors import InsufficientFunds
from ccxt_zagrava.base.errors import InvalidOrder
from ccxt_zagrava.base.errors import OrderNotFound
from ccxt_zagrava.base.errors import OrderImmediatelyFillable
from ccxt_zagrava.base.errors import RateLimitExceeded
from ccxt_zagrava.base.errors import OnMaintenance
from ccxt_zagrava.base.errors import InvalidNonce
from ccxt_zagrava.base.decimal_to_precision import TICK_SIZE
from ccxt_zagrava.base.precise import Precise


class zonda(Exchange, ImplicitAPI):

    def describe(self):
        return self.deep_extend(super(zonda, self).describe(), {
            'id': 'zonda',
            'name': 'Zonda',
            'countries': ['EE'],  # Estonia
            'rateLimit': 1000,
            'has': {
                'CORS': True,
                'spot': True,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'addMargin': False,
                'cancelAllOrders': False,
                'cancelOrder': True,
                'cancelOrders': False,
                'closeAllPositions': False,
                'closePosition': False,
                'createDepositAddress': False,
                'createOrder': True,
                'createReduceOnlyOrder': False,
                'fetchBalance': True,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchCrossBorrowRate': False,
                'fetchCrossBorrowRates': False,
                'fetchDeposit': False,
                'fetchDepositAddress': True,
                'fetchDepositAddresses': True,
                'fetchDeposits': None,
                'fetchFundingHistory': False,
                'fetchFundingRate': False,
                'fetchFundingRateHistory': False,
                'fetchFundingRates': False,
                'fetchIndexOHLCV': False,
                'fetchIsolatedBorrowRate': False,
                'fetchIsolatedBorrowRates': False,
                'fetchLedger': True,
                'fetchLeverage': False,
                'fetchLeverageTiers': False,
                'fetchMarginMode': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenInterestHistory': False,
                'fetchOpenOrder': False,
                'fetchOpenOrders': True,
                'fetchOrderBook': True,
                'fetchOrderBooks': False,
                'fetchPosition': False,
                'fetchPositionMode': False,
                'fetchPositions': False,
                'fetchPositionsRisk': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTime': False,
                'fetchTrades': True,
                'fetchTradingFee': False,
                'fetchTradingFees': False,
                'fetchTransactionFee': False,
                'fetchTransactionFees': False,
                'fetchTransactions': None,
                'fetchTransfer': False,
                'fetchWithdrawal': False,
                'fetchWithdrawals': None,
                'reduceMargin': False,
                'setLeverage': False,
                'setMargin': False,
                'setMarginMode': False,
                'setPositionMode': False,
                'transfer': True,
                'withdraw': True,
            },
            'timeframes': {
                '1m': '60',
                '3m': '180',
                '5m': '300',
                '15m': '900',
                '30m': '1800',
                '1h': '3600',
                '2h': '7200',
                '4h': '14400',
                '6h': '21600',
                '12h': '43200',
                '1d': '86400',
                '3d': '259200',
                '1w': '604800',
            },
            'hostname': 'zondacrypto.exchange',
            'urls': {
                'referral': 'https://auth.zondaglobal.com/ref/jHlbB4mIkdS1',
                'logo': 'https://user-images.githubusercontent.com/1294454/159202310-a0e38007-5e7c-4ba9-a32f-c8263a0291fe.jpg',
                'www': 'https://zondaglobal.com',
                'api': {
                    'public': 'https://{hostname}/API/Public',
                    'private': 'https://{hostname}/API/Trading/tradingApi.php',
                    'v1_01Public': 'https://api.{hostname}/rest',
                    'v1_01Private': 'https://api.{hostname}/rest',
                },
                'doc': [
                    'https://docs.zondacrypto.exchange/',
                    'https://github.com/BitBayNet/API',
                ],
                'support': 'https://zondaglobal.com/en/helpdesk/zonda-exchange',
                'fees': 'https://zondaglobal.com/legal/zonda-exchange/fees',
            },
            'api': {
                'public': {
                    'get': [
                        '{id}/all',
                        '{id}/market',
                        '{id}/orderbook',
                        '{id}/ticker',
                        '{id}/trades',
                    ],
                },
                'private': {
                    'post': [
                        'info',
                        'trade',
                        'cancel',
                        'orderbook',
                        'orders',
                        'transfer',
                        'withdraw',
                        'history',
                        'transactions',
                    ],
                },
                'v1_01Public': {
                    'get': [
                        'trading/ticker',
                        'trading/ticker/{symbol}',
                        'trading/stats',
                        'trading/stats/{symbol}',
                        'trading/orderbook/{symbol}',
                        'trading/transactions/{symbol}',
                        'trading/candle/history/{symbol}/{resolution}',
                    ],
                },
                'v1_01Private': {
                    'get': [
                        'api_payments/deposits/crypto/addresses',
                        'payments/withdrawal/{detailId}',
                        'payments/deposit/{detailId}',
                        'trading/offer',
                        'trading/stop/offer',
                        'trading/config/{symbol}',
                        'trading/history/transactions',
                        'balances/BITBAY/history',
                        'balances/BITBAY/balance',
                        'fiat_cantor/rate/{baseId}/{quoteId}',
                        'fiat_cantor/history',
                        'client_payments/v2/customer/crypto/{currency}/channels/deposit',
                        'client_payments/v2/customer/crypto/{currency}/channels/withdrawal',
                        'client_payments/v2/customer/crypto/deposit/fee',
                        'client_payments/v2/customer/crypto/withdrawal/fee',
                    ],
                    'post': [
                        'trading/offer/{symbol}',
                        'trading/stop/offer/{symbol}',
                        'trading/config/{symbol}',
                        'balances/BITBAY/balance',
                        'balances/BITBAY/balance/transfer/{source}/{destination}',
                        'fiat_cantor/exchange',
                        'api_payments/withdrawals/crypto',
                        'api_payments/withdrawals/fiat',
                        'client_payments/v2/customer/crypto/deposit',
                        'client_payments/v2/customer/crypto/withdrawal',
                    ],
                    'delete': [
                        'trading/offer/{symbol}/{id}/{side}/{price}',
                        'trading/stop/offer/{symbol}/{id}/{side}/{price}',
                    ],
                    'put': [
                        'balances/BITBAY/balance/{id}',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'maker': self.parse_number('0.0'),
                    'taker': self.parse_number('0.001'),
                    'percentage': True,
                    'tierBased': False,
                },
                'fiat': {
                    'maker': self.parse_number('0.0030'),
                    'taker': self.parse_number('0.0043'),
                    'percentage': True,
                    'tierBased': True,
                    'tiers': {
                        'taker': [
                            [self.parse_number('0.0043'), self.parse_number('0')],
                            [self.parse_number('0.0042'), self.parse_number('1250')],
                            [self.parse_number('0.0041'), self.parse_number('3750')],
                            [self.parse_number('0.0040'), self.parse_number('7500')],
                            [self.parse_number('0.0039'), self.parse_number('10000')],
                            [self.parse_number('0.0038'), self.parse_number('15000')],
                            [self.parse_number('0.0037'), self.parse_number('20000')],
                            [self.parse_number('0.0036'), self.parse_number('25000')],
                            [self.parse_number('0.0035'), self.parse_number('37500')],
                            [self.parse_number('0.0034'), self.parse_number('50000')],
                            [self.parse_number('0.0033'), self.parse_number('75000')],
                            [self.parse_number('0.0032'), self.parse_number('100000')],
                            [self.parse_number('0.0031'), self.parse_number('150000')],
                            [self.parse_number('0.0030'), self.parse_number('200000')],
                            [self.parse_number('0.0029'), self.parse_number('250000')],
                            [self.parse_number('0.0028'), self.parse_number('375000')],
                            [self.parse_number('0.0027'), self.parse_number('500000')],
                            [self.parse_number('0.0026'), self.parse_number('625000')],
                            [self.parse_number('0.0025'), self.parse_number('875000')],
                        ],
                        'maker': [
                            [self.parse_number('0.0030'), self.parse_number('0')],
                            [self.parse_number('0.0029'), self.parse_number('1250')],
                            [self.parse_number('0.0028'), self.parse_number('3750')],
                            [self.parse_number('0.0028'), self.parse_number('7500')],
                            [self.parse_number('0.0027'), self.parse_number('10000')],
                            [self.parse_number('0.0026'), self.parse_number('15000')],
                            [self.parse_number('0.0025'), self.parse_number('20000')],
                            [self.parse_number('0.0025'), self.parse_number('25000')],
                            [self.parse_number('0.0024'), self.parse_number('37500')],
                            [self.parse_number('0.0023'), self.parse_number('50000')],
                            [self.parse_number('0.0023'), self.parse_number('75000')],
                            [self.parse_number('0.0022'), self.parse_number('100000')],
                            [self.parse_number('0.0021'), self.parse_number('150000')],
                            [self.parse_number('0.0021'), self.parse_number('200000')],
                            [self.parse_number('0.0020'), self.parse_number('250000')],
                            [self.parse_number('0.0019'), self.parse_number('375000')],
                            [self.parse_number('0.0018'), self.parse_number('500000')],
                            [self.parse_number('0.0018'), self.parse_number('625000')],
                            [self.parse_number('0.0017'), self.parse_number('875000')],
                        ],
                    },
                },
                'funding': {
                    'withdraw': {},
                },
            },
            'options': {
                'fetchTickerMethod': 'v1_01PublicGetTradingTickerSymbol',  # or v1_01PublicGetTradingStatsSymbol
                'fetchTickersMethod': 'v1_01PublicGetTradingTicker',       # or v1_01PublicGetTradingStats
                'fiatCurrencies': ['EUR', 'USD', 'GBP', 'PLN'],
                'transfer': {
                    'fillResponseFromRequest': True,
                },
            },
            'precisionMode': TICK_SIZE,
            'exceptions': {
                '400': ExchangeError,  # At least one parameter wasn't set
                '401': InvalidOrder,  # Invalid order type
                '402': InvalidOrder,  # No orders with specified currencies
                '403': InvalidOrder,  # Invalid payment currency name
                '404': InvalidOrder,  # Error. Wrong transaction type
                '405': InvalidOrder,  # Order with self id doesn't exist
                '406': InsufficientFunds,  # No enough money or crypto
                # code 407 not specified are not specified in their docs
                '408': InvalidOrder,  # Invalid currency name
                '501': AuthenticationError,  # Invalid public key
                '502': AuthenticationError,  # Invalid sign
                '503': InvalidNonce,  # Invalid moment parameter. Request time doesn't match current server time
                '504': ExchangeError,  # Invalid method
                '505': AuthenticationError,  # Key has no permission for self action
                '506': AccountSuspended,  # Account locked. Please contact with customer service
                # codes 507 and 508 are not specified in their docs
                '509': ExchangeError,  # The BIC/SWIFT is required for self currency
                '510': BadSymbol,  # Invalid market name
                'FUNDS_NOT_SUFFICIENT': InsufficientFunds,
                'OFFER_FUNDS_NOT_EXCEEDING_MINIMUMS': InvalidOrder,
                'OFFER_NOT_FOUND': OrderNotFound,
                'OFFER_WOULD_HAVE_BEEN_PARTIALLY_FILLED': OrderImmediatelyFillable,
                'ACTION_LIMIT_EXCEEDED': RateLimitExceeded,
                'UNDER_MAINTENANCE': OnMaintenance,
                'REQUEST_TIMESTAMP_TOO_OLD': InvalidNonce,
                'PERMISSIONS_NOT_SUFFICIENT': PermissionDenied,
                'INVALID_STOP_RATE': InvalidOrder,
                'TIMEOUT': ExchangeError,
                'RESPONSE_TIMEOUT': ExchangeError,
                'ACTION_BLOCKED': PermissionDenied,
                'INVALID_HASH_SIGNATURE': AuthenticationError,
            },
            'commonCurrencies': {
                'GGC': 'Global Game Coin',
            },
        })

    def fetch_markets(self, params={}) -> List[Market]:
        """
        :see: https://docs.zondacrypto.exchange/reference/ticker-1
        retrieves data on all markets for zonda
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = self.v1_01PublicGetTradingTicker(params)
        #
        #     {
        #         "status": "Ok",
        #         "items": {
        #             "BSV-USD": {
        #                 "market": {
        #                     "code": "BSV-USD",
        #                     "first": {currency: "BSV", minOffer: "0.00035", scale: 8},
        #                     "second": {currency: "USD", minOffer: "5", scale: 2}
        #                 },
        #                 "time": "1557569762154",
        #                 "highestBid": "52.31",
        #                 "lowestAsk": "62.99",
        #                 "rate": "63",
        #                 "previousRate": "51.21",
        #             },
        #         },
        #     }
        #
        items = self.safe_value(response, 'items', {})
        markets = list(items.values())
        return self.parse_markets(markets)

    def parse_market(self, item) -> Market:
        market = self.safe_value(item, 'market', {})
        id = self.safe_string(market, 'code')
        first = self.safe_value(market, 'first', {})
        second = self.safe_value(market, 'second', {})
        baseId = self.safe_string(first, 'currency')
        quoteId = self.safe_string(second, 'currency')
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        fees = self.safe_value(self.fees, 'trading', {})
        fiatCurrencies = self.safe_value(self.options, 'fiatCurrencies', [])
        if self.in_array(base, fiatCurrencies) or self.in_array(quote, fiatCurrencies):
            fees = self.safe_value(self.fees, 'fiat', {})
        # todo: check that the limits have ben interpreted correctly
        return {
            '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': None,
            'contract': False,
            'linear': None,
            'inverse': None,
            'taker': self.safe_number(fees, 'taker'),
            'maker': self.safe_number(fees, 'maker'),
            'contractSize': None,
            'expiry': None,
            'expiryDatetime': None,
            'optionType': None,
            'strike': None,
            'precision': {
                'amount': self.parse_number(self.parse_precision(self.safe_string(first, 'scale'))),
                'price': self.parse_number(self.parse_precision(self.safe_string(second, 'scale'))),
            },
            'limits': {
                'leverage': {
                    'min': None,
                    'max': None,
                },
                'amount': {
                    'min': self.safe_number(first, 'minOffer'),
                    'max': None,
                },
                'price': {
                    'min': None,
                    'max': None,
                },
                'cost': {
                    'min': None,
                    'max': None,
                },
            },
            'created': None,
            'info': item,
        }

    def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
        :see: https://docs.zondacrypto.exchange/reference/active-orders
        fetch all unfilled currently open orders
        :param str symbol: not used by zonda fetchOpenOrders
        :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_zagrava.com/#/?id=order-structure>`
        """
        self.load_markets()
        request: dict = {}
        response = self.v1_01PrivateGetTradingOffer(self.extend(request, params))
        items = self.safe_list(response, 'items', [])
        return self.parse_orders(items, None, since, limit, {'status': 'open'})

    def parse_order(self, order: dict, market: Market = None) -> Order:
        #
        #     {
        #         "market": "ETH-EUR",
        #         "offerType": "Sell",
        #         "id": "93d3657b-d616-11e9-9248-0242ac110005",
        #         "currentAmount": "0.04",
        #         "lockedAmount": "0.04",
        #         "rate": "280",
        #         "startAmount": "0.04",
        #         "time": "1568372806924",
        #         "postOnly": False,
        #         "hidden": False,
        #         "mode": "limit",
        #         "receivedAmount": "0.0",
        #         "firstBalanceId": "5b816c3e-437c-4e43-9bef-47814ae7ebfc",
        #         "secondBalanceId": "ab43023b-4079-414c-b340-056e3430a3af"
        #     }
        #
        # cancelOrder
        #
        #    {
        #        status: "Ok",
        #        errors: []
        #    }
        #
        marketId = self.safe_string(order, 'market')
        symbol = self.safe_symbol(marketId, market, '-')
        timestamp = self.safe_integer(order, 'time')
        amount = self.safe_string(order, 'startAmount')
        remaining = self.safe_string(order, 'currentAmount')
        postOnly = self.safe_value(order, 'postOnly')
        return self.safe_order({
            'id': self.safe_string(order, 'id'),
            'clientOrderId': None,
            'info': order,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'status': None,
            'symbol': symbol,
            'type': self.safe_string(order, 'mode'),
            'timeInForce': None,
            'postOnly': postOnly,
            'side': self.safe_string_lower(order, 'offerType'),
            'price': self.safe_string(order, 'rate'),
            'stopPrice': None,
            'triggerPrice': None,
            'amount': amount,
            'cost': None,
            'filled': None,
            'remaining': remaining,
            'average': None,
            'fee': None,
            'trades': None,
        }, market)

    def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        :see: https://docs.zondacrypto.exchange/reference/transactions-history
        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
        :returns Trade[]: a list of `trade structures <https://docs.ccxt_zagrava.com/#/?id=trade-structure>`
        """
        self.load_markets()
        request: dict = {}
        if symbol:
            markets = [self.market_id(symbol)]
            symbol = self.symbol(symbol)
            request['markets'] = markets
        query: dict = {'query': self.json(self.extend(request, params))}
        response = self.v1_01PrivateGetTradingHistoryTransactions(query)
        #
        #     {
        #         "status": "Ok",
        #         "totalRows": "67",
        #         "items": [
        #             {
        #                 "id": "b54659a0-51b5-42a0-80eb-2ac5357ccee2",
        #                 "market": "BTC-EUR",
        #                 "time": "1541697096247",
        #                 "amount": "0.00003",
        #                 "rate": "4341.44",
        #                 "initializedBy": "Sell",
        #                 "wasTaker": False,
        #                 "userAction": "Buy",
        #                 "offerId": "bd19804a-6f89-4a69-adb8-eb078900d006",
        #                 "commissionValue": null
        #             },
        #         ]
        #     }
        #
        items = self.safe_value(response, 'items')
        result = self.parse_trades(items, None, since, limit)
        if symbol is None:
            return result
        return self.filter_by_symbol(result, symbol)

    def parse_balance(self, response) -> Balances:
        balances = self.safe_value(response, 'balances')
        if balances is None:
            raise ExchangeError(self.id + ' empty balance response ' + self.json(response))
        result: dict = {'info': response}
        for i in range(0, len(balances)):
            balance = balances[i]
            currencyId = self.safe_string(balance, 'currency')
            code = self.safe_currency_code(currencyId)
            account = self.account()
            account['used'] = self.safe_string(balance, 'lockedFunds')
            account['free'] = self.safe_string(balance, 'availableFunds')
            result[code] = account
        return self.safe_balance(result)

    def fetch_balance(self, params={}) -> Balances:
        """
        :see: https://docs.zondacrypto.exchange/reference/list-of-wallets
        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_zagrava.com/#/?id=balance-structure>`
        """
        self.load_markets()
        response = self.v1_01PrivateGetBalancesBITBAYBalance(params)
        return self.parse_balance(response)

    def fetch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
        """
        :see: https://docs.zondacrypto.exchange/reference/orderbook-2
        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_zagrava.com/#/?id=order-book-structure>` indexed by market symbols
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = self.v1_01PublicGetTradingOrderbookSymbol(self.extend(request, params))
        #
        #     {
        #         "status":"Ok",
        #         "sell":[
        #             {"ra":"43988.93","ca":"0.00100525","sa":"0.00100525","pa":"0.00100525","co":1},
        #             {"ra":"43988.94","ca":"0.00114136","sa":"0.00114136","pa":"0.00114136","co":1},
        #             {"ra":"43989","ca":"0.010578","sa":"0.010578","pa":"0.010578","co":1},
        #         ],
        #         "buy":[
        #             {"ra":"42157.33","ca":"2.83147881","sa":"2.83147881","pa":"2.83147881","co":2},
        #             {"ra":"42096.0","ca":"0.00011878","sa":"0.00011878","pa":"0.00011878","co":1},
        #             {"ra":"42022.0","ca":"0.00011899","sa":"0.00011899","pa":"0.00011899","co":1},
        #         ],
        #         "timestamp":"1642299886122",
        #         "seqNo":"27641254"
        #     }
        #
        rawBids = self.safe_value(response, 'buy', [])
        rawAsks = self.safe_value(response, 'sell', [])
        timestamp = self.safe_integer(response, 'timestamp')
        return {
            'symbol': market['symbol'],
            'bids': self.parse_bids_asks(rawBids, 'ra', 'ca'),
            'asks': self.parse_bids_asks(rawAsks, 'ra', 'ca'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'nonce': self.safe_integer(response, 'seqNo'),
        }

    def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
        #
        # version 1
        #
        #    {
        #        "m": "ETH-PLN",
        #        "h": "13485.13",
        #        "l": "13100.01",
        #        "v": "126.10710939",
        #        "r24h": "13332.72"
        #    }
        #
        # version 2
        #
        #    {
        #        "market": {
        #            "code": "ADA-USDT",
        #            "first": {
        #                "currency": "ADA",
        #                "minOffer": "0.2",
        #                "scale": "6"
        #            },
        #            "second": {
        #                "currency": "USDT",
        #                "minOffer": "0.099",
        #                "scale": "6"
        #            },
        #            "amountPrecision": "6",
        #            "pricePrecision": "6",
        #            "ratePrecision": "6"
        #        },
        #        "time": "1655812661202",
        #        "highestBid": "0.492",
        #        "lowestAsk": "0.499389",
        #        "rate": "0.50588",
        #        "previousRate": "0.504981"
        #    }
        #
        tickerMarket = self.safe_value(ticker, 'market')
        marketId = self.safe_string_2(tickerMarket, 'code', 'm')
        market = self.safe_market(marketId, market)
        timestamp = self.safe_integer(ticker, 'time')
        rate = self.safe_value(ticker, 'rate')
        return self.safe_ticker({
            'symbol': self.safe_symbol(marketId, market),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': self.safe_string(ticker, 'h'),
            'low': self.safe_string(ticker, 'l'),
            'bid': self.safe_number(ticker, 'highestBid'),
            'bidVolume': None,
            'ask': self.safe_number(ticker, 'lowestAsk'),
            'askVolume': None,
            'vwap': None,
            'open': self.safe_string(ticker, 'r24h'),
            'close': rate,
            'last': rate,
            'previousClose': self.safe_value(ticker, 'previousRate'),
            'change': None,
            'percentage': None,
            'average': None,
            'baseVolume': self.safe_string(ticker, 'v'),
            'quoteVolume': None,
            'info': ticker,
        }, market)

    def fetch_ticker(self, symbol: str, params={}):
        """
        v1_01PublicGetTradingTickerSymbol retrieves timestamp, datetime, bid, ask, close, last, previousClose, v1_01PublicGetTradingStatsSymbol retrieves high, low, volume and opening price of an asset
        :see: https://docs.zondacrypto.exchange/reference/market-statistics
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.method]: v1_01PublicGetTradingTickerSymbol(default) or v1_01PublicGetTradingStatsSymbol
        :returns dict: a `ticker structure <https://docs.ccxt_zagrava.com/#/?id=ticker-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        method = 'v1_01PublicGetTradingTickerSymbol'
        defaultMethod = self.safe_string(self.options, 'fetchTickerMethod', method)
        fetchTickerMethod = self.safe_string_2(params, 'method', 'fetchTickerMethod', defaultMethod)
        response = None
        if fetchTickerMethod == method:
            response = self.v1_01PublicGetTradingTickerSymbol(self.extend(request, params))
            #
            #    {
            #        "status": "Ok",
            #        "ticker": {
            #            "market": {
            #                "code": "ADA-USDT",
            #                "first": {
            #                    "currency": "ADA",
            #                    "minOffer": "0.21",
            #                    "scale": 6
            #                },
            #                "second": {
            #                    "currency": "USDT",
            #                    "minOffer": "0.099",
            #                    "scale": 6
            #                },
            #                "amountPrecision": 6,
            #                "pricePrecision": 6,
            #                "ratePrecision": 6
            #            },
            #            "time": "1655810976780",
            #            "highestBid": "0.498543",
            #            "lowestAsk": "0.50684",
            #            "rate": "0.50588",
            #            "previousRate": "0.504981"
            #        }
            #    }
            #
        elif fetchTickerMethod == 'v1_01PublicGetTradingStatsSymbol':
            response = self.v1_01PublicGetTradingStatsSymbol(self.extend(request, params))
            #
            #    {
            #        "status": "Ok",
            #        "stats": {
            #            "m": "BTC-USDT",
            #            "h": "28800",
            #            "l": "26703.950101",
            #            "v": "6.72932396",
            #            "r24h": "27122.2"
            #        }
            #    }
            #
        else:
            raise BadRequest(self.id + ' fetchTicker params["method"] must be "v1_01PublicGetTradingTickerSymbol" or "v1_01PublicGetTradingStatsSymbol"')
        stats = self.safe_value_2(response, 'ticker', 'stats')
        return self.parse_ticker(stats, market)

    def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
        """
         * @ignore
        v1_01PublicGetTradingTicker retrieves timestamp, datetime, bid, ask, close, last, previousClose for each market, v1_01PublicGetTradingStats retrieves high, low, volume and opening price of each market
        :see: https://docs.zondacrypto.exchange/reference/market-statistics
        :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
        :param str [params.method]: v1_01PublicGetTradingTicker(default) or v1_01PublicGetTradingStats
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt_zagrava.com/#/?id=ticker-structure>`
        """
        self.load_markets()
        method = 'v1_01PublicGetTradingTicker'
        defaultMethod = self.safe_string(self.options, 'fetchTickersMethod', method)
        fetchTickersMethod = self.safe_string_2(params, 'method', 'fetchTickersMethod', defaultMethod)
        response = None
        if fetchTickersMethod == method:
            response = self.v1_01PublicGetTradingTicker(params)
            #
            #    {
            #        "status": "Ok",
            #        "items": {
            #            "DAI-PLN": {
            #                "market": {
            #                    "code": "DAI-PLN",
            #                    "first": {
            #                        "currency": "DAI",
            #                        "minOffer": "0.99",
            #                        "scale": 8
            #                    },
            #                    "second": {
            #                        "currency": "PLN",
            #                        "minOffer": "5",
            #                        "scale": 2
            #                    },
            #                    "amountPrecision": 8,
            #                    "pricePrecision": 2,
            #                    "ratePrecision": 2
            #                },
            #                "time": "1655810825137",
            #                "highestBid": "4.42",
            #                "lowestAsk": "4.44",
            #                "rate": "4.44",
            #                "previousRate": "4.43"
            #            },
            #            ...
            #        }
            #    }
            #
        elif fetchTickersMethod == 'v1_01PublicGetTradingStats':
            response = self.v1_01PublicGetTradingStats(params)
            #
            #     {
            #         "status": "Ok",
            #         "items": {
            #             "DAI-PLN": {
            #                 "m": "DAI-PLN",
            #                 "h": "4.41",
            #                 "l": "4.37",
            #                 "v": "8.71068087",
            #                 "r24h": "4.36"
            #             },
            #             ...
            #         }
            #     }
            #
        else:
            raise BadRequest(self.id + ' fetchTickers params["method"] must be "v1_01PublicGetTradingTicker" or "v1_01PublicGetTradingStats"')
        items = self.safe_dict(response, 'items')
        return self.parse_tickers(items, symbols)

    def fetch_ledger(self, code: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        :see: https://docs.zondacrypto.exchange/reference/operations-history
        fetch the history of changes, actions done by the user or operations that altered balance of the user
        :param str code: unified currency code, default is None
        :param int [since]: timestamp in ms of the earliest ledger entry, default is None
        :param int [limit]: max number of ledger entrys to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ledger structure <https://docs.ccxt_zagrava.com/#/?id=ledger-structure>`
        """
        balanceCurrencies = []
        if code is not None:
            currency = self.currency(code)
            balanceCurrencies.append(currency['id'])
        request: dict = {
            'balanceCurrencies': balanceCurrencies,
        }
        if since is not None:
            request['fromTime'] = since
        if limit is not None:
            request['limit'] = limit
        request = self.extend(request, params)
        response = self.v1_01PrivateGetBalancesBITBAYHistory({'query': self.json(request)})
        items = response['items']
        return self.parse_ledger(items, None, since, limit)

    def parse_ledger_entry(self, item: dict, currency: Currency = None):
        #
        #    FUNDS_MIGRATION
        #    {
        #      "historyId": "84ea7a29-7da5-4de5-b0c0-871e83cad765",
        #      "balance": {
        #        "id": "821ec166-cb88-4521-916c-f4eb44db98df",
        #        "currency": "LTC",
        #        "type": "CRYPTO",
        #        "userId": "a34d361d-7bad-49c1-888e-62473b75d877",
        #        "name": "LTC"
        #      },
        #      "detailId": null,
        #      "time": 1506128252968,
        #      "type": "FUNDS_MIGRATION",
        #      "value": 0.0009957,
        #      "fundsBefore": {"total": 0, "available": 0, "locked": 0},
        #      "fundsAfter": {"total": 0.0009957, "available": 0.0009957, "locked": 0},
        #      "change": {"total": 0.0009957, "available": 0.0009957, "locked": 0}
        #    }
        #
        #    CREATE_BALANCE
        #    {
        #      "historyId": "d0fabd8d-9107-4b5e-b9a6-3cab8af70d49",
        #      "balance": {
        #        "id": "653ffcf2-3037-4ebe-8e13-d5ea1a01d60d",
        #        "currency": "BTG",
        #        "type": "CRYPTO",
        #        "userId": "a34d361d-7bad-49c1-888e-62473b75d877",
        #        "name": "BTG"
        #      },
        #      "detailId": null,
        #      "time": 1508895244751,
        #      "type": "CREATE_BALANCE",
        #      "value": 0,
        #      "fundsBefore": {"total": null, "available": null, "locked": null},
        #      "fundsAfter": {"total": 0, "available": 0, "locked": 0},
        #      "change": {"total": 0, "available": 0, "locked": 0}
        #    }
        #
        #    BITCOIN_GOLD_FORK
        #    {
        #      "historyId": "2b4d52d3-611c-473d-b92c-8a8d87a24e41",
        #      "balance": {
        #        "id": "653ffcf2-3037-4ebe-8e13-d5ea1a01d60d",
        #        "currency": "BTG",
        #        "type": "CRYPTO",
        #        "userId": "a34d361d-7bad-49c1-888e-62473b75d877",
        #        "name": "BTG"
        #      },
        #      "detailId": null,
        #      "time": 1508895244778,
        #      "type": "BITCOIN_GOLD_FORK",
        #      "value": 0.00453512,
        #      "fundsBefore": {"total": 0, "available": 0, "locked": 0},
        #      "fundsAfter": {"total": 0.00453512, "available": 0.00453512, "locked": 0},
        #      "change": {"total": 0.00453512, "available": 0.00453512, "locked": 0}
        #    }
        #
        #    ADD_FUNDS
        #    {
        #      "historyId": "3158236d-dae5-4a5d-81af-c1fa4af340fb",
        #      "balance": {
        #        "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7",
        #        "currency": "BTC",
        #        "type": "CRYPTO",
        #        "userId": "a34d361d-7bad-49c1-888e-62473b75d877",
        #        "name": "BTC"
        #      },
        #      "detailId": "8e83a960-e737-4380-b8bb-259d6e236faa",
        #      "time": 1520631178816,
        #      "type": "ADD_FUNDS",
        #      "value": 0.628405,
        #      "fundsBefore": {"total": 0.00453512, "available": 0.00453512, "locked": 0},
        #      "fundsAfter": {"total": 0.63294012, "available": 0.63294012, "locked": 0},
        #      "change": {"total": 0.628405, "available": 0.628405, "locked": 0}
        #    }
        #
        #    TRANSACTION_PRE_LOCKING
        #    {
        #      "historyId": "e7d19e0f-03b3-46a8-bc72-dde72cc24ead",
        #      "balance": {
        #        "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7",
        #        "currency": "BTC",
        #        "type": "CRYPTO",
        #        "userId": "a34d361d-7bad-49c1-888e-62473b75d877",
        #        "name": "BTC"
        #      },
        #      "detailId": null,
        #      "time": 1520706403868,
        #      "type": "TRANSACTION_PRE_LOCKING",
        #      "value": -0.1,
        #      "fundsBefore": {"total": 0.63294012, "available": 0.63294012, "locked": 0},
        #      "fundsAfter": {"total": 0.63294012, "available": 0.53294012, "locked": 0.1},
        #      "change": {"total": 0, "available": -0.1, "locked": 0.1}
        #    }
        #
        #    TRANSACTION_POST_OUTCOME
        #    {
        #      "historyId": "c4010825-231d-4a9c-8e46-37cde1f7b63c",
        #      "balance": {
        #        "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7",
        #        "currency": "BTC",
        #        "type": "CRYPTO",
        #        "userId": "a34d361d-7bad-49c1-888e-62473b75d877",
        #        "name": "BTC"
        #      },
        #      "detailId": "bf2876bc-b545-4503-96c8-ef4de8233876",
        #      "time": 1520706404032,
        #      "type": "TRANSACTION_POST_OUTCOME",
        #      "value": -0.01771415,
        #      "fundsBefore": {"total": 0.63294012, "available": 0.53294012, "locked": 0.1},
        #      "fundsAfter": {"total": 0.61522597, "available": 0.53294012, "locked": 0.08228585},
        #      "change": {"total": -0.01771415, "available": 0, "locked": -0.01771415}
        #    }
        #
        #    TRANSACTION_POST_INCOME
        #    {
        #      "historyId": "7f18b7af-b676-4125-84fd-042e683046f6",
        #      "balance": {
        #        "id": "ab43023b-4079-414c-b340-056e3430a3af",
        #        "currency": "EUR",
        #        "type": "FIAT",
        #        "userId": "a34d361d-7bad-49c1-888e-62473b75d877",
        #        "name": "EUR"
        #      },
        #      "detailId": "f5fcb274-0cc7-4385-b2d3-bae2756e701f",
        #      "time": 1520706404035,
        #      "type": "TRANSACTION_POST_INCOME",
        #      "value": 628.78,
        #      "fundsBefore": {"total": 0, "available": 0, "locked": 0},
        #      "fundsAfter": {"total": 628.78, "available": 628.78, "locked": 0},
        #      "change": {"total": 628.78, "available": 628.78, "locked": 0}
        #    }
        #
        #    TRANSACTION_COMMISSION_OUTCOME
        #    {
        #      "historyId": "843177fa-61bc-4cbf-8be5-b029d856c93b",
        #      "balance": {
        #        "id": "ab43023b-4079-414c-b340-056e3430a3af",
        #        "currency": "EUR",
        #        "type": "FIAT",
        #        "userId": "a34d361d-7bad-49c1-888e-62473b75d877",
        #        "name": "EUR"
        #      },
        #      "detailId": "f5fcb274-0cc7-4385-b2d3-bae2756e701f",
        #      "time": 1520706404050,
        #      "type": "TRANSACTION_COMMISSION_OUTCOME",
        #      "value": -2.71,
        #      "fundsBefore": {"total": 766.06, "available": 766.06, "locked": 0},
        #      "fundsAfter": {"total": 763.35,"available": 763.35, "locked": 0},
        #      "change": {"total": -2.71, "available": -2.71, "locked": 0}
        #    }
        #
        #    TRANSACTION_OFFER_COMPLETED_RETURN
        #    {
        #      "historyId": "cac69b04-c518-4dc5-9d86-e76e91f2e1d2",
        #      "balance": {
        #        "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7",
        #        "currency": "BTC",
        #        "type": "CRYPTO",
        #        "userId": "a34d361d-7bad-49c1-888e-62473b75d877",
        #        "name": "BTC"
        #      },
        #      "detailId": null,
        #      "time": 1520714886425,
        #      "type": "TRANSACTION_OFFER_COMPLETED_RETURN",
        #      "value": 0.00000196,
        #      "fundsBefore": {"total": 0.00941208, "available": 0.00941012, "locked": 0.00000196},
        #      "fundsAfter": {"total": 0.00941208, "available": 0.00941208, "locked": 0},
        #      "change": {"total": 0, "available": 0.00000196, "locked": -0.00000196}
        #    }
        #
        #    WITHDRAWAL_LOCK_FUNDS
        #    {
        #      "historyId": "03de2271-66ab-4960-a786-87ab9551fc14",
        #      "balance": {
        #        "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7",
        #        "currency": "BTC",
        #        "type": "CRYPTO",
        #        "userId": "a34d361d-7bad-49c1-888e-62473b75d877",
        #        "name": "BTC"
        #      },
        #      "detailId": "6ad3dc72-1d6d-4ec2-8436-ca43f85a38a6",
        #      "time": 1522245654481,
        #      "type": "WITHDRAWAL_LOCK_FUNDS",
        #      "value": -0.8,
        #      "fundsBefore": {"total": 0.8, "available": 0.8, "locked": 0},
        #      "fundsAfter": {"total": 0.8, "available": 0, "locked": 0.8},
        #      "change": {"total": 0, "available": -0.8, "locked": 0.8}
        #    }
        #
        #    WITHDRAWAL_SUBTRACT_FUNDS
        #    {
        #      "historyId": "b0308c89-5288-438d-a306-c6448b1a266d",
        #      "balance": {
        #        "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7",
        #        "currency": "BTC",
        #        "type": "CRYPTO",
        #        "userId": "a34d361d-7bad-49c1-888e-62473b75d877",
        #        "name": "BTC"
        #      },
        #      "detailId": "6ad3dc72-1d6d-4ec2-8436-ca43f85a38a6",
        #      "time": 1522246526186,
        #      "type": "WITHDRAWAL_SUBTRACT_FUNDS",
        #      "value": -0.8,
        #      "fundsBefore": {"total": 0.8, "available": 0, "locked": 0.8},
        #      "fundsAfter": {"total": 0, "available": 0, "locked": 0},
        #      "change": {"total": -0.8, "available": 0, "locked": -0.8}
        #    }
        #
        #    TRANSACTION_OFFER_ABORTED_RETURN
        #    {
        #      "historyId": "b1a3c075-d403-4e05-8f32-40512cdd88c0",
        #      "balance": {
        #        "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7",
        #        "currency": "BTC",
        #        "type": "CRYPTO",
        #        "userId": "a34d361d-7bad-49c1-888e-62473b75d877",
        #        "name": "BTC"
        #      },
        #      "detailId": null,
        #      "time": 1522512298662,
        #      "type": "TRANSACTION_OFFER_ABORTED_RETURN",
        #      "value": 0.0564931,
        #      "fundsBefore": {"total": 0.44951311, "available": 0.39302001, "locked": 0.0564931},
        #      "fundsAfter": {"total": 0.44951311, "available": 0.44951311, "locked": 0},
        #      "change": {"total": 0, "available": 0.0564931, "locked": -0.0564931}
        #    }
        #
        #    WITHDRAWAL_UNLOCK_FUNDS
        #    {
        #      "historyId": "0ed569a2-c330-482e-bb89-4cb553fb5b11",
        #      "balance": {
        #        "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7",
        #        "currency": "BTC",
        #        "type": "CRYPTO",
        #        "userId": "a34d361d-7bad-49c1-888e-62473b75d877",
        #        "name": "BTC"
        #      },
        #      "detailId": "0c7be256-c336-4111-bee7-4eb22e339700",
        #      "time": 1527866360785,
        #      "type": "WITHDRAWAL_UNLOCK_FUNDS",
        #      "value": 0.05045,
        #      "fundsBefore": {"total": 0.86001578, "available": 0.80956578, "locked": 0.05045},
        #      "fundsAfter": {"total": 0.86001578, "available": 0.86001578, "locked": 0},
        #      "change": {"total": 0, "available": 0.05045, "locked": -0.05045}
        #    }
        #
        #    TRANSACTION_COMMISSION_RETURN
        #    {
        #      "historyId": "07c89c27-46f1-4d7a-8518-b73798bf168a",
        #      "balance": {
        #        "id": "ab43023b-4079-414c-b340-056e3430a3af",
        #        "currency": "EUR",
        #        "type": "FIAT",
        #        "userId": "a34d361d-7bad-49c1-888e-62473b75d877",
        #        "name": "EUR"
        #      },
        #      "detailId": null,
        #      "time": 1528304043063,
        #      "type": "TRANSACTION_COMMISSION_RETURN",
        #      "value": 0.6,
        #      "fundsBefore": {"total": 0, "available": 0, "locked": 0},
        #      "fundsAfter": {"total": 0.6, "available": 0.6, "locked": 0},
        #      "change": {"total": 0.6, "available": 0.6, "locked": 0}
        #    }
        #
        timestamp = self.safe_integer(item, 'time')
        balance = self.safe_value(item, 'balance', {})
        currencyId = self.safe_string(balance, 'currency')
        change = self.safe_value(item, 'change', {})
        amount = self.safe_string(change, 'total')
        direction = 'in'
        if Precise.string_lt(amount, '0'):
            direction = 'out'
            amount = Precise.string_neg(amount)
        # there are 2 undocumented api calls: (v1_01PrivateGetPaymentsDepositDetailId and v1_01PrivateGetPaymentsWithdrawalDetailId)
        # that can be used to enrich the transfers with txid, address etc(you need to use info.detailId parameter)
        fundsBefore = self.safe_value(item, 'fundsBefore', {})
        fundsAfter = self.safe_value(item, 'fundsAfter', {})
        return {
            'info': item,
            'id': self.safe_string(item, 'historyId'),
            'direction': direction,
            'account': None,
            'referenceId': self.safe_string(item, 'detailId'),
            'referenceAccount': None,
            'type': self.parse_ledger_entry_type(self.safe_string(item, 'type')),
            'currency': self.safe_currency_code(currencyId),
            'amount': self.parse_number(amount),
            'before': self.safe_number(fundsBefore, 'total'),
            'after': self.safe_number(fundsAfter, 'total'),
            'status': 'ok',
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'fee': None,
        }

    def parse_ledger_entry_type(self, type):
        types: dict = {
            'ADD_FUNDS': 'transaction',
            'BITCOIN_GOLD_FORK': 'transaction',
            'CREATE_BALANCE': 'transaction',
            'FUNDS_MIGRATION': 'transaction',
            'WITHDRAWAL_LOCK_FUNDS': 'transaction',
            'WITHDRAWAL_SUBTRACT_FUNDS': 'transaction',
            'WITHDRAWAL_UNLOCK_FUNDS': 'transaction',
            'TRANSACTION_COMMISSION_OUTCOME': 'fee',
            'TRANSACTION_COMMISSION_RETURN': 'fee',
            'TRANSACTION_OFFER_ABORTED_RETURN': 'trade',
            'TRANSACTION_OFFER_COMPLETED_RETURN': 'trade',
            'TRANSACTION_POST_INCOME': 'trade',
            'TRANSACTION_POST_OUTCOME': 'trade',
            'TRANSACTION_PRE_LOCKING': 'trade',
        }
        return self.safe_string(types, type, type)

    def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
        #
        #     [
        #         "1582399800000",
        #         {
        #             "o": "0.0001428",
        #             "c": "0.0001428",
        #             "h": "0.0001428",
        #             "l": "0.0001428",
        #             "v": "4",
        #             "co": "1"
        #         }
        #     ]
        #
        first = self.safe_value(ohlcv, 1, {})
        return [
            self.safe_integer(ohlcv, 0),
            self.safe_number(first, 'o'),
            self.safe_number(first, 'h'),
            self.safe_number(first, 'l'),
            self.safe_number(first, 'c'),
            self.safe_number(first, 'v'),
        ]

    def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
        """
        :see: https://docs.zondacrypto.exchange/reference/candles-chart
        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
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        self.load_markets()
        market = self.market(symbol)
        tradingSymbol = market['baseId'] + '-' + market['quoteId']
        request: dict = {
            'symbol': tradingSymbol,
            'resolution': self.safe_string(self.timeframes, timeframe, timeframe),
            # 'from': 1574709092000,  # unix timestamp in milliseconds, required
            # 'to': 1574709092000,  # unix timestamp in milliseconds, required
        }
        if limit is None:
            limit = 100
        else:
            limit = min(limit, 11000)  # supports up to 11k candles diapason
        duration = self.parse_timeframe(timeframe)
        timerange = limit * duration * 1000
        if since is None:
            request['to'] = self.milliseconds()
            request['from'] = request['to'] - timerange
        else:
            request['from'] = since
            request['to'] = self.sum(request['from'], timerange)
        response = self.v1_01PublicGetTradingCandleHistorySymbolResolution(self.extend(request, params))
        #
        #     {
        #         "status":"Ok",
        #         "items":[
        #             ["1591503060000",{"o":"0.02509572","c":"0.02509438","h":"0.02509664","l":"0.02509438","v":"0.02082165","co":"17"}],
        #             ["1591503120000",{"o":"0.02509606","c":"0.02509515","h":"0.02509606","l":"0.02509487","v":"0.04971703","co":"13"}],
        #             ["1591503180000",{"o":"0.02509532","c":"0.02509589","h":"0.02509589","l":"0.02509454","v":"0.01332236","co":"7"}],
        #         ]
        #     }
        #
        items = self.safe_list(response, 'items', [])
        return self.parse_ohlcvs(items, market, timeframe, since, limit)

    def parse_trade(self, trade: dict, market: Market = None) -> Trade:
        #
        # createOrder trades
        #
        #     {
        #         "rate": "0.02195928",
        #         "amount": "0.00167952"
        #     }
        #
        # fetchMyTrades(private)
        #
        #     {
        #         "amount": "0.29285199",
        #         "commissionValue": "0.00125927",
        #         "id": "11c8203a-a267-11e9-b698-0242ac110007",
        #         "initializedBy": "Buy",
        #         "market": "ETH-EUR",
        #         "offerId": "11c82038-a267-11e9-b698-0242ac110007",
        #         "rate": "277",
        #         "time": "1562689917517",
        #         "userAction": "Buy",
        #         "wasTaker": True,
        #     }
        #
        # fetchTrades(public)
        #
        #     {
        #          "id": "df00b0da-e5e0-11e9-8c19-0242ac11000a",
        #          "t": "1570108958831",
        #          "a": "0.04776653",
        #          "r": "0.02145854",
        #          "ty": "Sell"
        #     }
        #
        timestamp = self.safe_integer_2(trade, 'time', 't')
        side = self.safe_string_lower_2(trade, 'userAction', 'ty')
        wasTaker = self.safe_value(trade, 'wasTaker')
        takerOrMaker: Str = None
        if wasTaker is not None:
            takerOrMaker = 'taker' if wasTaker else 'maker'
        priceString = self.safe_string_2(trade, 'rate', 'r')
        amountString = self.safe_string_2(trade, 'amount', 'a')
        feeCostString = self.safe_string(trade, 'commissionValue')
        marketId = self.safe_string(trade, 'market')
        market = self.safe_market(marketId, market, '-')
        symbol = market['symbol']
        fee = None
        if feeCostString is not None:
            feeCurrency = market['base'] if (side == 'buy') else market['quote']
            fee = {
                'currency': feeCurrency,
                'cost': feeCostString,
            }
        order = self.safe_string(trade, 'offerId')
        # todo: check self logic
        type: Str = None
        if order is not None:
            type = 'limit' if order else 'market'
        return self.safe_trade({
            'id': self.safe_string(trade, 'id'),
            'order': order,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': symbol,
            'type': type,
            'side': side,
            'price': priceString,
            'amount': amountString,
            'cost': None,
            'takerOrMaker': takerOrMaker,
            'fee': fee,
            'info': trade,
        }, market)

    def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
        """
        :see: https://docs.zondacrypto.exchange/reference/last-transactions
        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
        :returns Trade[]: a list of `trade structures <https://docs.ccxt_zagrava.com/#/?id=public-trades>`
        """
        self.load_markets()
        market = self.market(symbol)
        tradingSymbol = market['baseId'] + '-' + market['quoteId']
        request: dict = {
            'symbol': tradingSymbol,
        }
        if since is not None:
            request['fromTime'] = since - 1  # result does not include exactly `since` time therefore decrease by 1
        if limit is not None:
            request['limit'] = limit  # default - 10, max - 300
        response = self.v1_01PublicGetTradingTransactionsSymbol(self.extend(request, params))
        items = self.safe_list(response, 'items')
        return self.parse_trades(items, market, since, limit)

    def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
        """
        create a trade order
        :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 exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt_zagrava.com/#/?id=order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        tradingSymbol = market['baseId'] + '-' + market['quoteId']
        amount = float(self.amount_to_precision(symbol, amount))
        request: dict = {
            'symbol': tradingSymbol,
            'offerType': side.upper(),
            'amount': amount,
        }
        stopLossPrice = self.safe_value_2(params, 'stopPrice', 'stopLossPrice')
        isStopLossPrice = stopLossPrice is not None
        isLimitOrder = type == 'limit'
        isMarketOrder = type == 'market'
        isStopLimit = (type == 'stop-limit') or (isLimitOrder and isStopLossPrice)
        isStopMarket = type == 'stop-market' or (isMarketOrder and isStopLossPrice)
        isStopOrder = isStopLimit or isStopMarket
        if isLimitOrder or isStopLimit:
            request['rate'] = self.price_to_precision(symbol, price)
            request['mode'] = 'stop-limit' if isStopLimit else 'limit'
        elif isMarketOrder or isStopMarket:
            request['mode'] = 'stop-market' if isStopMarket else 'market'
        else:
            raise ExchangeError(self.id + ' createOrder() invalid type')
        params = self.omit(params, ['stopPrice', 'stopLossPrice'])
        response = None
        if isStopOrder:
            if not isStopLossPrice:
                raise ExchangeError(self.id + ' createOrder() zonda requires `triggerPrice` or `stopPrice` parameter for stop-limit or stop-market orders')
            request['stopRate'] = self.price_to_precision(symbol, stopLossPrice)
            response = self.v1_01PrivatePostTradingStopOfferSymbol(self.extend(request, params))
        else:
            response = self.v1_01PrivatePostTradingOfferSymbol(self.extend(request, params))
        #
        # unfilled(open order)
        #
        #     {
        #         "status": "Ok",
        #         "completed": False,  # can deduce status from here
        #         "offerId": "ce9cc72e-d61c-11e9-9248-0242ac110005",
        #         "transactions": [],  # can deduce order info from here
        #     }
        #
        # filled(closed order)
        #
        #     {
        #         "status": "Ok",
        #         "offerId": "942a4a3e-e922-11e9-8c19-0242ac11000a",
        #         "completed": True,
        #         "transactions": [
        #           {
        #             "rate": "0.02195928",
        #             "amount": "0.00167952"
        #           },
        #           {
        #             "rate": "0.02195928",
        #             "amount": "0.00167952"
        #           },
        #           {
        #             "rate": "0.02196207",
        #             "amount": "0.27704177"
        #           }
        #         ]
        #     }
        #
        # partially-filled(open order)
        #
        #     {
        #         "status": "Ok",
        #         "offerId": "d0ebefab-f4d7-11e9-8c19-0242ac11000a",
        #         "completed": False,
        #         "transactions": [
        #           {
        #             "rate": "0.02106404",
        #             "amount": "0.0019625"
        #           },
        #           {
        #             "rate": "0.02106404",
        #             "amount": "0.0019625"
        #           },
        #           {
        #             "rate": "0.02105901",
        #             "amount": "0.00975256"
        #           }
        #         ]
        #     }
        #
        id = self.safe_string_2(response, 'offerId', 'stopOfferId')
        completed = self.safe_bool(response, 'completed', False)
        status = 'closed' if completed else 'open'
        transactions = self.safe_value(response, 'transactions')
        return self.safe_order({
            'id': id,
            'info': response,
            'timestamp': None,
            'datetime': None,
            'lastTradeTimestamp': None,
            'status': status,
            'symbol': symbol,
            'type': type,
            'side': side,
            'price': price,
            'amount': amount,
            'cost': None,
            'filled': None,
            'remaining': None,
            'average': None,
            'fee': None,
            'trades': transactions,
            'clientOrderId': None,
        })

    def cancel_order(self, id: str, symbol: Str = None, params={}):
        """
        :see: https://docs.zondacrypto.exchange/reference/cancel-order
        cancels an open order
        :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_zagrava.com/#/?id=order-structure>`
        """
        side = self.safe_string(params, 'side')
        if side is None:
            raise ExchangeError(self.id + ' cancelOrder() requires a `side` parameter("buy" or "sell")')
        price = self.safe_value(params, 'price')
        if price is None:
            raise ExchangeError(self.id + ' cancelOrder() requires a `price` parameter(float or string)')
        self.load_markets()
        market = self.market(symbol)
        tradingSymbol = market['baseId'] + '-' + market['quoteId']
        request: dict = {
            'symbol': tradingSymbol,
            'id': id,
            'side': side,
            'price': price,
        }
        response = self.v1_01PrivateDeleteTradingOfferSymbolIdSidePrice(self.extend(request, params))
        # {status: "Fail", errors: ["NOT_RECOGNIZED_OFFER_TYPE"]}  -- if required params are missing
        # {status: "Ok", errors: []}
        return self.parse_order(response)

    def is_fiat(self, currency):
        fiatCurrencies: dict = {
            'USD': True,
            'EUR': True,
            'PLN': True,
        }
        return self.safe_bool(fiatCurrencies, currency, False)

    def parse_deposit_address(self, depositAddress, currency: Currency = None):
        #
        #     {
        #         "address": "33u5YAEhQbYfjHHPsfMfCoSdEjfwYjVcBE",
        #         "currency": "BTC",
        #         "balanceId": "5d5d19e7-2265-49c7-af9a-047bcf384f21",
        #         "balanceEngine": "BITBAY",
        #         "tag": null
        #     }
        #
        currencyId = self.safe_string(depositAddress, 'currency')
        address = self.safe_string(depositAddress, 'address')
        self.check_address(address)
        return {
            'currency': self.safe_currency_code(currencyId, currency),
            'address': address,
            'tag': self.safe_string(depositAddress, 'tag'),
            'network': None,
            'info': depositAddress,
        }

    def fetch_deposit_address(self, code: str, params={}):
        """
        :see: https://docs.zondacrypto.exchange/reference/deposit-addresses-for-crypto
        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
        :param str [params.walletId]: Wallet id to filter deposit adresses.
        :returns dict: an `address structure <https://docs.ccxt_zagrava.com/#/?id=address-structure>`
        """
        self.load_markets()
        currency = self.currency(code)
        request: dict = {
            'currency': currency['id'],
        }
        response = self.v1_01PrivateGetApiPaymentsDepositsCryptoAddresses(self.extend(request, params))
        #
        #     {
        #         "status": "Ok",
        #         "data": [{
        #                 "address": "33u5YAEhQbYfjHHPsfMfCoSdEjfwYjVcBE",
        #                 "currency": "BTC",
        #                 "balanceId": "5d5d19e7-2265-49c7-af9a-047bcf384f21",
        #                 "balanceEngine": "BITBAY",
        #                 "tag": null
        #             }
        #         ]
        #     }
        #
        data = self.safe_value(response, 'data')
        first = self.safe_dict(data, 0)
        return self.parse_deposit_address(first, currency)

    def fetch_deposit_addresses(self, codes: Strings = None, params={}):
        """
        :see: https://docs.zondacrypto.exchange/reference/deposit-addresses-for-crypto
        fetch deposit addresses for multiple currencies and chain types
        :param str[]|None codes: zonda does not support filtering filtering by multiple codes and will ignore self parameter.
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `address structures <https://docs.ccxt_zagrava.com/#/?id=address-structure>`
        """
        self.load_markets()
        response = self.v1_01PrivateGetApiPaymentsDepositsCryptoAddresses(params)
        #
        #     {
        #         "status": "Ok",
        #         "data": [{
        #                 "address": "33u5YAEhQbYfjHHPsfMfCoSdEjfwYjVcBE",
        #                 "currency": "BTC",
        #                 "balanceId": "5d5d19e7-2265-49c7-af9a-047bcf384f21",
        #                 "balanceEngine": "BITBAY",
        #                 "tag": null
        #             }
        #         ]
        #     }
        #
        data = self.safe_list(response, 'data')
        return self.parse_deposit_addresses(data, codes)

    def transfer(self, code: str, amount: float, fromAccount: str, toAccount: str, params={}) -> TransferEntry:
        """
        :see: https://docs.zondacrypto.exchange/reference/internal-transfer
        transfer currency internally between wallets on the same account
        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account to transfer from
        :param str toAccount: account to transfer to
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transfer structure <https://docs.ccxt_zagrava.com/#/?id=transfer-structure>`
        """
        self.load_markets()
        currency = self.currency(code)
        request: dict = {
            'source': fromAccount,
            'destination': toAccount,
            'currency': code,
            'funds': self.currency_to_precision(code, amount),
        }
        response = self.v1_01PrivatePostBalancesBITBAYBalanceTransferSourceDestination(self.extend(request, params))
        #
        #     {
        #         "status": "Ok",
        #         "from": {
        #             "id": "ad9397c5-3bd9-4372-82ba-22da6a90cb56",
        #             "userId": "4bc43956-423f-47fd-9faa-acd37c58ed9f",
        #             "availableFunds": 0.01803472,
        #             "totalFunds": 0.01804161,
        #             "lockedFunds": 0.00000689,
        #             "currency": "BTC",
        #             "type": "CRYPTO",
        #             "name": "BTC",
        #             "balanceEngine": "BITBAY"
        #         },
        #         "to": {
        #             "id": "01931d52-536b-4ca5-a9f4-be28c86d0cc3",
        #             "userId": "4bc43956-423f-47fd-9faa-acd37c58ed9f",
        #             "availableFunds": 0.0001,
        #             "totalFunds": 0.0001,
        #             "lockedFunds": 0,
        #             "currency": "BTC",
        #             "type": "CRYPTO",
        #             "name": "Prowizja",
        #             "balanceEngine": "BITBAY"
        #         },
        #         "errors": null
        #     }
        #
        transfer = self.parse_transfer(response, currency)
        transferOptions = self.safe_value(self.options, 'transfer', {})
        fillResponseFromRequest = self.safe_bool(transferOptions, 'fillResponseFromRequest', True)
        if fillResponseFromRequest:
            transfer['amount'] = amount
        return transfer

    def parse_transfer(self, transfer: dict, currency: Currency = None) -> TransferEntry:
        #
        #     {
        #         "status": "Ok",
        #         "from": {
        #             "id": "ad9397c5-3bd9-4372-82ba-22da6a90cb56",
        #             "userId": "4bc43956-423f-47fd-9faa-acd37c58ed9f",
        #             "availableFunds": 0.01803472,
        #             "totalFunds": 0.01804161,
        #             "lockedFunds": 0.00000689,
        #             "currency": "BTC",
        #             "type": "CRYPTO",
        #             "name": "BTC",
        #             "balanceEngine": "BITBAY"
        #         },
        #         "to": {
        #             "id": "01931d52-536b-4ca5-a9f4-be28c86d0cc3",
        #             "userId": "4bc43956-423f-47fd-9faa-acd37c58ed9f",
        #             "availableFunds": 0.0001,
        #             "totalFunds": 0.0001,
        #             "lockedFunds": 0,
        #             "currency": "BTC",
        #             "type": "CRYPTO",
        #             "name": "Prowizja",
        #             "balanceEngine": "BITBAY"
        #         },
        #         "errors": null
        #     }
        #
        status = self.safe_string(transfer, 'status')
        fromAccount = self.safe_value(transfer, 'from', {})
        fromId = self.safe_string(fromAccount, 'id')
        to = self.safe_value(transfer, 'to', {})
        toId = self.safe_string(to, 'id')
        currencyId = self.safe_string(fromAccount, 'currency')
        return {
            'info': transfer,
            'id': None,
            'timestamp': None,
            'datetime': None,
            'currency': self.safe_currency_code(currencyId, currency),
            'amount': None,
            'fromAccount': fromId,
            'toAccount': toId,
            'status': self.parse_transfer_status(status),
        }

    def parse_transfer_status(self, status: Str) -> Str:
        statuses: dict = {
            'Ok': 'ok',
            'Fail': 'failed',
        }
        return self.safe_string(statuses, status, status)

    def withdraw(self, code: str, amount: float, address: str, tag=None, params={}):
        """
        :see: https://docs.zondacrypto.exchange/reference/crypto-withdrawal-1
        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_zagrava.com/#/?id=transaction-structure>`
        """
        tag, params = self.handle_withdraw_tag_and_params(tag, params)
        self.check_address(address)
        self.load_markets()
        response = None
        currency = self.currency(code)
        request: dict = {
            'currency': currency['id'],
            'amount': amount,
            'address': address,
            # request['balanceId'] = params['balanceId']  # Wallet id used for withdrawal. If not provided, any BITBAY wallet with sufficient funds is used. If BITBAYPAY wallet should be used parameter must be explicitly specified.
        }
        if self.is_fiat(code):
            # request['swift'] = params['swift']  # Bank identifier, if required.
            response = self.v1_01PrivatePostApiPaymentsWithdrawalsFiat(self.extend(request, params))
        else:
            if tag is not None:
                request['tag'] = tag
            response = self.v1_01PrivatePostApiPaymentsWithdrawalsCrypto(self.extend(request, params))
        #
        #     {
        #         "status": "Ok",
        #         "data": {
        #           "id": "65e01087-afb0-4ab2-afdb-cc925e360296"
        #         }
        #     }
        #
        data = self.safe_dict(response, 'data')
        return self.parse_transaction(data, currency)

    def parse_transaction(self, transaction: dict, currency: Currency = None) -> Transaction:
        #
        # withdraw
        #
        #     {
        #         "id": "65e01087-afb0-4ab2-afdb-cc925e360296"
        #     }
        #
        currency = self.safe_currency(None, currency)
        return {
            'id': self.safe_string(transaction, 'id'),
            'txid': None,
            'timestamp': None,
            'datetime': None,
            'network': None,
            'addressFrom': None,
            'address': None,
            'addressTo': None,
            'amount': None,
            'type': None,
            'currency': currency['code'],
            'status': None,
            'updated': None,
            'tagFrom': None,
            'tag': None,
            'tagTo': None,
            'comment': None,
            'internal': None,
            'fee': None,
            'info': transaction,
        }

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = self.implode_hostname(self.urls['api'][api])
        if api == 'public':
            query = self.omit(params, self.extract_params(path))
            url += '/' + self.implode_params(path, params) + '.json'
            if query:
                url += '?' + self.urlencode(query)
        elif api == 'v1_01Public':
            query = self.omit(params, self.extract_params(path))
            url += '/' + self.implode_params(path, params)
            if query:
                url += '?' + self.urlencode(query)
        elif api == 'v1_01Private':
            self.check_required_credentials()
            query = self.omit(params, self.extract_params(path))
            url += '/' + self.implode_params(path, params)
            nonce = str(self.milliseconds())
            payload: Str = None
            if method != 'POST':
                if query:
                    url += '?' + self.urlencode(query)
                payload = self.apiKey + nonce
            elif body is None:
                body = self.json(query)
                payload = self.apiKey + nonce + body
            headers = {
                'Request-Timestamp': nonce,
                'Operation-Id': self.uuid(),
                'API-Key': self.apiKey,
                'API-Hash': self.hmac(self.encode(payload), self.encode(self.secret), hashlib.sha512),
                'Content-Type': 'application/json',
            }
        else:
            self.check_required_credentials()
            body = self.urlencode(self.extend({
                'method': path,
                'moment': self.nonce(),
            }, params))
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'API-Key': self.apiKey,
                'API-Hash': self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512),
            }
        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
        if 'code' in response:
            #
            # bitbay returns the integer "success": 1 key from their private API
            # or an integer "code" value from 0 to 510 and an error message
            #
            #      {"success": 1, ...}
            #      {'code': 502, "message": "Invalid sign"}
            #      {'code': 0, "message": "offer funds not exceeding minimums"}
            #
            #      400 At least one parameter wasn't set
            #      401 Invalid order type
            #      402 No orders with specified currencies
            #      403 Invalid payment currency name
            #      404 Error. Wrong transaction type
            #      405 Order with self id doesn't exist
            #      406 No enough money or crypto
            #      408 Invalid currency name
            #      501 Invalid public key
            #      502 Invalid sign
            #      503 Invalid moment parameter. Request time doesn't match current server time
            #      504 Invalid method
            #      505 Key has no permission for self action
            #      506 Account locked. Please contact with customer service
            #      509 The BIC/SWIFT is required for self currency
            #      510 Invalid market name
            #
            code = self.safe_string(response, 'code')  # always an integer
            feedback = self.id + ' ' + body
            self.throw_exactly_matched_exception(self.exceptions, code, feedback)
            raise ExchangeError(feedback)
        elif 'status' in response:
            #
            #      {"status":"Fail","errors":["OFFER_FUNDS_NOT_EXCEEDING_MINIMUMS"]}
            #
            status = self.safe_string(response, 'status')
            if status == 'Fail':
                errors = self.safe_value(response, 'errors')
                feedback = self.id + ' ' + body
                for i in range(0, len(errors)):
                    error = errors[i]
                    self.throw_exactly_matched_exception(self.exceptions, error, feedback)
                raise ExchangeError(feedback)
        return None
