# -*- 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.btcmarkets import ImplicitAPI
import hashlib
from ccxt.base.types import Any, Balances, Currency, Int, Market, Num, Order, OrderBook, OrderSide, OrderType, Str, Ticker, Trade, Transaction
from typing import List
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class btcmarkets(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(btcmarkets, self).describe(), {
            'id': 'btcmarkets',
            'name': 'BTC Markets',
            'countries': ['AU'],  # Australia
            'rateLimit': 1000,  # market data cached for 1 second(trades cached for 2 seconds)
            'version': 'v3',
            'has': {
                'CORS': None,
                'spot': True,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'addMargin': False,
                'borrowCrossMargin': False,
                'borrowIsolatedMargin': False,
                'borrowMargin': False,
                'cancelOrder': True,
                'cancelOrders': True,
                'closeAllPositions': False,
                'closePosition': False,
                'createDepositAddress': False,
                'createOrder': True,
                'createOrderWithTakeProfitAndStopLoss': False,
                'createOrderWithTakeProfitAndStopLossWs': False,
                'createPostOnlyOrder': False,
                'createReduceOnlyOrder': False,
                'createTriggerOrder': True,
                'fetchBalance': True,
                'fetchBorrowInterest': False,
                'fetchBorrowRate': False,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchBorrowRates': False,
                'fetchBorrowRatesPerSymbol': False,
                'fetchClosedOrders': 'emulated',
                'fetchCrossBorrowRate': False,
                'fetchCrossBorrowRates': False,
                'fetchDepositAddress': False,
                'fetchDepositAddresses': False,
                'fetchDepositAddressesByNetwork': False,
                'fetchDeposits': True,
                'fetchDepositsWithdrawals': True,
                'fetchFundingHistory': False,
                'fetchFundingInterval': False,
                'fetchFundingIntervals': False,
                'fetchFundingRate': False,
                'fetchFundingRateHistory': False,
                'fetchFundingRates': False,
                'fetchGreeks': False,
                'fetchIndexOHLCV': False,
                'fetchIsolatedBorrowRate': False,
                'fetchIsolatedBorrowRates': False,
                'fetchIsolatedPositions': False,
                'fetchLeverage': False,
                'fetchLeverages': False,
                'fetchLeverageTiers': False,
                'fetchLiquidations': False,
                'fetchLongShortRatio': False,
                'fetchLongShortRatioHistory': False,
                'fetchMarginAdjustmentHistory': False,
                'fetchMarginMode': False,
                'fetchMarginModes': False,
                'fetchMarketLeverageTiers': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMarkPrices': False,
                'fetchMyLiquidations': False,
                'fetchMySettlementHistory': False,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenInterest': False,
                'fetchOpenInterestHistory': False,
                'fetchOpenInterests': False,
                'fetchOpenOrders': True,
                'fetchOption': False,
                'fetchOptionChain': False,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrders': True,
                'fetchPosition': False,
                'fetchPositionHistory': False,
                'fetchPositionMode': False,
                'fetchPositions': False,
                'fetchPositionsForSymbol': False,
                'fetchPositionsHistory': False,
                'fetchPositionsRisk': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchSettlementHistory': False,
                'fetchTicker': True,
                'fetchTime': True,
                'fetchTrades': True,
                'fetchTransactions': 'emulated',
                'fetchVolatilityHistory': False,
                'fetchWithdrawals': True,
                'reduceMargin': False,
                'repayCrossMargin': False,
                'repayIsolatedMargin': False,
                'repayMargin': False,
                'setLeverage': False,
                'setMargin': False,
                'setMarginMode': False,
                'setPositionMode': False,
                'withdraw': True,
            },
            'urls': {
                'logo': 'https://github.com/user-attachments/assets/8c8d6907-3873-4cc4-ad20-e22fba28247e',
                'api': {
                    'public': 'https://api.btcmarkets.net',
                    'private': 'https://api.btcmarkets.net',
                },
                'www': 'https://btcmarkets.net',
                'doc': [
                    'https://api.btcmarkets.net/doc/v3',
                    'https://github.com/BTCMarkets/API',
                ],
            },
            'api': {
                'public': {
                    'get': [
                        'markets',
                        'markets/{marketId}/ticker',
                        'markets/{marketId}/trades',
                        'markets/{marketId}/orderbook',
                        'markets/{marketId}/candles',
                        'markets/tickers',
                        'markets/orderbooks',
                        'time',
                    ],
                },
                'private': {
                    'get': [
                        'orders',
                        'orders/{id}',
                        'batchorders/{ids}',
                        'trades',
                        'trades/{id}',
                        'withdrawals',
                        'withdrawals/{id}',
                        'deposits',
                        'deposits/{id}',
                        'transfers',
                        'transfers/{id}',
                        'addresses',
                        'withdrawal-fees',
                        'assets',
                        'accounts/me/trading-fees',
                        'accounts/me/withdrawal-limits',
                        'accounts/me/balances',
                        'accounts/me/transactions',
                        'reports/{id}',
                    ],
                    'post': [
                        'orders',
                        'batchorders',
                        'withdrawals',
                        'reports',
                    ],
                    'delete': [
                        'orders',
                        'orders/{id}',
                        'batchorders/{ids}',
                    ],
                    'put': [
                        'orders/{id}',
                    ],
                },
            },
            'timeframes': {
                '1m': '1m',
                '1h': '1h',
                '1d': '1d',
            },
            'features': {
                'spot': {
                    'sandbox': False,
                    'createOrder': {
                        'marginMode': False,
                        'triggerPrice': True,  # todo: check
                        'triggerPriceType': None,
                        'triggerDirection': False,
                        'stopLossPrice': False,
                        'takeProfitPrice': False,
                        'attachedStopLossTakeProfit': None,
                        'timeInForce': {
                            'IOC': True,
                            'FOK': True,
                            'PO': True,
                            'GTD': False,
                        },
                        'hedged': False,
                        'leverage': False,
                        'marketBuyRequiresPrice': False,
                        'marketBuyByCost': False,
                        'selfTradePrevention': True,  # todo: check
                        'trailing': False,
                        'iceberg': False,
                    },
                    'createOrders': None,
                    'fetchMyTrades': {
                        'marginMode': False,
                        'limit': 100,
                        'daysBack': 100000,
                        'untilDays': 100000,
                        'symbolRequired': True,
                    },
                    'fetchOrder': {
                        'marginMode': False,
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOpenOrders': {
                        'marginMode': False,
                        'limit': 100,
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOrders': {
                        'marginMode': False,
                        'limit': 100,
                        'daysBack': 100000,
                        'untilDays': 100000,
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchClosedOrders': {
                        'marginMode': False,
                        'limit': 100,
                        'daysBack': 100000,
                        'daysBackCanceled': 1,
                        'untilDays': 100000,
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOHLCV': {
                        'limit': 1000,
                    },
                },
                'swap': {
                    'linear': None,
                    'inverse': None,
                },
                'future': {
                    'linear': None,
                    'inverse': None,
                },
            },
            'precisionMode': TICK_SIZE,
            'exceptions': {
                'exact': {
                    'InsufficientFund': InsufficientFunds,
                    'InvalidPrice': InvalidOrder,
                    'InvalidAmount': InvalidOrder,
                    'MissingArgument': BadRequest,
                    'OrderAlreadyCancelled': InvalidOrder,
                    'OrderNotFound': OrderNotFound,
                    'OrderStatusIsFinal': InvalidOrder,
                    'InvalidPaginationParameter': BadRequest,
                },
                'broad': {
                },
            },
            'fees': {
                'percentage': True,
                'tierBased': True,
                'maker': self.parse_number('-0.0005'),
                'taker': self.parse_number('0.0020'),
            },
            'options': {
                'fees': {
                    'AUD': {
                        'maker': self.parse_number('0.0085'),
                        'taker': self.parse_number('0.0085'),
                    },
                },
            },
        })

    async def fetch_transactions_with_method(self, method, code: Str = None, since: Int = None, limit: Int = None, params={}):
        await self.load_markets()
        request: dict = {}
        if limit is not None:
            request['limit'] = limit
        if since is not None:
            request['after'] = since
        currency = None
        if code is not None:
            currency = self.currency(code)
        response = await getattr(self, method)(self.extend(request, params))
        return self.parse_transactions(response, currency, since, limit)

    async def fetch_deposits_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
        """
        fetch history of deposits and withdrawals

        https://docs.btcmarkets.net/v3/#tag/Fund-Management-APIs/paths/~1v3~1transfers/get

        :param str [code]: unified currency code for the currency of the deposit/withdrawals, default is None
        :param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None
        :param int [limit]: max number of deposit/withdrawals to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        return await self.fetch_transactions_with_method('privateGetTransfers', code, since, limit, params)

    async def fetch_deposits(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
        """
        fetch all deposits made to an account

        https://docs.btcmarkets.net/v3/#tag/Fund-Management-APIs/paths/~1v3~1deposits/get

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        return await self.fetch_transactions_with_method('privateGetDeposits', code, since, limit, params)

    async def fetch_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
        """
        fetch all withdrawals made from an account

        https://docs.btcmarkets.net/v3/#tag/Fund-Management-APIs/paths/~1v3~1withdrawals/get

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        return await self.fetch_transactions_with_method('privateGetWithdrawals', code, since, limit, params)

    def parse_transaction_status(self, status: Str):
        statuses: dict = {
            'Accepted': 'pending',
            'Pending Authorization': 'pending',
            'Complete': 'ok',
            'Cancelled': 'cancelled',
            'Failed': 'failed',
        }
        return self.safe_string(statuses, status, status)

    def parse_transaction_type(self, type):
        statuses: dict = {
            'Withdraw': 'withdrawal',
            'Deposit': 'deposit',
        }
        return self.safe_string(statuses, type, type)

    def parse_transaction(self, transaction: dict, currency: Currency = None) -> Transaction:
        #
        #    {
        #         "id": "6500230339",
        #         "assetName": "XRP",
        #         "amount": "500",
        #         "type": "Deposit",
        #         "creationTime": "2020-07-27T07:52:08.640000Z",
        #         "status": "Complete",
        #         "description": "RIPPLE Deposit, XRP 500",
        #         "fee": "0",
        #         "lastUpdate": "2020-07-27T07:52:08.665000Z",
        #         "paymentDetail": {
        #             "txId": "lsjflsjdfljsd",
        #             "address": "kjasfkjsdf?dt=873874545"
        #         }
        #    }
        #
        #    {
        #         "id": "500985282",
        #         "assetName": "BTC",
        #         "amount": "0.42570126",
        #         "type": "Withdraw",
        #         "creationTime": "2017-07-29T12:49:03.931000Z",
        #         "status": "Complete",
        #         "description": "BTC withdraw from [nick-btcmarkets@snowmonkey.co.uk] to Address: 1B9DsnSYQ54VMqFHVJYdGoLMCYzFwrQzsj amount: 0.42570126 fee: 0.00000000",
        #         "fee": "0.0005",
        #         "lastUpdate": "2017-07-29T12:52:20.676000Z",
        #         "paymentDetail": {
        #             "txId": "fkjdsfjsfljsdfl",
        #             "address": "a;daddjas;djas"
        #         }
        #    }
        #
        #    {
        #         "id": "505102262",
        #         "assetName": "XRP",
        #         "amount": "979.836",
        #         "type": "Deposit",
        #         "creationTime": "2017-07-31T08:50:01.053000Z",
        #         "status": "Complete",
        #         "description": "Ripple Deposit, X 979.8360",
        #         "fee": "0",
        #         "lastUpdate": "2017-07-31T08:50:01.290000Z"
        #     }
        #
        timestamp = self.parse8601(self.safe_string(transaction, 'creationTime'))
        lastUpdate = self.parse8601(self.safe_string(transaction, 'lastUpdate'))
        type = self.parse_transaction_type(self.safe_string_lower(transaction, 'type'))
        if type == 'withdraw':
            type = 'withdrawal'
        cryptoPaymentDetail = self.safe_dict(transaction, 'paymentDetail', {})
        txid = self.safe_string(cryptoPaymentDetail, 'txId')
        address = self.safe_string(cryptoPaymentDetail, 'address')
        tag = None
        if address is not None:
            addressParts = address.split('?dt=')
            numParts = len(addressParts)
            if numParts > 1:
                address = addressParts[0]
                tag = addressParts[1]
        addressTo = address
        tagTo = tag
        addressFrom = None
        tagFrom = None
        fee = self.safe_string(transaction, 'fee')
        status = self.parse_transaction_status(self.safe_string(transaction, 'status'))
        currencyId = self.safe_string(transaction, 'assetName')
        code = self.safe_currency_code(currencyId)
        amount = self.safe_string(transaction, 'amount')
        if fee:
            amount = Precise.string_sub(amount, fee)
        return {
            'id': self.safe_string(transaction, 'id'),
            'txid': txid,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'network': None,
            'address': address,
            'addressTo': addressTo,
            'addressFrom': addressFrom,
            'tag': tag,
            'tagTo': tagTo,
            'tagFrom': tagFrom,
            'type': type,
            'amount': self.parse_number(amount),
            'currency': code,
            'status': status,
            'updated': lastUpdate,
            'comment': self.safe_string(transaction, 'description'),
            'internal': None,
            'fee': {
                'currency': code,
                'cost': self.parse_number(fee),
                'rate': None,
            },
            'info': transaction,
        }

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

        https://docs.btcmarkets.net/v3/#tag/Market-Data-APIs/paths/~1v3~1markets/get

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = await self.publicGetMarkets(params)
        #
        #     [
        #         {
        #             "marketId":"COMP-AUD",
        #             "baseAssetName":"COMP",
        #             "quoteAssetName":"AUD",
        #             "minOrderAmount":"0.00006",
        #             "maxOrderAmount":"1000000",
        #             "amountDecimals":"8",
        #             "priceDecimals":"2",
        #             "status": "Online"
        #         }
        #     ]
        #
        return self.parse_markets(response)

    def parse_market(self, market: dict) -> Market:
        baseId = self.safe_string(market, 'baseAssetName')
        quoteId = self.safe_string(market, 'quoteAssetName')
        id = self.safe_string(market, 'marketId')
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        symbol = base + '/' + quote
        fees = self.safe_value(self.safe_dict(self.options, 'fees', {}), quote, self.fees)
        pricePrecision = self.parse_number(self.parse_precision(self.safe_string(market, 'priceDecimals')))
        minAmount = self.safe_number(market, 'minOrderAmount')
        maxAmount = self.safe_number(market, 'maxOrderAmount')
        status = self.safe_string(market, 'status')
        minPrice = None
        if quote == 'AUD':
            minPrice = pricePrecision
        return {
            'id': id,
            'symbol': symbol,
            '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 == 'Online'),
            'contract': False,
            'linear': None,
            'inverse': None,
            'taker': fees['taker'],
            'maker': fees['maker'],
            'contractSize': None,
            'expiry': None,
            'expiryDatetime': None,
            'strike': None,
            'optionType': None,
            'precision': {
                'amount': self.parse_number(self.parse_precision(self.safe_string(market, 'amountDecimals'))),
                'price': pricePrecision,
            },
            'limits': {
                'leverage': {
                    'min': None,
                    'max': None,
                },
                'amount': {
                    'min': minAmount,
                    'max': maxAmount,
                },
                'price': {
                    'min': minPrice,
                    'max': None,
                },
                'cost': {
                    'min': None,
                    'max': None,
                },
            },
            'created': None,
            'info': market,
        }

    async def fetch_time(self, params={}) -> Int:
        """
        fetches the current integer timestamp in milliseconds from the exchange server

        https://docs.btcmarkets.net/v3/#tag/Misc-APIs/paths/~1v3~1time/get

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        """
        response = await self.publicGetTime(params)
        #
        #     {
        #         "timestamp": "2019-09-01T18:34:27.045000Z"
        #     }
        #
        return self.parse8601(self.safe_string(response, 'timestamp'))

    def parse_balance(self, response) -> Balances:
        result: dict = {'info': response}
        for i in range(0, len(response)):
            balance = response[i]
            currencyId = self.safe_string(balance, 'assetName')
            code = self.safe_currency_code(currencyId)
            account = self.account()
            account['used'] = self.safe_string(balance, 'locked')
            account['total'] = self.safe_string(balance, 'balance')
            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://docs.btcmarkets.net/v3/#tag/Account-APIs/paths/~1v3~1accounts~1me~1balances/get

        :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.privateGetAccountsMeBalances(params)
        return self.parse_balance(response)

    def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
        #
        #     [
        #         "2020-09-12T18:30:00.000000Z",
        #         "14409.45",  # open
        #         "14409.45",  # high
        #         "14403.91",  # low
        #         "14403.91",  # close
        #         "0.01571701"  # volume
        #     ]
        #
        return [
            self.parse8601(self.safe_string(ohlcv, 0)),
            self.safe_number(ohlcv, 1),  # open
            self.safe_number(ohlcv, 2),  # high
            self.safe_number(ohlcv, 3),  # low
            self.safe_number(ohlcv, 4),  # close
            self.safe_number(ohlcv, 5),  # volume
        ]

    async def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
        """
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://docs.btcmarkets.net/v3/#tag/Market-Data-APIs/paths/~1v3~1markets~1{marketId}~1candles/get

        :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
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'marketId': market['id'],
            'timeWindow': self.safe_string(self.timeframes, timeframe, timeframe),
            # 'from': self.iso8601(since),
            # 'to': self.iso8601(self.milliseconds()),
            # 'before': 1234567890123,
            # 'after': 1234567890123,
            # 'limit': limit,  # default 10, max 200
        }
        if since is not None:
            request['from'] = self.iso8601(since)
        if limit is not None:
            request['limit'] = min(limit, 200)  # default is 10, max 200
        response = await self.publicGetMarketsMarketIdCandles(self.extend(request, params))
        #
        #     [
        #         ["2020-09-12T18:30:00.000000Z","14409.45","14409.45","14403.91","14403.91","0.01571701"],
        #         ["2020-09-12T18:21:00.000000Z","14409.45","14409.45","14409.45","14409.45","0.0035"],
        #         ["2020-09-12T18:03:00.000000Z","14361.37","14361.37","14361.37","14361.37","0.00345221"],
        #     ]
        #
        return self.parse_ohlcvs(response, market, timeframe, since, limit)

    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://docs.btcmarkets.net/v3/#tag/Market-Data-APIs/paths/~1v3~1markets~1{marketId}~1orderbook/get

        :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 = {
            'marketId': market['id'],
        }
        response = await self.publicGetMarketsMarketIdOrderbook(self.extend(request, params))
        #
        #     {
        #         "marketId":"BTC-AUD",
        #         "snapshotId":1599936148941000,
        #         "asks":[
        #             ["14459.45","0.00456475"],
        #             ["14463.56","2"],
        #             ["14470.91","0.98"],
        #         ],
        #         "bids":[
        #             ["14421.01","0.52"],
        #             ["14421","0.75"],
        #             ["14418","0.3521"],
        #         ]
        #     }
        #
        timestamp = self.safe_integer_product(response, 'snapshotId', 0.001)
        orderbook = self.parse_order_book(response, symbol, timestamp)
        orderbook['nonce'] = self.safe_integer(response, 'snapshotId')
        return orderbook

    def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
        #
        # fetchTicker
        #
        #     {
        #         "marketId":"BAT-AUD",
        #         "bestBid":"0.3751",
        #         "bestAsk":"0.377",
        #         "lastPrice":"0.3769",
        #         "volume24h":"56192.97613335",
        #         "volumeQte24h":"21179.13270465",
        #         "price24h":"0.0119",
        #         "pricePct24h":"3.26",
        #         "low24h":"0.3611",
        #         "high24h":"0.3799",
        #         "timestamp":"2020-08-09T18:28:23.280000Z"
        #     }
        #
        marketId = self.safe_string(ticker, 'marketId')
        market = self.safe_market(marketId, market, '-')
        symbol = market['symbol']
        timestamp = self.parse8601(self.safe_string(ticker, 'timestamp'))
        last = self.safe_string(ticker, 'lastPrice')
        baseVolume = self.safe_string(ticker, 'volume24h')
        quoteVolume = self.safe_string(ticker, 'volumeQte24h')
        change = self.safe_string(ticker, 'price24h')
        percentage = self.safe_string(ticker, 'pricePct24h')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': self.safe_string(ticker, 'high24h'),
            'low': self.safe_string(ticker, 'low'),
            'bid': self.safe_string(ticker, 'bestBid'),
            'bidVolume': None,
            'ask': self.safe_string(ticker, 'bestAsk'),
            'askVolume': None,
            'vwap': None,
            'open': None,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': change,
            'percentage': percentage,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market)

    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://docs.btcmarkets.net/v3/#tag/Market-Data-APIs/paths/~1v3~1markets~1{marketId}~1ticker/get

        :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 = {
            'marketId': market['id'],
        }
        response = await self.publicGetMarketsMarketIdTicker(self.extend(request, params))
        #
        #     {
        #         "marketId":"BAT-AUD",
        #         "bestBid":"0.3751",
        #         "bestAsk":"0.377",
        #         "lastPrice":"0.3769",
        #         "volume24h":"56192.97613335",
        #         "volumeQte24h":"21179.13270465",
        #         "price24h":"0.0119",
        #         "pricePct24h":"3.26",
        #         "low24h":"0.3611",
        #         "high24h":"0.3799",
        #         "timestamp":"2020-08-09T18:28:23.280000Z"
        #     }
        #
        return self.parse_ticker(response, market)

    async def fetch_ticker_2(self, symbol: str, params={}):
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'id': market['id'],
        }
        response = await self.publicGetMarketsMarketIdTicker(self.extend(request, params))
        return self.parse_ticker(response, market)

    def parse_trade(self, trade: dict, market: Market = None) -> Trade:
        #
        # public fetchTrades
        #
        #     {
        #         "id":"6191646611",
        #         "price":"539.98",
        #         "amount":"0.5",
        #         "timestamp":"2020-08-09T15:21:05.016000Z",
        #         "side":"Ask"
        #     }
        #
        # private fetchMyTrades
        #
        #     {
        #         "id": "36014819",
        #         "marketId": "XRP-AUD",
        #         "timestamp": "2019-06-25T16:01:02.977000Z",
        #         "price": "0.67",
        #         "amount": "1.50533262",
        #         "side": "Ask",
        #         "fee": "0.00857285",
        #         "orderId": "3648306",
        #         "liquidityType": "Taker",
        #         "clientOrderId": "48"
        #     }
        #
        timestamp = self.parse8601(self.safe_string(trade, 'timestamp'))
        marketId = self.safe_string(trade, 'marketId')
        market = self.safe_market(marketId, market, '-')
        feeCurrencyCode = market['quote'] if (market['quote'] == 'AUD') else market['base']
        side = self.safe_string(trade, 'side')
        if side == 'Bid':
            side = 'buy'
        elif side == 'Ask':
            side = 'sell'
        id = self.safe_string(trade, 'id')
        priceString = self.safe_string(trade, 'price')
        amountString = self.safe_string(trade, 'amount')
        orderId = self.safe_string(trade, 'orderId')
        fee = None
        feeCostString = self.safe_string(trade, 'fee')
        if feeCostString is not None:
            fee = {
                'cost': feeCostString,
                'currency': feeCurrencyCode,
            }
        takerOrMaker = self.safe_string_lower(trade, 'liquidityType')
        return self.safe_trade({
            'info': trade,
            'id': id,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'order': orderId,
            'symbol': market['symbol'],
            'type': None,
            'side': side,
            'price': priceString,
            'amount': amountString,
            'cost': None,
            'takerOrMaker': takerOrMaker,
            'fee': fee,
        }, 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://docs.btcmarkets.net/v3/#tag/Market-Data-APIs/paths/~1v3~1markets~1{marketId}~1trades/get

        :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 = {
            # 'since': 59868345231,
            'marketId': market['id'],
        }
        response = await self.publicGetMarketsMarketIdTrades(self.extend(request, params))
        #
        #     [
        #         {"id":"6191646611","price":"539.98","amount":"0.5","timestamp":"2020-08-09T15:21:05.016000Z","side":"Ask"},
        #         {"id":"6191646610","price":"539.99","amount":"0.5","timestamp":"2020-08-09T15:21:05.015000Z","side":"Ask"},
        #         {"id":"6191646590","price":"540","amount":"0.00233785","timestamp":"2020-08-09T15:21:04.171000Z","side":"Bid"},
        #     ]
        #
        return self.parse_trades(response, market, since, limit)

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

        https://docs.btcmarkets.net/v3/#tag/Order-Placement-APIs/paths/~1v3~1orders/post

        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.triggerPrice]: the price at which a trigger order is triggered at
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'marketId': market['id'],
            # 'price': self.price_to_precision(symbol, price),
            'amount': self.amount_to_precision(symbol, amount),
            # 'type': 'Limit',  # "Limit", "Market", "Stop Limit", "Stop", "Take Profit"
            'side': 'Bid' if (side == 'buy') else 'Ask',
            # 'triggerPrice': self.price_to_precision(symbol, triggerPrice),  # required for Stop, Stop Limit, Take Profit orders
            # 'targetAmount': self.amount_to_precision(symbol, targetAmount),  # target amount when a desired target outcome is required for order execution
            # 'timeInForce': 'GTC',  # GTC, FOK, IOC
            # 'postOnly': False,  # boolean if self is a post-only order
            # 'selfTrade': 'A',  # A = allow, P = prevent
            # 'clientOrderId': self.uuid(),
        }
        lowercaseType = type.lower()
        orderTypes = self.safe_value(self.options, 'orderTypes', {
            'limit': 'Limit',
            'market': 'Market',
            'stop': 'Stop',
            'stop limit': 'Stop Limit',
            'take profit': 'Take Profit',
        })
        request['type'] = self.safe_string(orderTypes, lowercaseType, type)
        priceIsRequired = False
        triggerPriceIsRequired = False
        if lowercaseType == 'limit':
            priceIsRequired = True
        # elif lowercaseType == 'market':
        #     ...
        # }
        elif lowercaseType == 'stop limit':
            triggerPriceIsRequired = True
            priceIsRequired = True
        elif lowercaseType == 'take profit':
            triggerPriceIsRequired = True
        elif lowercaseType == 'stop':
            triggerPriceIsRequired = True
        if priceIsRequired:
            if price is None:
                raise ArgumentsRequired(self.id + ' createOrder() requires a price argument for a ' + type + 'order')
            else:
                request['price'] = self.price_to_precision(symbol, price)
        if triggerPriceIsRequired:
            triggerPrice = self.safe_number(params, 'triggerPrice')
            params = self.omit(params, 'triggerPrice')
            if triggerPrice is None:
                raise ArgumentsRequired(self.id + ' createOrder() requires a triggerPrice parameter for a ' + type + 'order')
            else:
                request['triggerPrice'] = self.price_to_precision(symbol, triggerPrice)
        clientOrderId = self.safe_string(params, 'clientOrderId')
        if clientOrderId is not None:
            request['clientOrderId'] = clientOrderId
        params = self.omit(params, 'clientOrderId')
        response = await self.privatePostOrders(self.extend(request, params))
        #
        #     {
        #         "orderId": "7524",
        #         "marketId": "BTC-AUD",
        #         "side": "Bid",
        #         "type": "Limit",
        #         "creationTime": "2019-08-30T11:08:21.956000Z",
        #         "price": "100.12",
        #         "amount": "1.034",
        #         "openAmount": "1.034",
        #         "status": "Accepted",
        #         "clientOrderId": "1234-5678",
        #         "timeInForce": "IOC",
        #         "postOnly": False,
        #         "selfTrade": "P",
        #         "triggerAmount": "105",
        #         "targetAmount": "1000"
        #     }
        #
        return self.parse_order(response, market)

    async def cancel_orders(self, ids, symbol: Str = None, params={}):
        """
        cancel multiple orders

        https://docs.btcmarkets.net/v3/#tag/Batch-Order-APIs/paths/~1v3~1batchorders~1{ids}/delete

        :param str[] ids: order ids
        :param str symbol: not used by btcmarkets cancelOrders()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        await self.load_markets()
        for i in range(0, len(ids)):
            ids[i] = int(ids[i])
        request: dict = {
            'ids': ids,
        }
        response = await self.privateDeleteBatchordersIds(self.extend(request, params))
        #
        #    {
        #       "cancelOrders": [
        #            {
        #               "orderId": "414186",
        #               "clientOrderId": "6"
        #            },
        #            ...
        #        ],
        #        "unprocessedRequests": [
        #            {
        #               "code": "OrderAlreadyCancelled",
        #               "message": "order is already cancelled.",
        #               "requestId": "1"
        #            }
        #        ]
        #    }
        #
        cancelOrders = self.safe_list(response, 'cancelOrders', [])
        unprocessedRequests = self.safe_list(response, 'unprocessedRequests', [])
        orders = self.array_concat(cancelOrders, unprocessedRequests)
        return self.parse_orders(orders)

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

        https://docs.btcmarkets.net/v3/#operation/cancelOrder

        :param str id: order id
        :param str symbol: not used by btcmarket cancelOrder()
        :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.privateDeleteOrdersId(self.extend(request, params))
        #
        #    {
        #        "orderId": "7524",
        #        "clientOrderId": "123-456"
        #    }
        #
        return self.parse_order(response)

    def calculate_fee(self, symbol, type, side, amount, price, takerOrMaker='taker', params={}):
        """
        calculates the presumptive fee that would be charged for an order
        :param str symbol: unified market symbol
        :param str type: not used by btcmarkets.calculateFee
        :param str side: not used by btcmarkets.calculateFee
        :param float amount: how much you want to trade, in units of the base currency on most exchanges, or number of contracts
        :param float price: the price for the order to be filled at, in units of the quote currency
        :param str takerOrMaker: 'taker' or 'maker'
        :param dict params:
        :returns dict: contains the rate, the percentage multiplied to the order amount to obtain the fee amount, and cost, the total value of the fee in units of the quote currency, for the order
        """
        market = self.markets[symbol]
        currency = None
        cost = None
        if market['quote'] == 'AUD':
            currency = market['quote']
            amountString = self.number_to_string(amount)
            priceString = self.number_to_string(price)
            otherUnitsAmount = Precise.string_mul(amountString, priceString)
            cost = self.cost_to_precision(symbol, otherUnitsAmount)
        else:
            currency = market['base']
            cost = self.amount_to_precision(symbol, amount)
        rate = market[takerOrMaker]
        rateCost = Precise.string_mul(self.number_to_string(rate), cost)
        return {
            'type': takerOrMaker,
            'currency': currency,
            'rate': rate,
            'cost': float(self.fee_to_precision(symbol, rateCost)),
        }

    def parse_order_status(self, status: Str):
        statuses: dict = {
            'Accepted': 'open',
            'Placed': 'open',
            'Partially Matched': 'open',
            'Fully Matched': 'closed',
            'Cancelled': 'canceled',
            'Partially Cancelled': 'canceled',
            'Failed': 'rejected',
        }
        return self.safe_string(statuses, status, status)

    def parse_order(self, order: dict, market: Market = None) -> Order:
        #
        # createOrder
        #
        #     {
        #         "orderId": "7524",
        #         "marketId": "BTC-AUD",
        #         "side": "Bid",
        #         "type": "Limit",
        #         "creationTime": "2019-08-30T11:08:21.956000Z",
        #         "price": "100.12",
        #         "amount": "1.034",
        #         "openAmount": "1.034",
        #         "status": "Accepted",
        #         "clientOrderId": "1234-5678",
        #         "timeInForce": "IOC",
        #         "postOnly": False,
        #         "selfTrade": "P",
        #         "triggerAmount": "105",
        #         "targetAmount": "1000"
        #     }
        #
        timestamp = self.parse8601(self.safe_string(order, 'creationTime'))
        marketId = self.safe_string(order, 'marketId')
        market = self.safe_market(marketId, market, '-')
        side = self.safe_string(order, 'side')
        if side == 'Bid':
            side = 'buy'
        elif side == 'Ask':
            side = 'sell'
        type = self.safe_string_lower(order, 'type')
        price = self.safe_string(order, 'price')
        amount = self.safe_string(order, 'amount')
        remaining = self.safe_string(order, 'openAmount')
        status = self.parse_order_status(self.safe_string(order, 'status'))
        id = self.safe_string(order, 'orderId')
        clientOrderId = self.safe_string(order, 'clientOrderId')
        timeInForce = self.safe_string(order, 'timeInForce')
        postOnly = self.safe_bool(order, 'postOnly')
        return self.safe_order({
            'info': order,
            'id': id,
            'clientOrderId': clientOrderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'symbol': market['symbol'],
            'type': type,
            'timeInForce': timeInForce,
            'postOnly': postOnly,
            'side': side,
            'price': price,
            'triggerPrice': self.safe_number(order, 'triggerPrice'),
            'cost': None,
            'amount': amount,
            'filled': None,
            'remaining': remaining,
            'average': None,
            'status': status,
            'trades': None,
            'fee': None,
        }, market)

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

        https://docs.btcmarkets.net/v3/#operation/getOrderById

        :param str id: the order id
        :param str symbol: not used by btcmarkets 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(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
        fetches information on multiple orders made by the user

        https://docs.btcmarkets.net/v3/#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>`
        """
        await self.load_markets()
        request: dict = {
            'status': 'all',
        }
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['marketId'] = market['id']
        if since is not None:
            request['after'] = since
        if limit is not None:
            request['limit'] = limit
        response = await self.privateGetOrders(self.extend(request, params))
        return self.parse_orders(response, market, since, limit)

    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://docs.btcmarkets.net/v3/#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>`
        """
        request: dict = {'status': 'open'}
        return await self.fetch_orders(symbol, since, limit, self.extend(request, 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://docs.btcmarkets.net/v3/#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>`
        """
        orders = await self.fetch_orders(symbol, since, limit, params)
        return self.filter_by(orders, 'status', 'closed')

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

        https://docs.btcmarkets.net/v3/#operation/getTrades

        :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>`
        """
        await self.load_markets()
        request: dict = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['marketId'] = market['id']
        if since is not None:
            request['after'] = since
        if limit is not None:
            request['limit'] = limit
        response = await self.privateGetTrades(self.extend(request, params))
        #
        #     [
        #         {
        #             "id": "36014819",
        #             "marketId": "XRP-AUD",
        #             "timestamp": "2019-06-25T16:01:02.977000Z",
        #             "price": "0.67",
        #             "amount": "1.50533262",
        #             "side": "Ask",
        #             "fee": "0.00857285",
        #             "orderId": "3648306",
        #             "liquidityType": "Taker",
        #             "clientOrderId": "48"
        #         },
        #         {
        #             "id": "3568960",
        #             "marketId": "GNT-AUD",
        #             "timestamp": "2019-06-20T08:44:04.488000Z",
        #             "price": "0.1362",
        #             "amount": "0.85",
        #             "side": "Bid",
        #             "fee": "0.00098404",
        #             "orderId": "3543015",
        #             "liquidityType": "Maker"
        #         }
        #     ]
        #
        return self.parse_trades(response, market, since, limit)

    async def withdraw(self, code: str, amount: float, address: str, tag: Str = None, params={}) -> Transaction:
        """
        make a withdrawal

        https://docs.btcmarkets.net/v3/#tag/Fund-Management-APIs/paths/~1v3~1withdrawals/post

        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        tag, params = self.handle_withdraw_tag_and_params(tag, params)
        await self.load_markets()
        currency = self.currency(code)
        request: dict = {
            'currency_id': currency['id'],
            'amount': self.currency_to_precision(code, amount),
        }
        if code != 'AUD':
            self.check_address(address)
            request['toAddress'] = address
        if tag is not None:
            request['toAddress'] = address + '?dt=' + tag
        response = await self.privatePostWithdrawals(self.extend(request, params))
        #
        #      {
        #          "id": "4126657",
        #          "assetName": "XRP",
        #          "amount": "25",
        #          "type": "Withdraw",
        #          "creationTime": "2019-09-04T00:04:10.973000Z",
        #          "status": "Pending Authorization",
        #          "description": "XRP withdraw from [me@test.com] to Address: abc amount: 25 fee: 0",
        #          "fee": "0",
        #          "lastUpdate": "2019-09-04T00:04:11.018000Z",
        #          "paymentDetail": {
        #              "address": "abc"
        #          }
        #      }
        #
        return self.parse_transaction(response, currency)

    def nonce(self):
        return self.milliseconds()

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        request = '/' + self.version + '/' + self.implode_params(path, params)
        query = self.keysort(self.omit(params, self.extract_params(path)))
        if api == 'private':
            self.check_required_credentials()
            nonce = str(self.nonce())
            secret = self.base64_to_binary(self.secret)
            auth = method + request + nonce
            if (method == 'GET') or (method == 'DELETE'):
                if query:
                    request += '?' + self.urlencode(query)
            else:
                body = self.json(query)
                auth += body
            signature = self.hmac(self.encode(auth), secret, hashlib.sha512, 'base64')
            headers = {
                'Accept': 'application/json',
                'Accept-Charset': 'UTF-8',
                'Content-Type': 'application/json',
                'BM-AUTH-APIKEY': self.apiKey,
                'BM-AUTH-TIMESTAMP': nonce,
                'BM-AUTH-SIGNATURE': signature,
            }
        elif api == 'public':
            if query:
                request += '?' + self.urlencode(query)
        url = self.urls['api'][api] + request
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, code: 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
        #
        #     {"code":"UnAuthorized","message":"invalid access token"}
        #     {"code":"MarketNotFound","message":"invalid marketId"}
        #
        errorCode = self.safe_string(response, 'code')
        message = self.safe_string(response, 'message')
        if errorCode is not None:
            feedback = self.id + ' ' + body
            self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
            self.throw_exactly_matched_exception(self.exceptions['exact'], errorCode, feedback)
            self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback)
            raise ExchangeError(feedback)  # unknown message
        return None
