# -*- 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.abstract.luno import ImplicitAPI
from ccxt.base.types import Account, Any, Balances, Currencies, Currency, DepositAddress, Int, LedgerEntry, Market, Num, Order, OrderBook, OrderSide, OrderType, Str, Strings, Ticker, Tickers, Trade, TradingFeeInterface
from typing import List
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class luno(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(luno, self).describe(), {
            'id': 'luno',
            'name': 'luno',
            'countries': ['GB', 'SG', 'ZA'],
            # 300 calls per minute = 5 calls per second = 1000ms / 5 = 200ms between requests
            'rateLimit': 200,
            'version': '1',
            'pro': True,
            'has': {
                'CORS': None,
                'spot': True,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'addMargin': False,
                'borrowCrossMargin': False,
                'borrowIsolatedMargin': False,
                'borrowMargin': False,
                'cancelOrder': True,
                'closeAllPositions': False,
                'closePosition': False,
                'createDepositAddress': True,
                'createOrder': True,
                'createReduceOnlyOrder': False,
                'fetchAccounts': True,
                'fetchAllGreeks': False,
                'fetchBalance': True,
                'fetchBorrowInterest': False,
                'fetchBorrowRate': False,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchBorrowRates': False,
                'fetchBorrowRatesPerSymbol': False,
                'fetchClosedOrders': True,
                'fetchCrossBorrowRate': False,
                'fetchCrossBorrowRates': False,
                'fetchCurrencies': True,
                'fetchDepositAddress': True,
                'fetchFundingHistory': False,
                'fetchFundingInterval': False,
                'fetchFundingIntervals': False,
                'fetchFundingRate': False,
                'fetchFundingRateHistory': False,
                'fetchFundingRates': False,
                'fetchGreeks': False,
                'fetchIndexOHLCV': False,
                'fetchIsolatedBorrowRate': False,
                'fetchIsolatedBorrowRates': False,
                'fetchIsolatedPositions': False,
                'fetchLedger': True,
                'fetchLeverage': False,
                'fetchLeverages': False,
                'fetchLeverageTiers': False,
                'fetchLiquidations': False,
                'fetchLongShortRatio': False,
                'fetchLongShortRatioHistory': False,
                'fetchMarginAdjustmentHistory': False,
                'fetchMarginMode': False,
                'fetchMarginModes': False,
                'fetchMarketLeverageTiers': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMarkPrice': False,
                'fetchMarkPrices': False,
                'fetchMyLiquidations': False,
                'fetchMySettlementHistory': False,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenInterest': False,
                'fetchOpenInterestHistory': False,
                'fetchOpenInterests': False,
                'fetchOpenOrders': True,
                'fetchOption': False,
                'fetchOptionChain': False,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrders': True,
                'fetchPosition': False,
                'fetchPositionForSymbolWs': False,
                'fetchPositionHistory': False,
                'fetchPositionMode': False,
                'fetchPositions': False,
                'fetchPositionsForSymbol': False,
                'fetchPositionsForSymbolWs': False,
                'fetchPositionsHistory': False,
                'fetchPositionsRisk': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchSettlementHistory': False,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTrades': True,
                'fetchTradingFee': True,
                'fetchTradingFees': False,
                'fetchUnderlyingAssets': False,
                'fetchVolatilityHistory': False,
                'reduceMargin': False,
                'repayCrossMargin': False,
                'repayIsolatedMargin': False,
                'setLeverage': False,
                'setMargin': False,
                'setMarginMode': False,
                'setPositionMode': False,
            },
            'urls': {
                'referral': 'https://www.luno.com/invite/44893A',
                'logo': 'https://user-images.githubusercontent.com/1294454/27766607-8c1a69d8-5ede-11e7-930c-540b5eb9be24.jpg',
                'api': {
                    'public': 'https://api.luno.com/api',
                    'private': 'https://api.luno.com/api',
                    'exchange': 'https://api.luno.com/api/exchange',
                    'exchangePrivate': 'https://api.luno.com/api/exchange',
                },
                'www': 'https://www.luno.com',
                'doc': [
                    'https://www.luno.com/en/api',
                    'https://npmjs.org/package/bitx',
                    'https://github.com/bausmeier/node-bitx',
                ],
            },
            'api': {
                'exchange': {
                    'get': {
                        'markets': 1,
                    },
                },
                'exchangePrivate': {
                    'get': {
                        'candles': 1,
                    },
                },
                'public': {
                    'get': {
                        'orderbook': 1,
                        'orderbook_top': 1,
                        'ticker': 1,
                        'tickers': 1,
                        'trades': 1,
                    },
                },
                'private': {
                    'get': {
                        'accounts/{id}/pending': 1,
                        'accounts/{id}/transactions': 1,
                        'balance': 1,
                        'beneficiaries': 1,
                        'send/networks': 1,
                        'fee_info': 1,
                        'funding_address': 1,
                        'listorders': 1,
                        'listtrades': 1,
                        'send_fee': 1,
                        'orders/{id}': 1,
                        'withdrawals': 1,
                        'withdrawals/{id}': 1,
                        'transfers': 1,
                        # GET /api/exchange/1/move
                        # GET /api/exchange/1/move/list_moves
                        # GET /api/exchange/1/candles
                        # GET /api/exchange/1/transfers
                        # GET /api/exchange/2/listorders
                        # GET /api/exchange/2/orders/{id}
                        # GET /api/exchange/3/order
                    },
                    'post': {
                        'accounts': 1,
                        'address/validate': 1,
                        'postorder': 1,
                        'marketorder': 1,
                        'stoporder': 1,
                        'funding_address': 1,
                        'withdrawals': 1,
                        'send': 1,
                        'oauth2/grant': 1,
                        'beneficiaries': 1,
                        # POST /api/exchange/1/move
                    },
                    'put': {
                        'accounts/{id}/name': 1,
                    },
                    'delete': {
                        'withdrawals/{id}': 1,
                        'beneficiaries/{id}': 1,
                    },
                },
            },
            'timeframes': {
                '1m': 60,
                '5m': 300,
                '15m': 900,
                '30m': 1800,
                '1h': 3600,
                '3h': 10800,
                '4h': 14400,
                '1d': 86400,
                '3d': 259200,
                '1w': 604800,
            },
            'fees': {
                'trading': {
                    'tierBased': True,  # based on volume from your primary currency(not the same for everyone)
                    'percentage': True,
                    'taker': self.parse_number('0.001'),
                    'maker': self.parse_number('0'),
                },
            },
            'precisionMode': TICK_SIZE,
            'features': {
                'spot': {
                    'sandbox': False,
                    'fetchCurrencies': {
                        'private': True,
                    },
                    'createOrder': {
                        'marginMode': False,
                        'triggerPrice': True,  # todo
                        'triggerPriceType': None,
                        'triggerDirection': True,  # todo
                        'stopLossPrice': False,  # todo
                        'takeProfitPrice': False,  # todo
                        'attachedStopLossTakeProfit': None,
                        'timeInForce': {
                            'IOC': True,
                            'FOK': True,
                            'PO': True,
                            'GTD': False,
                        },
                        'hedged': False,
                        'trailing': False,
                        'leverage': False,
                        'marketBuyByCost': True,
                        'marketBuyRequiresPrice': False,
                        'selfTradePrevention': False,
                        'iceberg': False,
                    },
                    'createOrders': None,
                    'fetchMyTrades': {
                        'marginMode': False,
                        'limit': 1000,
                        'daysBack': 100000,  # todo
                        'untilDays': 100000,  # todo
                        'symbolRequired': True,
                    },
                    'fetchOrder': {
                        'marginMode': False,
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOpenOrders': {
                        'marginMode': False,
                        'limit': 1000,
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOrders': {
                        'marginMode': False,
                        'limit': 1000,
                        'daysBack': 100000,
                        'untilDays': None,
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchClosedOrders': {
                        'marginMode': False,
                        'limit': 1000,
                        'daysBack': 100000,
                        'daysBackCanceled': 1,
                        'untilDays': None,
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOHLCV': {
                        'limit': None,
                    },
                },
                'swap': {
                    'linear': None,
                    'inverse': None,
                },
                'future': {
                    'linear': None,
                    'inverse': None,
                },
            },
            'rollingWindowSize': 60000.0,
        })

    async def fetch_currencies(self, params={}) -> Currencies:
        """
        fetches all available currencies on an exchange
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        """
        if not self.check_required_credentials(False):
            return {}
        response = await self.privateGetSendNetworks(params)
        #
        #     {
        #         "networks": [
        #           {
        #             "id": 0,
        #             "name": "Ethereum",
        #             "native_currency": "ETH"
        #           },
        #           ...
        #         ]
        #     }
        #
        currenciesData = self.safe_list(response, 'data', [])
        result: dict = {}
        for i in range(0, len(currenciesData)):
            networkEntry = currenciesData[i]
            id = self.safe_string(networkEntry, 'native_currency')
            code = self.safe_currency_code(id)
            if not (code in result):
                result[code] = {
                    'id': id,
                    'code': code,
                    'precision': None,
                    'type': None,
                    'name': None,
                    'active': None,
                    'deposit': None,
                    'withdraw': None,
                    'fee': None,
                    'limits': {
                        'withdraw': {
                            'min': None,
                            'max': None,
                        },
                        'deposit': {
                            'min': None,
                            'max': None,
                        },
                    },
                    'networks': {},
                    'info': {},
                }
            networkId = self.safe_string(networkEntry, 'name')
            networkCode = self.network_id_to_code(networkId)
            result[code]['networks'][networkCode] = {
                'id': networkId,
                'network': networkCode,
                'limits': {
                    'withdraw': {
                        'min': None,
                        'max': None,
                    },
                    'deposit': {
                        'min': None,
                        'max': None,
                    },
                },
                'active': None,
                'deposit': None,
                'withdraw': None,
                'fee': None,
                'precision': None,
                'info': networkEntry,
            }
            # add entry in info
            info = self.safe_list(result[code], 'info', [])
            info.append(networkEntry)
            result[code]['info'] = info
        # only after all entries are formed in currencies, restructure each entry
        allKeys = list(result.keys())
        for i in range(0, len(allKeys)):
            code = allKeys[i]
            result[code] = self.safe_currency_structure(result[code])  # self is needed after adding network entry
        return result

    async def fetch_markets(self, params={}) -> List[Market]:
        """
        retrieves data on all markets for luno

        https://www.luno.com/en/developers/api#tag/Market/operation/Markets

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = await self.exchangeGetMarkets(params)
        #
        #     {
        #         "markets":[
        #             {
        #                 "market_id":"BCHXBT",
        #                 "trading_status":"ACTIVE",
        #                 "base_currency":"BCH",
        #                 "counter_currency":"XBT",
        #                 "min_volume":"0.01",
        #                 "max_volume":"100.00",
        #                 "volume_scale":2,
        #                 "min_price":"0.0001",
        #                 "max_price":"1.00",
        #                 "price_scale":6,
        #                 "fee_scale":8,
        #             },
        #         ]
        #     }
        #
        result = []
        markets = self.safe_value(response, 'markets', [])
        for i in range(0, len(markets)):
            market = markets[i]
            id = self.safe_string(market, 'market_id')
            baseId = self.safe_string(market, 'base_currency')
            quoteId = self.safe_string(market, 'counter_currency')
            base = self.safe_currency_code(baseId)
            quote = self.safe_currency_code(quoteId)
            status = self.safe_string(market, 'trading_status')
            result.append({
                'id': id,
                'symbol': base + '/' + quote,
                'base': base,
                'quote': quote,
                'settle': None,
                'baseId': baseId,
                'quoteId': quoteId,
                'settleId': None,
                'type': 'spot',
                'spot': True,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'active': (status == 'ACTIVE'),
                'contract': False,
                'linear': None,
                'inverse': None,
                'contractSize': None,
                'expiry': None,
                'expiryDatetime': None,
                'strike': None,
                'optionType': None,
                'precision': {
                    'amount': self.parse_number(self.parse_precision(self.safe_string(market, 'volume_scale'))),
                    'price': self.parse_number(self.parse_precision(self.safe_string(market, 'price_scale'))),
                },
                'limits': {
                    'leverage': {
                        'min': None,
                        'max': None,
                    },
                    'amount': {
                        'min': self.safe_number(market, 'min_volume'),
                        'max': self.safe_number(market, 'max_volume'),
                    },
                    'price': {
                        'min': self.safe_number(market, 'min_price'),
                        'max': self.safe_number(market, 'max_price'),
                    },
                    'cost': {
                        'min': None,
                        'max': None,
                    },
                },
                'created': None,
                'info': market,
            })
        return result

    async def fetch_accounts(self, params={}) -> List[Account]:
        """
        fetch all the accounts associated with a profile

        https://www.luno.com/en/developers/api#tag/Accounts/operation/getBalances

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `account structures <https://docs.ccxt.com/?id=account-structure>` indexed by the account type
        """
        response = await self.privateGetBalance(params)
        wallets = self.safe_value(response, 'balance', [])
        result = []
        for i in range(0, len(wallets)):
            account = wallets[i]
            accountId = self.safe_string(account, 'account_id')
            currencyId = self.safe_string(account, 'asset')
            code = self.safe_currency_code(currencyId)
            result.append({
                'id': accountId,
                'type': None,
                'currency': code,
                'info': account,
            })
        return result

    def parse_balance(self, response) -> Balances:
        wallets = self.safe_value(response, 'balance', [])
        result: dict = {
            'info': response,
            'timestamp': None,
            'datetime': None,
        }
        for i in range(0, len(wallets)):
            wallet = wallets[i]
            currencyId = self.safe_string(wallet, 'asset')
            code = self.safe_currency_code(currencyId)
            reserved = self.safe_string(wallet, 'reserved')
            unconfirmed = self.safe_string(wallet, 'unconfirmed')
            balance = self.safe_string(wallet, 'balance')
            reservedUnconfirmed = Precise.string_add(reserved, unconfirmed)
            balanceUnconfirmed = Precise.string_add(balance, unconfirmed)
            if code in result:
                result[code]['used'] = Precise.string_add(result[code]['used'], reservedUnconfirmed)
                result[code]['total'] = Precise.string_add(result[code]['total'], balanceUnconfirmed)
            else:
                account = self.account()
                account['used'] = reservedUnconfirmed
                account['total'] = balanceUnconfirmed
                result[code] = account
        return self.safe_balance(result)

    async def fetch_balance(self, params={}) -> Balances:
        """
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://www.luno.com/en/developers/api#tag/Accounts/operation/getBalances

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/?id=balance-structure>`
        """
        await self.load_markets()
        response = await self.privateGetBalance(params)
        #
        #     {
        #         "balance": [
        #             {'account_id': '119...1336','asset': 'XBT','balance': '0.00','reserved': '0.00',"unconfirmed": "0.00"},
        #             {'account_id': '66...289','asset': 'XBT','balance': '0.00','reserved': '0.00',"unconfirmed": "0.00"},
        #             {'account_id': '718...5300','asset': 'ETH','balance': '0.00','reserved': '0.00',"unconfirmed": "0.00"},
        #             {'account_id': '818...7072','asset': 'ZAR','balance': '0.001417','reserved': '0.00',"unconfirmed": "0.00"}]}
        #         ]
        #     }
        #
        return self.parse_balance(response)

    async def fetch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
        """
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://www.luno.com/en/developers/api#tag/Market/operation/GetOrderBookFull
        https://www.luno.com/en/developers/api#tag/Market/operation/GetOrderBook

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'pair': market['id'],
        }
        response = None
        if limit is not None and limit <= 100:
            response = await self.publicGetOrderbookTop(self.extend(request, params))
        else:
            response = await self.publicGetOrderbook(self.extend(request, params))
        timestamp = self.safe_integer(response, 'timestamp')
        return self.parse_order_book(response, market['symbol'], timestamp, 'bids', 'asks', 'price', 'volume')

    def parse_order_status(self, status: Str):
        statuses: dict = {
            # todo add other statuses
            'PENDING': 'open',
        }
        return self.safe_string(statuses, status, status)

    def parse_order(self, order: dict, market: Market = None) -> Order:
        #
        #     {
        #         "base": "string",
        #         "completed_timestamp": "string",
        #         "counter": "string",
        #         "creation_timestamp": "string",
        #         "expiration_timestamp": "string",
        #         "fee_base": "string",
        #         "fee_counter": "string",
        #         "limit_price": "string",
        #         "limit_volume": "string",
        #         "order_id": "string",
        #         "pair": "string",
        #         "state": "PENDING",
        #         "type": "BID"
        #     }
        #
        timestamp = self.safe_integer(order, 'creation_timestamp')
        status = self.parse_order_status(self.safe_string(order, 'state'))
        status = status if (status == 'open') else status
        side = None
        orderType = self.safe_string(order, 'type')
        if (orderType == 'ASK') or (orderType == 'SELL'):
            side = 'sell'
        elif (orderType == 'BID') or (orderType == 'BUY'):
            side = 'buy'
        marketId = self.safe_string(order, 'pair')
        market = self.safe_market(marketId, market)
        price = self.safe_string(order, 'limit_price')
        amount = self.safe_string(order, 'limit_volume')
        quoteFee = self.safe_number(order, 'fee_counter')
        baseFee = self.safe_number(order, 'fee_base')
        filled = self.safe_string(order, 'base')
        cost = self.safe_string(order, 'counter')
        fee = None
        if quoteFee is not None:
            fee = {
                'cost': quoteFee,
                'currency': market['quote'],
            }
        elif baseFee is not None:
            fee = {
                'cost': baseFee,
                'currency': market['base'],
            }
        id = self.safe_string(order, 'order_id')
        return self.safe_order({
            'id': id,
            'clientOrderId': None,
            'datetime': self.iso8601(timestamp),
            'timestamp': timestamp,
            'lastTradeTimestamp': None,
            'status': status,
            'symbol': market['symbol'],
            'type': None,
            'timeInForce': None,
            'postOnly': None,
            'side': side,
            'price': price,
            'triggerPrice': None,
            'amount': amount,
            'filled': filled,
            'cost': cost,
            'remaining': None,
            'trades': None,
            'fee': fee,
            'info': order,
            'average': None,
        }, market)

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

        https://www.luno.com/en/developers/api#tag/Orders/operation/GetOrder

        :param str id: order id
        :param str symbol: not used by luno fetchOrder
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/?id=order-structure>`
        """
        await self.load_markets()
        request: dict = {
            'id': id,
        }
        response = await self.privateGetOrdersId(self.extend(request, params))
        return self.parse_order(response)

    async def fetch_orders_by_state(self, state: Str, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        await self.load_markets()
        request: dict = {}
        market = None
        if state is not None:
            request['state'] = state
        if symbol is not None:
            market = self.market(symbol)
            request['pair'] = market['id']
        response = await self.privateGetListorders(self.extend(request, params))
        orders = self.safe_list(response, 'orders', [])
        return self.parse_orders(orders, market, since, limit)

    async def fetch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
        fetches information on multiple orders made by the user

        https://www.luno.com/en/developers/api#tag/Orders/operation/ListOrders

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        """
        return await self.fetch_orders_by_state(None, symbol, since, limit, params)

    async def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
        fetch all unfilled currently open orders

        https://www.luno.com/en/developers/api#tag/Orders/operation/ListOrders

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of  open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        """
        return await self.fetch_orders_by_state('PENDING', symbol, since, limit, params)

    async def fetch_closed_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
        fetches information on multiple closed orders made by the user

        https://www.luno.com/en/developers/api#tag/Orders/operation/ListOrders

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        """
        return await self.fetch_orders_by_state('COMPLETE', symbol, since, limit, params)

    def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
        # {
        #     "pair":"XBTAUD",
        #     "timestamp":1642201439301,
        #     "bid":"59972.30000000",
        #     "ask":"59997.99000000",
        #     "last_trade":"59997.99000000",
        #     "rolling_24_hour_volume":"1.89510000",
        #     "status":"ACTIVE"
        # }
        timestamp = self.safe_integer(ticker, 'timestamp')
        marketId = self.safe_string(ticker, 'pair')
        symbol = self.safe_symbol(marketId, market)
        last = self.safe_string(ticker, 'last_trade')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': None,
            'low': None,
            'bid': self.safe_string(ticker, 'bid'),
            'bidVolume': None,
            'ask': self.safe_string(ticker, 'ask'),
            'askVolume': None,
            'vwap': None,
            'open': None,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': None,
            'percentage': None,
            'average': None,
            'baseVolume': self.safe_string(ticker, 'rolling_24_hour_volume'),
            'quoteVolume': None,
            'info': ticker,
        }, market)

    async def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
        """
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://www.luno.com/en/developers/api#tag/Market/operation/GetTickers

        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/?id=ticker-structure>`
        """
        await self.load_markets()
        symbols = self.market_symbols(symbols)
        response = await self.publicGetTickers(params)
        tickers = self.index_by(response['tickers'], 'pair')
        ids = list(tickers.keys())
        result: dict = {}
        for i in range(0, len(ids)):
            id = ids[i]
            market = self.safe_market(id)
            symbol = market['symbol']
            ticker = tickers[id]
            result[symbol] = self.parse_ticker(ticker, market)
        return self.filter_by_array_tickers(result, 'symbol', symbols)

    async def fetch_ticker(self, symbol: str, params={}) -> Ticker:
        """
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://www.luno.com/en/developers/api#tag/Market/operation/GetTicker

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'pair': market['id'],
        }
        response = await self.publicGetTicker(self.extend(request, params))
        # {
        #     "pair":"XBTAUD",
        #     "timestamp":1642201439301,
        #     "bid":"59972.30000000",
        #     "ask":"59997.99000000",
        #     "last_trade":"59997.99000000",
        #     "rolling_24_hour_volume":"1.89510000",
        #     "status":"ACTIVE"
        # }
        return self.parse_ticker(response, market)

    def parse_trade(self, trade: dict, market: Market = None) -> Trade:
        #
        # fetchTrades(public)
        #
        #      {
        #          "sequence":276989,
        #          "timestamp":1648651276949,
        #          "price":"35773.20000000",
        #          "volume":"0.00300000",
        #          "is_buy":false
        #      }
        #
        # fetchMyTrades(private)
        #
        #      {
        #          "pair":"LTCXBT",
        #          "sequence":3256813,
        #          "order_id":"BXEX6XHHDT5EGW2",
        #          "type":"ASK",
        #          "timestamp":1648652135235,
        #          "price":"0.002786",
        #          "volume":"0.10",
        #          "base":"0.10",
        #          "counter":"0.0002786",
        #          "fee_base":"0.0001",
        #          "fee_counter":"0.00",
        #          "is_buy":false,
        #          "client_order_id":""
        #      }
        #
        # For public trade data(is_buy is True) indicates 'buy' side but for private trade data
        # is_buy indicates maker or taker. The value of "type"(ASK/BID) indicate sell/buy side.
        # Private trade data includes ID field which public trade data does not.
        orderId = self.safe_string(trade, 'order_id')
        id = self.safe_string(trade, 'sequence')
        takerOrMaker = None
        side = None
        if orderId is not None:
            type = self.safe_string(trade, 'type')
            if (type == 'ASK') or (type == 'SELL'):
                side = 'sell'
            elif (type == 'BID') or (type == 'BUY'):
                side = 'buy'
            if side == 'sell' and trade['is_buy']:
                takerOrMaker = 'maker'
            elif side == 'buy' and not trade['is_buy']:
                takerOrMaker = 'maker'
            else:
                takerOrMaker = 'taker'
        else:
            side = 'buy' if trade['is_buy'] else 'sell'
        feeBaseString = self.safe_string(trade, 'fee_base')
        feeCounterString = self.safe_string(trade, 'fee_counter')
        feeCurrency = None
        feeCost = None
        if feeBaseString is not None:
            if not Precise.string_equals(feeBaseString, '0.0'):
                feeCurrency = market['base']
                feeCost = feeBaseString
        elif feeCounterString is not None:
            if not Precise.string_equals(feeCounterString, '0.0'):
                feeCurrency = market['quote']
                feeCost = feeCounterString
        timestamp = self.safe_integer(trade, 'timestamp')
        return self.safe_trade({
            'info': trade,
            'id': id,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': market['symbol'],
            'order': orderId,
            'type': None,
            'side': side,
            'takerOrMaker': takerOrMaker,
            'price': self.safe_string(trade, 'price'),
            'amount': self.safe_string_2(trade, 'volume', 'base'),
            # Does not include potential fee costs
            'cost': self.safe_string(trade, 'counter'),
            'fee': {
                'cost': feeCost,
                'currency': feeCurrency,
            },
        }, market)

    async def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
        """
        get the list of most recent trades for a particular symbol

        https://www.luno.com/en/developers/api#tag/Market/operation/ListTrades

        :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.com/?id=public-trades>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'pair': market['id'],
        }
        if since is not None:
            request['since'] = since
        response = await self.publicGetTrades(self.extend(request, params))
        #
        #      {
        #          "trades":[
        #              {
        #                  "sequence":276989,
        #                  "timestamp":1648651276949,
        #                  "price":"35773.20000000",
        #                  "volume":"0.00300000",
        #                  "is_buy":false
        #              },...
        #          ]
        #      }
        #
        trades = self.safe_list(response, 'trades', [])
        return self.parse_trades(trades, market, since, limit)

    async def fetch_ohlcv(self, symbol: str, timeframe: str = '1m', since: Int = None, limit: Int = None, params={}):
        """

        https://www.luno.com/en/developers/api#tag/Market/operation/GetCandles

        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 luno api endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'duration': self.safe_value(self.timeframes, timeframe, timeframe),
            'pair': market['id'],
        }
        if since is not None:
            request['since'] = self.parse_to_int(since)
        else:
            duration = 1000 * 1000 * self.parse_timeframe(timeframe)
            request['since'] = self.milliseconds() - duration
        response = await self.exchangePrivateGetCandles(self.extend(request, params))
        #
        #     {
        #          "candles": [
        #              {
        #                  "timestamp": 1664055240000,
        #                  "open": "19612.65",
        #                  "close": "19612.65",
        #                  "high": "19612.65",
        #                  "low": "19612.65",
        #                  "volume": "0.00"
        #              },...
        #          ],
        #          "duration": 60,
        #          "pair": "XBTEUR"
        #     }
        #
        ohlcvs = self.safe_list(response, 'candles', [])
        return self.parse_ohlcvs(ohlcvs, market, timeframe, since, limit)

    def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
        # {
        #     "timestamp": 1664055240000,
        #     "open": "19612.65",
        #     "close": "19612.65",
        #     "high": "19612.65",
        #     "low": "19612.65",
        #     "volume": "0.00"
        # }
        return [
            self.safe_integer(ohlcv, 'timestamp'),
            self.safe_number(ohlcv, 'open'),
            self.safe_number(ohlcv, 'high'),
            self.safe_number(ohlcv, 'low'),
            self.safe_number(ohlcv, 'close'),
            self.safe_number(ohlcv, 'volume'),
        ]

    async def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        fetch all trades made by the user

        https://www.luno.com/en/developers/api#tag/Orders/operation/ListUserTrades

        :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.com/?id=trade-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchMyTrades() requires a symbol argument')
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'pair': market['id'],
        }
        if since is not None:
            request['since'] = since
        if limit is not None:
            request['limit'] = limit
        response = await self.privateGetListtrades(self.extend(request, params))
        #
        #      {
        #          "trades":[
        #              {
        #                  "pair":"LTCXBT",
        #                  "sequence":3256813,
        #                  "order_id":"BXEX6XHHDT5EGW2",
        #                  "type":"ASK",
        #                  "timestamp":1648652135235,
        #                  "price":"0.002786",
        #                  "volume":"0.10",
        #                  "base":"0.10",
        #                  "counter":"0.0002786",
        #                  "fee_base":"0.0001",
        #                  "fee_counter":"0.00",
        #                  "is_buy":false,
        #                  "client_order_id":""
        #              },...
        #          ]
        #      }
        #
        trades = self.safe_list(response, 'trades', [])
        return self.parse_trades(trades, market, since, limit)

    async def fetch_trading_fee(self, symbol: str, params={}) -> TradingFeeInterface:
        """
        fetch the trading fees for a market

        https://www.luno.com/en/developers/api#tag/Orders/operation/getFeeInfo

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/?id=fee-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'pair': market['id'],
        }
        response = await self.privateGetFeeInfo(self.extend(request, params))
        #
        #     {
        #          "maker_fee": "0.00250000",
        #          "taker_fee": "0.00500000",
        #          "thirty_day_volume": "0"
        #     }
        #
        return {
            'info': response,
            'symbol': symbol,
            'maker': self.safe_number(response, 'maker_fee'),
            'taker': self.safe_number(response, 'taker_fee'),
            'percentage': None,
            'tierBased': None,
        }

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

        https://www.luno.com/en/developers/api#tag/Orders/operation/PostMarketOrder
        https://www.luno.com/en/developers/api#tag/Orders/operation/PostLimitOrder

        :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.com/?id=order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'pair': market['id'],
        }
        response = None
        if type == 'market':
            request['type'] = side.upper()
            # todo add createMarketBuyOrderRequires price logic is implemented in the other exchanges
            if side == 'buy':
                request['counter_volume'] = self.amount_to_precision(market['symbol'], amount)
            else:
                request['base_volume'] = self.amount_to_precision(market['symbol'], amount)
            response = await self.privatePostMarketorder(self.extend(request, params))
        else:
            request['volume'] = self.amount_to_precision(market['symbol'], amount)
            request['price'] = self.price_to_precision(market['symbol'], price)
            request['type'] = 'BID' if (side == 'buy') else 'ASK'
            response = await self.privatePostPostorder(self.extend(request, params))
        return self.safe_order({
            'info': response,
            'id': response['order_id'],
        }, market)

    async def cancel_order(self, id: str, symbol: Str = None, params={}):
        """
        cancels an open order

        https://www.luno.com/en/developers/api#tag/Orders/operation/StopOrder

        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/?id=order-structure>`
        """
        await self.load_markets()
        request: dict = {
            'order_id': id,
        }
        response = await self.privatePostStoporder(self.extend(request, params))
        #
        #    {
        #        "success": True
        #    }
        #
        return self.safe_order({
            'info': response,
        })

    async def fetch_ledger_by_entries(self, code: Str = None, entry=None, limit=None, params={}):
        # by default without entry number or limit number, return most recent entry
        if entry is None:
            entry = -1
        if limit is None:
            limit = 1
        since = None
        request: dict = {
            'min_row': entry,
            'max_row': self.sum(entry, limit),
        }
        return await self.fetch_ledger(code, since, limit, self.extend(request, params))

    async def fetch_ledger(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[LedgerEntry]:
        """
        fetch the history of changes, actions done by the user or operations that altered the balance of the user

        https://www.luno.com/en/developers/api#tag/Accounts/operation/ListTransactions

        :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 entries to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ledger structure <https://docs.ccxt.com/?id=ledger-entry-structure>`
        """
        await self.load_markets()
        await self.load_accounts()
        currency = None
        id = self.safe_string(params, 'id')  # account id
        min_row = self.safe_value(params, 'min_row')
        max_row = self.safe_value(params, 'max_row')
        if id is None:
            if code is None:
                raise ArgumentsRequired(self.id + ' fetchLedger() requires a currency code argument if no account id specified in params')
            currency = self.currency(code)
            accountsByCurrencyCode = self.index_by(self.accounts, 'currency')
            account = self.safe_value(accountsByCurrencyCode, code)
            if account is None:
                raise ExchangeError(self.id + ' fetchLedger() could not find account id for ' + code)
            id = account['id']
        if min_row is None and max_row is None:
            max_row = 0  # Default to most recent transactions
            min_row = -1000  # Maximum number of records supported
        elif min_row is None or max_row is None:
            raise ExchangeError(self.id + " fetchLedger() require both params 'max_row' and 'min_row' or neither to be defined")
        if limit is not None and max_row - min_row > limit:
            if max_row <= 0:
                min_row = max_row - limit
            elif min_row > 0:
                max_row = min_row + limit
        if max_row - min_row > 1000:
            raise ExchangeError(self.id + " fetchLedger() requires the params 'max_row' - 'min_row' <= 1000")
        request: dict = {
            'id': id,
            'min_row': min_row,
            'max_row': max_row,
        }
        response = await self.privateGetAccountsIdTransactions(self.extend(params, request))
        entries = self.safe_value(response, 'transactions', [])
        return self.parse_ledger(entries, currency, since, limit)

    def parse_ledger_comment(self, comment):
        words = comment.split(' ')
        types: dict = {
            'Withdrawal': 'fee',
            'Trading': 'fee',
            'Payment': 'transaction',
            'Sent': 'transaction',
            'Deposit': 'transaction',
            'Received': 'transaction',
            'Released': 'released',
            'Reserved': 'reserved',
            'Sold': 'trade',
            'Bought': 'trade',
            'Failure': 'failed',
        }
        referenceId = None
        firstWord = self.safe_string(words, 0)
        thirdWord = self.safe_string(words, 2)
        fourthWord = self.safe_string(words, 3)
        type = self.safe_string(types, firstWord)
        if (type is None) and (thirdWord == 'fee'):
            type = 'fee'
        if (type == 'reserved') and (fourthWord == 'order'):
            referenceId = self.safe_string(words, 4)
        return {
            'type': type,
            'referenceId': referenceId,
        }

    def parse_ledger_entry(self, entry, currency: Currency = None) -> LedgerEntry:
        # details = self.safe_value(entry, 'details', {})
        id = self.safe_string(entry, 'row_index')
        account_id = self.safe_string(entry, 'account_id')
        timestamp = self.safe_integer(entry, 'timestamp')
        currencyId = self.safe_string(entry, 'currency')
        code = self.safe_currency_code(currencyId, currency)
        currency = self.safe_currency(currencyId, currency)
        available_delta = self.safe_string(entry, 'available_delta')
        balance_delta = self.safe_string(entry, 'balance_delta')
        after = self.safe_string(entry, 'balance')
        comment = self.safe_string(entry, 'description')
        before = after
        amount = '0.0'
        result = self.parse_ledger_comment(comment)
        type = result['type']
        referenceId = result['referenceId']
        direction = None
        status = None
        if not Precise.string_equals(balance_delta, '0.0'):
            before = Precise.string_sub(after, balance_delta)
            status = 'ok'
            amount = Precise.string_abs(balance_delta)
        elif Precise.string_lt(available_delta, '0.0'):
            status = 'pending'
            amount = Precise.string_abs(available_delta)
        elif Precise.string_gt(available_delta, '0.0'):
            status = 'canceled'
            amount = Precise.string_abs(available_delta)
        if Precise.string_gt(balance_delta, '0') or Precise.string_gt(available_delta, '0'):
            direction = 'in'
        elif Precise.string_lt(balance_delta, '0') or Precise.string_lt(available_delta, '0'):
            direction = 'out'
        return self.safe_ledger_entry({
            'info': entry,
            'id': id,
            'direction': direction,
            'account': account_id,
            'referenceId': referenceId,
            'referenceAccount': None,
            'type': type,
            'currency': code,
            'amount': self.parse_to_numeric(amount),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'before': self.parse_to_numeric(before),
            'after': self.parse_to_numeric(after),
            'status': status,
            'fee': None,
        }, currency)

    async def create_deposit_address(self, code: str, params={}) -> DepositAddress:
        """
        create a currency deposit address

        https://www.luno.com/en/developers/api#tag/Receive/operation/createFundingAddress

        :param str code: unified currency code of the currency for the deposit address
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.name]: an optional name for the new address
        :param int [params.account_id]: an optional account id for the new address
        :returns dict: an `address structure <https://docs.ccxt.com/?id=address-structure>`
        """
        await self.load_markets()
        currency = self.currency(code)
        request: dict = {
            'asset': currency['id'],
        }
        response = await self.privatePostFundingAddress(self.extend(request, params))
        #
        #     {
        #         "account_id": "string",
        #         "address": "string",
        #         "address_meta": [
        #             {
        #                 "label": "string",
        #                 "value": "string"
        #             }
        #         ],
        #         "asset": "string",
        #         "assigned_at": 0,
        #         "name": "string",
        #         "network": 0,
        #         "qr_code_uri": "string",
        #         "receive_fee": "string",
        #         "total_received": "string",
        #         "total_unconfirmed": "string"
        #     }
        #
        return self.parse_deposit_address(response, currency)

    async def fetch_deposit_address(self, code: str, params={}) -> DepositAddress:
        """
        fetch the deposit address for a currency associated with self account

        https://www.luno.com/en/developers/api#tag/Receive/operation/getFundingAddress

        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.address]: a specific cryptocurrency address to retrieve
        :returns dict: an `address structure <https://docs.ccxt.com/?id=address-structure>`
        """
        await self.load_markets()
        currency = self.currency(code)
        request: dict = {
            'asset': currency['id'],
        }
        response = await self.privateGetFundingAddress(self.extend(request, params))
        #
        #     {
        #         "account_id": "string",
        #         "address": "string",
        #         "address_meta": [
        #             {
        #                 "label": "string",
        #                 "value": "string"
        #             }
        #         ],
        #         "asset": "string",
        #         "assigned_at": 0,
        #         "name": "string",
        #         "network": 0,
        #         "qr_code_uri": "string",
        #         "receive_fee": "string",
        #         "total_received": "string",
        #         "total_unconfirmed": "string"
        #     }
        #
        return self.parse_deposit_address(response, currency)

    def parse_deposit_address(self, depositAddress, currency: Currency = None) -> DepositAddress:
        #
        #     {
        #         "account_id": "string",
        #         "address": "string",
        #         "address_meta": [
        #             {
        #                 "label": "string",
        #                 "value": "string"
        #             }
        #         ],
        #         "asset": "string",
        #         "assigned_at": 0,
        #         "name": "string",
        #         "network": 0,
        #         "qr_code_uri": "string",
        #         "receive_fee": "string",
        #         "total_received": "string",
        #         "total_unconfirmed": "string"
        #     }
        #
        currencyId = self.safe_string_upper(depositAddress, 'currency')
        code = self.safe_currency_code(currencyId, currency)
        return {
            'info': depositAddress,
            'currency': code,
            'network': None,
            'address': self.safe_string(depositAddress, 'address'),
            'tag': self.safe_string(depositAddress, 'name'),
        }

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = self.urls['api'][api] + '/' + self.version + '/' + self.implode_params(path, params)
        query = self.omit(params, self.extract_params(path))
        if query:
            url += '?' + self.urlencode(query)
        if (api == 'private') or (api == 'exchangePrivate'):
            self.check_required_credentials()
            auth = self.string_to_base64(self.apiKey + ':' + self.secret)
            headers = {
                'Authorization': 'Basic ' + auth,
            }
        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
        error = self.safe_value(response, 'error')
        if error is not None:
            raise ExchangeError(self.id + ' ' + self.json(response))
        return None
