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

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

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


class novadax(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(novadax, self).describe(), {
            'id': 'novadax',
            'name': 'NovaDAX',
            'countries': ['BR'],  # Brazil
            # 6000 weight per min => 100 weight per second => min weight = 1
            # 100 requests per second =>( 1000ms / 100 ) = 10 ms between requests on average
            'rateLimit': 10,
            'version': 'v1',
            # new metainfo interface
            '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,
                'createMarketBuyOrderWithCost': True,
                'createMarketOrderWithCost': False,
                'createMarketSellOrderWithCost': False,
                'createOrder': True,
                'createReduceOnlyOrder': False,
                'createStopLimitOrder': True,
                'createStopMarketOrder': True,
                'createStopOrder': True,
                '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': 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,
                '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,
                'fetchOrderTrades': True,
                'fetchPosition': False,
                'fetchPositionHistory': False,
                'fetchPositionMode': False,
                'fetchPositions': False,
                'fetchPositionsForSymbol': False,
                'fetchPositionsHistory': False,
                'fetchPositionsRisk': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchSettlementHistory': False,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTime': True,
                'fetchTrades': True,
                'fetchTradingFee': False,
                'fetchTradingFees': False,
                'fetchTransactions': 'emulated',
                'fetchUnderlyingAssets': False,
                'fetchVolatilityHistory': False,
                'fetchWithdrawals': True,
                'reduceMargin': False,
                'repayCrossMargin': False,
                'repayIsolatedMargin': False,
                'setLeverage': False,
                'setMargin': False,
                'setMarginMode': False,
                'setPositionMode': False,
                'transfer': True,
                'withdraw': True,
            },
            'timeframes': {
                '1m': 'ONE_MIN',
                '5m': 'FIVE_MIN',
                '15m': 'FIFTEEN_MIN',
                '30m': 'HALF_HOU',
                '1h': 'ONE_HOU',
                '1d': 'ONE_DAY',
                '1w': 'ONE_WEE',
                '1M': 'ONE_MON',
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/92337550-2b085500-f0b3-11ea-98e7-5794fb07dd3b.jpg',
                'api': {
                    'public': 'https://api.novadax.com',
                    'private': 'https://api.novadax.com',
                },
                'www': 'https://www.novadax.com.br',
                'doc': [
                    'https://doc.novadax.com/pt-BR/',
                ],
                'fees': 'https://www.novadax.com.br/fees-and-limits',
                'referral': 'https://www.novadax.com.br/?s=ccxt',
            },
            'api': {
                'public': {
                    'get': {
                        'common/symbol': 1,
                        'common/symbols': 1,
                        'common/timestamp': 1,
                        'market/tickers': 5,
                        'market/ticker': 1,
                        'market/depth': 1,
                        'market/trades': 5,
                        'market/kline/history': 5,
                    },
                },
                'private': {
                    'get': {
                        'orders/get': 1,
                        'orders/list': 10,
                        'orders/fill': 3,  # not found in doc
                        'orders/fills': 10,
                        'account/getBalance': 1,
                        'account/subs': 1,
                        'account/subs/balance': 1,
                        'account/subs/transfer/record': 10,
                        'wallet/query/deposit-withdraw': 3,
                    },
                    'post': {
                        'orders/create': 5,
                        'orders/batch-create': 50,
                        'orders/cancel': 1,
                        'orders/batch-cancel': 10,
                        'orders/cancel-by-symbol': 10,
                        'account/subs/transfer': 5,
                        'wallet/withdraw/coin': 3,
                        'account/withdraw/coin': 3,  # not found in doc
                    },
                },
            },
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'taker': self.parse_number('0.005'),
                    'maker': self.parse_number('0.0025'),
                },
            },
            'requiredCredentials': {
                'apiKey': True,
                'secret': True,
            },
            'precisionMode': TICK_SIZE,
            'exceptions': {
                'exact': {
                    'A99999': ExchangeError,  # 500 Failed Internal error
                    # 'A10000': ExchangeError,  # 200 Success Successful request
                    'A10001': BadRequest,  # 400 Params error Parameter is invalid
                    'A10002': ExchangeError,  # 404 Api not found API used is irrelevant
                    'A10003': AuthenticationError,  # 403 Authentication failed Authentication is failed
                    'A10004': RateLimitExceeded,  # 429 Too many requests Too many requests are made
                    'A10005': PermissionDenied,  # 403 Kyc required Need to complete KYC firstly
                    'A10006': AccountSuspended,  # 403 Customer canceled Account is canceled
                    'A10007': AccountNotEnabled,  # 400 Account not exist Sub account does not exist
                    'A10011': BadSymbol,  # 400 Symbol not exist Trading symbol does not exist
                    'A10012': BadSymbol,  # 400 Symbol not trading Trading symbol is temporarily not available
                    'A10013': OnMaintenance,  # 503 Symbol maintain Trading symbol is in maintain
                    'A30001': OrderNotFound,  # 400 Order not found Queried order is not found
                    'A30002': InvalidOrder,  # 400 Order amount is too small Order amount is too small
                    'A30003': InvalidOrder,  # 400 Order amount is invalid Order amount is invalid
                    'A30004': InvalidOrder,  # 400 Order value is too small Order value is too small
                    'A30005': InvalidOrder,  # 400 Order value is invalid Order value is invalid
                    'A30006': InvalidOrder,  # 400 Order price is invalid Order price is invalid
                    'A30007': InsufficientFunds,  # 400 Insufficient balance The balance is insufficient
                    'A30008': InvalidOrder,  # 400 Order was closed The order has been executed
                    'A30009': InvalidOrder,  # 400 Order canceled The order has been cancelled
                    'A30010': CancelPending,  # 400 Order cancelling The order is being cancelled
                    'A30011': InvalidOrder,  # 400 Order price too high The order price is too high
                    'A30012': InvalidOrder,  # 400 Order price too low The order price is too low
                    'A40004': InsufficientFunds,  # {"code":"A40004","data":[],"message":"sub account balance Insufficient"}
                },
                'broad': {
                },
            },
            'options': {
                'fetchOHLCV': {
                    'volume': 'amount',  # 'amount' for base volume or 'vol' for quote volume
                },
                'transfer': {
                    'fillResponseFromRequest': True,
                },
            },
            'features': {
                'spot': {
                    'sandbox': False,
                    'createOrder': {
                        'marginMode': False,
                        'triggerPrice': True,
                        'triggerDirection': True,  # todo
                        'triggerPriceType': None,
                        'stopLossPrice': False,  # todo
                        'takeProfitPrice': False,  # todo
                        'attachedStopLossTakeProfit': None,
                        # todo
                        'timeInForce': {
                            'IOC': False,
                            'FOK': False,
                            'PO': False,
                            'GTD': False,
                        },
                        'hedged': False,
                        'trailing': False,
                        'leverage': False,
                        'marketBuyByCost': True,
                        'marketBuyRequiresPrice': False,
                        'selfTradePrevention': False,
                        'iceberg': True,  # todo
                    },
                    'createOrders': None,  # todo: add implementation
                    'fetchMyTrades': {
                        'marginMode': False,
                        'limit': 100,
                        'daysBack': 100000,  # todo
                        'untilDays': 100000,  # todo
                        'symbolRequired': False,
                    },
                    'fetchOrder': {
                        'marginMode': False,
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOpenOrders': {
                        'marginMode': False,
                        'limit': None,
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOrders': {
                        'marginMode': False,
                        'limit': 100,
                        'daysBack': 100000,  # todo
                        'untilDays': 100000,  # todo
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchClosedOrders': {
                        'marginMode': False,
                        'limit': 100,
                        'daysBack': 100000,  # todo
                        'daysBackCanceled': 1,  # todo
                        'untilDays': 100000,  # todo
                        'trigger': False,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOHLCV': {
                        'limit': None,  # todo max 3000
                    },
                },
                'swap': {
                    'linear': None,
                    'inverse': None,
                },
                'future': {
                    'linear': None,
                    'inverse': None,
                },
            },
        })

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

        https://doc.novadax.com/en-US/#get-current-system-time

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        """
        response = self.publicGetCommonTimestamp(params)
        #
        #     {
        #         "code":"A10000",
        #         "data":1599090512080,
        #         "message":"Success"
        #     }
        #
        return self.safe_integer(response, 'data')

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

        https://doc.novadax.com/en-US/#get-all-supported-trading-symbol

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = self.publicGetCommonSymbols(params)
        #
        #     {
        #         "code":"A10000",
        #         "data":[
        #             {
        #                 "amountPrecision":8,
        #                 "baseCurrency":"BTC",
        #                 "minOrderAmount":"0.001",
        #                 "minOrderValue":"25",
        #                 "pricePrecision":2,
        #                 "quoteCurrency":"BRL",
        #                 "status":"ONLINE",
        #                 "symbol":"BTC_BRL",
        #                 "valuePrecision":2
        #             },
        #         ],
        #         "message":"Success"
        #     }
        #
        data = self.safe_value(response, 'data', [])
        return self.parse_markets(data)

    def parse_market(self, market: dict) -> Market:
        baseId = self.safe_string(market, 'baseCurrency')
        quoteId = self.safe_string(market, 'quoteCurrency')
        id = self.safe_string(market, 'symbol')
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        status = self.safe_string(market, 'status')
        return {
            'id': id,
            'symbol': base + '/' + quote,
            'base': base,
            'quote': quote,
            'settle': None,
            'baseId': baseId,
            'quoteId': quoteId,
            'settleId': None,
            'type': 'spot',
            'spot': True,
            'margin': False,
            'swap': False,
            'future': False,
            'option': False,
            'active': (status == 'ONLINE'),
            '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, 'amountPrecision'))),
                'price': self.parse_number(self.parse_precision(self.safe_string(market, 'pricePrecision'))),
                # 'cost': self.parse_number(self.parse_precision(self.safe_string(market, 'valuePrecision'))),
            },
            'limits': {
                'leverage': {
                    'min': None,
                    'max': None,
                },
                'amount': {
                    'min': self.safe_number(market, 'minOrderAmount'),
                    'max': None,
                },
                'price': {
                    'min': None,
                    'max': None,
                },
                'cost': {
                    'min': self.safe_number(market, 'minOrderValue'),
                    'max': None,
                },
            },
            'created': None,
            'info': market,
        }

    def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
        #
        # fetchTicker, fetchTickers
        #
        #     {
        #         "ask":"61946.1",
        #         "baseVolume24h":"164.41930186",
        #         "bid":"61815",
        #         "high24h":"64930.72",
        #         "lastPrice":"61928.41",
        #         "low24h":"61156.32",
        #         "open24h":"64512.46",
        #         "quoteVolume24h":"10308157.95",
        #         "symbol":"BTC_BRL",
        #         "timestamp":1599091115090
        #     }
        #
        timestamp = self.safe_integer(ticker, 'timestamp')
        marketId = self.safe_string(ticker, 'symbol')
        symbol = self.safe_symbol(marketId, market, '_')
        open = self.safe_string(ticker, 'open24h')
        last = self.safe_string(ticker, 'lastPrice')
        baseVolume = self.safe_string(ticker, 'baseVolume24h')
        quoteVolume = self.safe_string(ticker, 'quoteVolume24h')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': self.safe_string(ticker, 'high24h'),
            'low': self.safe_string(ticker, 'low24h'),
            'bid': self.safe_string(ticker, 'bid'),
            'bidVolume': None,
            'ask': self.safe_string(ticker, 'ask'),
            'askVolume': None,
            'vwap': None,
            'open': open,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': None,
            'percentage': None,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market)

    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://doc.novadax.com/en-US/#get-latest-ticker-for-specific-pair

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = self.publicGetMarketTicker(self.extend(request, params))
        #
        #     {
        #         "code":"A10000",
        #         "data":{
        #             "ask":"61946.1",
        #             "baseVolume24h":"164.41930186",
        #             "bid":"61815",
        #             "high24h":"64930.72",
        #             "lastPrice":"61928.41",
        #             "low24h":"61156.32",
        #             "open24h":"64512.46",
        #             "quoteVolume24h":"10308157.95",
        #             "symbol":"BTC_BRL",
        #             "timestamp":1599091115090
        #         },
        #         "message":"Success"
        #     }
        #
        data = self.safe_dict(response, 'data', {})
        return self.parse_ticker(data, market)

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

        https://doc.novadax.com/en-US/#get-latest-tickers-for-all-trading-pairs

        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        self.load_markets()
        symbols = self.market_symbols(symbols)
        response = self.publicGetMarketTickers(params)
        #
        #     {
        #         "code":"A10000",
        #         "data":[
        #             {
        #                 "ask":"61879.36",
        #                 "baseVolume24h":"164.40955092",
        #                 "bid":"61815",
        #                 "high24h":"64930.72",
        #                 "lastPrice":"61820.04",
        #                 "low24h":"61156.32",
        #                 "open24h":"64624.19",
        #                 "quoteVolume24h":"10307493.92",
        #                 "symbol":"BTC_BRL",
        #                 "timestamp":1599091291083
        #             },
        #         ],
        #         "message":"Success"
        #     }
        #
        data = self.safe_value(response, 'data', [])
        result: dict = {}
        for i in range(0, len(data)):
            ticker = self.parse_ticker(data[i])
            symbol = ticker['symbol']
            result[symbol] = ticker
        return self.filter_by_array_tickers(result, 'symbol', symbols)

    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://doc.novadax.com/en-US/#get-market-depth

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit  # default 10, max 20
        response = self.publicGetMarketDepth(self.extend(request, params))
        #
        #     {
        #         "code":"A10000",
        #         "data":{
        #             "asks":[
        #                 ["0.037159","0.3741"],
        #                 ["0.037215","0.2706"],
        #                 ["0.037222","1.8459"],
        #             ],
        #             "bids":[
        #                 ["0.037053","0.3857"],
        #                 ["0.036969","0.8101"],
        #                 ["0.036953","1.5226"],
        #             ],
        #             "timestamp":1599280414448
        #         },
        #         "message":"Success"
        #     }
        #
        data = self.safe_value(response, 'data', {})
        timestamp = self.safe_integer(data, 'timestamp')
        return self.parse_order_book(data, market['symbol'], timestamp, 'bids', 'asks')

    def parse_trade(self, trade: dict, market: Market = None) -> Trade:
        #
        # public fetchTrades
        #
        #     {
        #         "amount":"0.0632",
        #         "price":"0.037288",
        #         "side":"BUY",
        #         "timestamp":1599279694576
        #     }
        #
        # private fetchOrderTrades
        #
        #      {
        #          "id": "608717046691139584",
        #          "orderId": "608716957545402368",
        #          "symbol": "BTC_BRL",
        #          "side": "BUY",
        #          "amount": "0.0988",
        #          "price": "45514.76",
        #          "fee": "0.0000988 BTC",
        #          "feeAmount": "0.0000988",
        #          "feeCurrency": "BTC",
        #          "role": "MAKER",
        #          "timestamp": 1565171053345
        #       }
        #
        # private fetchMyTrades(same endpoint)
        #
        #      {
        #          "id": "608717046691139584",
        #          "orderId": "608716957545402368",
        #          "symbol": "BTC_BRL",
        #          "side": "BUY",
        #          "amount": "0.0988",
        #          "price": "45514.76",
        #          "fee": "0.0000988 BTC",
        #          "feeAmount": "0.0000988",
        #          "feeCurrency": "BTC",
        #          "role": "MAKER",
        #          "timestamp": 1565171053345
        #       }
        #
        id = self.safe_string(trade, 'id')
        orderId = self.safe_string(trade, 'orderId')
        timestamp = self.safe_integer(trade, 'timestamp')
        side = self.safe_string_lower(trade, 'side')
        priceString = self.safe_string(trade, 'price')
        amountString = self.safe_string(trade, 'amount')
        marketId = self.safe_string(trade, 'symbol')
        symbol = self.safe_symbol(marketId, market, '_')
        takerOrMaker = self.safe_string_lower(trade, 'role')
        feeString = self.safe_string(trade, 'fee')
        fee = None
        if feeString is not None:
            feeCurrencyId = self.safe_string(trade, 'feeCurrency')
            feeCurrencyCode = self.safe_currency_code(feeCurrencyId)
            fee = {
                'cost': self.safe_string(trade, 'feeAmount'),
                'currency': feeCurrencyCode,
            }
        return self.safe_trade({
            'id': id,
            'order': orderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': symbol,
            'type': None,
            'side': side,
            'price': priceString,
            'amount': amountString,
            'cost': None,
            'takerOrMaker': takerOrMaker,
            'fee': fee,
            'info': trade,
        }, market)

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

        https://doc.novadax.com/en-US/#get-recent-trades

        :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>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit  # default 100
        response = self.publicGetMarketTrades(self.extend(request, params))
        #
        #     {
        #         "code":"A10000",
        #         "data":[
        #             {"amount":"0.0632","price":"0.037288","side":"BUY","timestamp":1599279694576},
        #             {"amount":"0.0052","price":"0.03715","side":"SELL","timestamp":1599276606852},
        #             {"amount":"0.0058","price":"0.037188","side":"SELL","timestamp":1599275187812},
        #         ],
        #         "message":"Success"
        #     }
        #
        data = self.safe_list(response, 'data', [])
        return self.parse_trades(data, market, since, limit)

    def fetch_ohlcv(self, symbol: str, timeframe: str = '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://doc.novadax.com/en-US/#get-kline-data

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
            'unit': self.safe_string(self.timeframes, timeframe, timeframe),
        }
        duration = self.parse_timeframe(timeframe)
        now = self.seconds()
        if limit is None:
            limit = 3000  # max
        if since is None:
            request['from'] = now - limit * duration
            request['to'] = now
        else:
            startFrom = self.parse_to_int(since / 1000)
            request['from'] = startFrom
            request['to'] = self.sum(startFrom, limit * duration)
        response = self.publicGetMarketKlineHistory(self.extend(request, params))
        #
        #     {
        #         "code": "A10000",
        #         "data": [
        #             {
        #                 "amount": 8.25709100,
        #                 "closePrice": 62553.20,
        #                 "count": 29,
        #                 "highPrice": 62592.87,
        #                 "lowPrice": 62553.20,
        #                 "openPrice": 62554.23,
        #                 "score": 1602501480,
        #                 "symbol": "BTC_BRL",
        #                 "vol": 516784.2504067500
        #             }
        #         ],
        #         "message": "Success"
        #     }
        #
        data = self.safe_list(response, 'data', [])
        return self.parse_ohlcvs(data, market, timeframe, since, limit)

    def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
        #
        #     {
        #         "amount": 8.25709100,
        #         "closePrice": 62553.20,
        #         "count": 29,
        #         "highPrice": 62592.87,
        #         "lowPrice": 62553.20,
        #         "openPrice": 62554.23,
        #         "score": 1602501480,
        #         "symbol": "BTC_BRL",
        #         "vol": 516784.2504067500
        #     }
        #
        options = self.safe_value(self.options, 'fetchOHLCV', {})
        volumeField = self.safe_string(options, 'volume', 'amount')  # or vol
        return [
            self.safe_timestamp(ohlcv, 'score'),
            self.safe_number(ohlcv, 'openPrice'),
            self.safe_number(ohlcv, 'highPrice'),
            self.safe_number(ohlcv, 'lowPrice'),
            self.safe_number(ohlcv, 'closePrice'),
            self.safe_number(ohlcv, volumeField),
        ]

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

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

        https://doc.novadax.com/en-US/#get-account-balance

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        """
        self.load_markets()
        response = self.privateGetAccountGetBalance(params)
        #
        #     {
        #         "code": "A10000",
        #         "data": [
        #             {
        #                 "available": "1.23",
        #                 "balance": "0.23",
        #                 "currency": "BTC",
        #                 "hold": "1"
        #             }
        #         ],
        #         "message": "Success"
        #     }
        #
        return self.parse_balance(response)

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

        https://doc.novadax.com/en-US/#order-introduction

        :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 you want to trade in units of the 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.cost]: for spot market buy orders, the quote quantity that can be used alternative for the amount
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        uppercaseType = type.upper()
        uppercaseSide = side.upper()
        request: dict = {
            'symbol': market['id'],
            'side': uppercaseSide,  # or SELL
            # "amount": self.amount_to_precision(symbol, amount),
            # "price": "1234.5678",  # required for LIMIT and STOP orders
            # "operator": ""  # for stop orders, can be found in order introduction
            # "stopPrice": self.price_to_precision(symbol, stopPrice),
            # "accountId": "...",  # subaccount id, optional
        }
        triggerPrice = self.safe_value_2(params, 'triggerPrice', 'stopPrice')
        if triggerPrice is None:
            if (uppercaseType == 'STOP_LIMIT') or (uppercaseType == 'STOP_MARKET'):
                raise ArgumentsRequired(self.id + ' createOrder() requires a stopPrice parameter for ' + uppercaseType + ' orders')
        else:
            if uppercaseType == 'LIMIT':
                uppercaseType = 'STOP_LIMIT'
            elif uppercaseType == 'MARKET':
                uppercaseType = 'STOP_MARKET'
            defaultOperator = 'LTE' if (uppercaseSide == 'BUY') else 'GTE'
            request['operator'] = self.safe_string(params, 'operator', defaultOperator)
            request['stopPrice'] = self.price_to_precision(symbol, triggerPrice)
            params = self.omit(params, ['triggerPrice', 'stopPrice'])
        if (uppercaseType == 'LIMIT') or (uppercaseType == 'STOP_LIMIT'):
            request['price'] = self.price_to_precision(symbol, price)
            request['amount'] = self.amount_to_precision(symbol, amount)
        elif (uppercaseType == 'MARKET') or (uppercaseType == 'STOP_MARKET'):
            if uppercaseSide == 'SELL':
                request['amount'] = self.amount_to_precision(symbol, amount)
            elif uppercaseSide == 'BUY':
                quoteAmount = None
                createMarketBuyOrderRequiresPrice = True
                createMarketBuyOrderRequiresPrice, params = self.handle_option_and_params(params, 'createOrder', 'createMarketBuyOrderRequiresPrice', True)
                cost = self.safe_number_2(params, 'cost', 'value')
                params = self.omit(params, 'cost')
                if cost is not None:
                    quoteAmount = self.cost_to_precision(symbol, cost)
                elif createMarketBuyOrderRequiresPrice:
                    if price is None:
                        raise InvalidOrder(self.id + ' createOrder() requires the price argument for market buy orders to calculate the total cost to spend(amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to False and pass the cost to spend(quote quantity) in the amount argument')
                    else:
                        amountString = self.number_to_string(amount)
                        priceString = self.number_to_string(price)
                        costRequest = Precise.string_mul(amountString, priceString)
                        quoteAmount = self.cost_to_precision(symbol, costRequest)
                else:
                    quoteAmount = self.cost_to_precision(symbol, amount)
                request['value'] = quoteAmount
        request['type'] = uppercaseType
        response = self.privatePostOrdersCreate(self.extend(request, params))
        #
        #     {
        #         "code": "A10000",
        #         "data": {
        #             "amount": "0.001",
        #             "averagePrice": null,
        #             "filledAmount": "0",
        #             "filledFee": "0",
        #             "filledValue": "0",
        #             "id": "870613508008464384",
        #             "operator": "GTE",
        #             "price": "210000",
        #             "side": "BUY",
        #             "status": "SUBMITTED",
        #             "stopPrice": "211000",
        #             "symbol": "BTC_BRL",
        #             "timestamp": 1627612035528,
        #             "type": "STOP_LIMIT",
        #             "value": "210"
        #         },
        #         "message": "Success"
        #     }
        #
        data = self.safe_dict(response, 'data', {})
        return self.parse_order(data, market)

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

        https://doc.novadax.com/en-US/#cancel-an-order

        :param str id: order id
        :param str symbol: not used by novadax cancelOrder()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        request: dict = {
            'id': id,
        }
        response = self.privatePostOrdersCancel(self.extend(request, params))
        #
        #     {
        #         "code": "A10000",
        #         "data": {
        #             "result": True
        #         },
        #         "message": "Success"
        #     }
        #
        data = self.safe_dict(response, 'data', {})
        return self.parse_order(data)

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

        https://doc.novadax.com/en-US/#get-order-details

        :param str id: order id
        :param str symbol: not used by novadax fetchOrder
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        request: dict = {
            'id': id,
        }
        response = self.privateGetOrdersGet(self.extend(request, params))
        #
        #     {
        #         "code": "A10000",
        #         "data": {
        #             "id": "608695623247466496",
        #             "symbol": "BTC_BRL",
        #             "type": "MARKET",
        #             "side": "SELL",
        #             "price": null,
        #             "averagePrice": "0",
        #             "amount": "0.123",
        #             "filledAmount": "0",
        #             "value": null,
        #             "filledValue": "0",
        #             "filledFee": "0",
        #             "status": "REJECTED",
        #             "timestamp": 1565165945588
        #         },
        #         "message": "Success"
        #     }
        #
        data = self.safe_dict(response, 'data', {})
        return self.parse_order(data)

    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://doc.novadax.com/en-US/#get-order-history

        :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>`
        """
        self.load_markets()
        request: dict = {
            # 'symbol': market['id'],
            # 'status': 'SUBMITTED,PROCESSING',  # SUBMITTED, PROCESSING, PARTIAL_FILLED, CANCELING, FILLED, CANCELED, REJECTED
            # 'fromId': '...',  # order id to begin with
            # 'toId': '...',  # order id to end up with
            # 'fromTimestamp': since,
            # 'toTimestamp': self.milliseconds(),
            # 'limit': limit,  # default 100, max 100
        }
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if limit is not None:
            request['limit'] = limit  # default 100, max 100
        if since is not None:
            request['fromTimestamp'] = since
        response = self.privateGetOrdersList(self.extend(request, params))
        #
        #     {
        #         "code": "A10000",
        #         "data": [
        #             {
        #                 "id": "608695678650028032",
        #                 "symbol": "BTC_BRL",
        #                 "type": "MARKET",
        #                 "side": "SELL",
        #                 "price": null,
        #                 "averagePrice": "0",
        #                 "amount": "0.123",
        #                 "filledAmount": "0",
        #                 "value": null,
        #                 "filledValue": "0",
        #                 "filledFee": "0",
        #                 "status": "REJECTED",
        #                 "timestamp": 1565165958796
        #             },
        #         ],
        #         "message": "Success"
        #     }
        #
        data = self.safe_list(response, 'data', [])
        return self.parse_orders(data, market, since, limit)

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

        https://doc.novadax.com/en-US/#get-order-history

        :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': 'SUBMITTED,PROCESSING,PARTIAL_FILLED,CANCELING',
        }
        return self.fetch_orders(symbol, since, limit, self.extend(request, params))

    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://doc.novadax.com/en-US/#get-order-history

        :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>`
        """
        request: dict = {
            'status': 'FILLED,CANCELED,REJECTED',
        }
        return self.fetch_orders(symbol, since, limit, self.extend(request, params))

    def fetch_order_trades(self, id: str, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        fetch all the trades made from a single order

        https://doc.novadax.com/en-US/#get-order-match-details

        :param str id: order id
        :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 to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        """
        self.load_markets()
        request: dict = {
            'id': id,
        }
        response = self.privateGetOrdersFill(self.extend(request, params))
        market = None
        if symbol is not None:
            market = self.market(symbol)
        data = self.safe_value(response, 'data', [])
        #
        #      {
        #          "code": "A10000",
        #          "data": [
        #              {
        #                  "id": "608717046691139584",
        #                  "orderId": "608716957545402368",
        #                  "symbol": "BTC_BRL",
        #                  "side": "BUY",
        #                  "amount": "0.0988",
        #                  "price": "45514.76",
        #                  "fee": "0.0000988 BTC",
        #                  "feeAmount": "0.0000988",
        #                  "feeCurrency": "BTC",
        #                  "role": "MAKER",
        #                  "timestamp": 1565171053345
        #              },
        #          ],
        #          "message": "Success"
        #      }
        #
        return self.parse_trades(data, market, since, limit)

    def parse_order_status(self, status: Str):
        statuses: dict = {
            'SUBMITTED': 'open',
            'PROCESSING': 'open',
            'PARTIAL_FILLED': 'open',
            'CANCELING': 'open',
            'FILLED': 'closed',
            'CANCELED': 'canceled',
            'REJECTED': 'rejected',
        }
        return self.safe_string(statuses, status, status)

    def parse_order(self, order: dict, market: Market = None) -> Order:
        #
        # createOrder, fetchOrders, fetchOrder
        #
        #     {
        #         "amount": "0.001",
        #         "averagePrice": null,
        #         "filledAmount": "0",
        #         "filledFee": "0",
        #         "filledValue": "0",
        #         "id": "870613508008464384",
        #         "operator": "GTE",
        #         "price": "210000",
        #         "side": "BUY",
        #         "status": "SUBMITTED",
        #         "stopPrice": "211000",
        #         "symbol": "BTC_BRL",
        #         "timestamp": 1627612035528,
        #         "type": "STOP_LIMIT",
        #         "value": "210"
        #     }
        #
        # cancelOrder
        #
        #     {
        #         "result": True
        #     }
        #
        id = self.safe_string(order, 'id')
        amount = self.safe_string(order, 'amount')
        price = self.safe_string(order, 'price')
        cost = self.safe_string_2(order, 'filledValue', 'value')
        type = self.safe_string_lower(order, 'type')
        side = self.safe_string_lower(order, 'side')
        status = self.parse_order_status(self.safe_string(order, 'status'))
        timestamp = self.safe_integer(order, 'timestamp')
        average = self.safe_string(order, 'averagePrice')
        filled = self.safe_string(order, 'filledAmount')
        fee = None
        feeCost = self.safe_number(order, 'filledFee')
        if feeCost is not None:
            fee = {
                'cost': feeCost,
                'currency': None,
            }
        marketId = self.safe_string(order, 'symbol')
        symbol = self.safe_symbol(marketId, market, '_')
        return self.safe_order({
            'id': id,
            'clientOrderId': None,
            'info': order,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'symbol': symbol,
            'type': type,
            'timeInForce': None,
            'postOnly': None,
            'side': side,
            'price': price,
            'triggerPrice': self.safe_number(order, 'stopPrice'),
            'amount': amount,
            'cost': cost,
            'average': average,
            'filled': filled,
            'remaining': None,
            'status': status,
            'fee': fee,
            'trades': None,
        }, market)

    def transfer(self, code: str, amount: float, fromAccount: str, toAccount: str, params={}) -> TransferEntry:
        """
        transfer currency internally between wallets on the same account

        https://doc.novadax.com/en-US/#get-sub-account-transfer

        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account to transfer from
        :param str toAccount: account to transfer to
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        """
        self.load_markets()
        currency = self.currency(code)
        if fromAccount != 'main' and toAccount != 'main':
            raise ExchangeError(self.id + ' transfer() supports transfers between main account and subaccounts only')
        # master-transfer-in = from master account to subaccount
        # master-transfer-out = from subaccount to master account
        type = 'master-transfer-in' if (fromAccount == 'main') else 'master-transfer-out'
        request: dict = {
            'transferAmount': self.currency_to_precision(code, amount),
            'currency': currency['id'],
            'subId': toAccount if (type == 'master-transfer-in') else fromAccount,
            'transferType': type,
        }
        response = self.privatePostAccountSubsTransfer(self.extend(request, params))
        #
        #    {
        #        "code":"A10000",
        #        "message":"Success",
        #        "data":40
        #    }
        #
        transfer = self.parse_transfer(response, currency)
        transferOptions = self.safe_value(self.options, 'transfer', {})
        fillResponseFromRequest = self.safe_bool(transferOptions, 'fillResponseFromRequest', True)
        if fillResponseFromRequest:
            transfer['fromAccount'] = fromAccount
            transfer['toAccount'] = toAccount
            transfer['amount'] = amount
        return transfer

    def parse_transfer(self, transfer: dict, currency: Currency = None) -> TransferEntry:
        #
        #    {
        #        "code":"A10000",
        #        "message":"Success",
        #        "data":40
        #    }
        #
        id = self.safe_string(transfer, 'data')
        status = self.safe_string(transfer, 'message')
        currencyCode = self.safe_currency_code(None, currency)
        return {
            'info': transfer,
            'id': id,
            'amount': None,
            'currency': currencyCode,
            'fromAccount': None,
            'toAccount': None,
            'timestamp': None,
            'datetime': None,
            'status': status,
        }

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

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

        https://doc.novadax.com/en-US/#send-cryptocurrencies

        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        tag, params = self.handle_withdraw_tag_and_params(tag, params)
        self.load_markets()
        currency = self.currency(code)
        request: dict = {
            'code': currency['id'],
            'amount': self.currency_to_precision(code, amount),
            'wallet': address,
        }
        if tag is not None:
            request['tag'] = tag
        response = self.privatePostAccountWithdrawCoin(self.extend(request, params))
        #
        #     {
        #         "code":"A10000",
        #         "data": "DR123",
        #         "message":"Success"
        #     }
        #
        return self.parse_transaction(response, currency)

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

        https://doc.novadax.com/en-US/#get-sub-account-list

        :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 = self.privateGetAccountSubs(params)
        #
        #     {
        #         "code": "A10000",
        #         "data": [
        #             {
        #                 "subId": "CA648856083527372800",
        #                 "state": "Normal",
        #                 "subAccount": "003",
        #                 "subIdentify": "003"
        #             }
        #         ],
        #         "message": "Success"
        #     }
        #
        data = self.safe_value(response, 'data', [])
        result = []
        for i in range(0, len(data)):
            account = data[i]
            accountId = self.safe_string(account, 'subId')
            type = self.safe_string(account, 'subAccount')
            result.append({
                'id': accountId,
                'type': type,
                'currency': None,
                'info': account,
            })
        return result

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

        https://doc.novadax.com/en-US/#wallet-records-of-deposits-and-withdraws

        :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>`
        """
        request: dict = {
            'type': 'coin_in',
        }
        return self.fetch_deposits_withdrawals(code, since, limit, self.extend(request, params))

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

        https://doc.novadax.com/en-US/#wallet-records-of-deposits-and-withdraws

        :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>`
        """
        request: dict = {
            'type': 'coin_out',
        }
        return self.fetch_deposits_withdrawals(code, since, limit, self.extend(request, params))

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

        https://doc.novadax.com/en-US/#wallet-records-of-deposits-and-withdraws

        :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>`
        """
        self.load_markets()
        request: dict = {
            # 'currency': currency['id'],
            # 'type': 'coin_in',  # 'coin_out'
            # 'direct': 'asc',  # 'desc'
            # 'size': limit,  # default 100
            # 'start': id,  # offset id
        }
        currency = None
        if code is not None:
            currency = self.currency(code)
            request['currency'] = currency['id']
        if limit is not None:
            request['size'] = limit
        response = self.privateGetWalletQueryDepositWithdraw(self.extend(request, params))
        #
        #     {
        #         "code": "A10000",
        #         "data": [
        #             {
        #                 "id": "DR562339304588709888",
        #                 "type": "COIN_IN",
        #                 "currency": "XLM",
        #                 "chain": "XLM",
        #                 "address": "GCUTK7KHPJC3ZQJ3OMWWFHAK2OXIBRD4LNZQRCCOVE7A2XOPP2K5PU5Q",
        #                 "addressTag": "1000009",
        #                 "amount": 1.0,
        #                 "state": "SUCCESS",
        #                 "txHash": "39210645748822f8d4ce673c7559aa6622e6e9cdd7073bc0fcae14b1edfda5f4",
        #                 "createdAt": 1554113737000,
        #                 "updatedAt": 1601371273000
        #             }
        #         ],
        #         "message": "Success"
        #     }
        #
        data = self.safe_list(response, 'data', [])
        return self.parse_transactions(data, currency, since, limit)

    def parse_transaction_status(self, status: Str):
        # Pending the record is wait broadcast to chain
        # x/M confirming the comfirming state of tx, the M is total confirmings needed
        # SUCCESS the record is success full
        # FAIL the record failed
        parts = status.split(' ')
        status = self.safe_string(parts, 1, status)
        statuses: dict = {
            'Pending': 'pending',
            'confirming': 'pending',
            'SUCCESS': 'ok',
            'FAIL': 'failed',
        }
        return self.safe_string(statuses, status, status)

    def parse_transaction(self, transaction: dict, currency: Currency = None) -> Transaction:
        #
        # withdraw
        #
        #     {
        #         "code":"A10000",
        #         "data": "DR123",
        #         "message":"Success"
        #     }
        #
        # fetchDepositsWithdrawals
        #
        #     {
        #         "id": "DR562339304588709888",
        #         "type": "COIN_IN",
        #         "currency": "XLM",
        #         "chain": "XLM",
        #         "address": "GCUTK7KHPJC3ZQJ3OMWWFHAK2OXIBRD4LNZQRCCOVE7A2XOPP2K5PU5Q",
        #         "addressTag": "1000009",
        #         "amount": 1.0,
        #         "state": "SUCCESS",
        #         "txHash": "39210645748822f8d4ce673c7559aa6622e6e9cdd7073bc0fcae14b1edfda5f4",
        #         "createdAt": 1554113737000,
        #         "updatedAt": 1601371273000
        #     }
        #
        id = self.safe_string_2(transaction, 'id', 'data')
        type = self.safe_string(transaction, 'type')
        if type == 'COIN_IN':
            type = 'deposit'
        elif type == 'COIN_OUT':
            type = 'withdraw'
        amount = self.safe_number(transaction, 'amount')
        address = self.safe_string(transaction, 'address')
        tag = self.safe_string(transaction, 'addressTag')
        txid = self.safe_string(transaction, 'txHash')
        timestamp = self.safe_integer(transaction, 'createdAt')
        updated = self.safe_integer(transaction, 'updatedAt')
        currencyId = self.safe_string(transaction, 'currency')
        code = self.safe_currency_code(currencyId, currency)
        status = self.parse_transaction_status(self.safe_string(transaction, 'state'))
        network = self.safe_string(transaction, 'chain')
        return {
            'info': transaction,
            'id': id,
            'currency': code,
            'amount': amount,
            'network': network,
            'address': address,
            'addressTo': address,
            'addressFrom': None,
            'tag': tag,
            'tagTo': tag,
            'tagFrom': None,
            'status': status,
            'type': type,
            'updated': updated,
            'txid': txid,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'comment': None,
            'internal': None,
            'fee': {
                'currency': None,
                'cost': None,
                'rate': None,
            },
        }

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

        https://doc.novadax.com/en-US/#get-order-history

        :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>`
        """
        self.load_markets()
        request: dict = {
            #  'orderId': id,  # Order ID, string
            #  'symbol': market['id'],  # The trading symbol, like BTC_BRL, string
            #  'fromId': fromId,  # Search fill id to begin with, string
            #  'toId': toId,  # Search fill id to end up with, string
            #  'fromTimestamp': since,  # Search order fill time to begin with, in milliseconds, string
            #  'toTimestamp': self.milliseconds(),  # Search order fill time to end up with, in milliseconds, string
            #  'limit': limit,  # The number of fills to return, default 100, max 100, string
            #  'accountId': subaccountId,  # Sub account ID, if not informed, the fills will be return under master account, string
        }
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if limit is not None:
            request['limit'] = limit
        if since is not None:
            request['fromTimestamp'] = since
        response = self.privateGetOrdersFills(self.extend(request, params))
        #
        #      {
        #          "code": "A10000",
        #          "data": [
        #              {
        #                  "id": "608717046691139584",
        #                  "orderId": "608716957545402368",
        #                  "symbol": "BTC_BRL",
        #                  "side": "BUY",
        #                  "amount": "0.0988",
        #                  "price": "45514.76",
        #                  "fee": "0.0000988 BTC",
        #                  "feeAmount": "0.0000988",
        #                  "feeCurrency": "BTC",
        #                  "role": "MAKER",
        #                  "timestamp": 1565171053345
        #              },
        #          ],
        #          "message": "Success"
        #      }
        #
        data = self.safe_list(response, 'data', [])
        return self.parse_trades(data, market, since, limit)

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        request = '/' + self.version + '/' + self.implode_params(path, params)
        url = self.urls['api'][api] + request
        query = self.omit(params, self.extract_params(path))
        if api == 'public':
            if query:
                url += '?' + self.urlencode(query)
        elif api == 'private':
            self.check_required_credentials()
            timestamp = str(self.milliseconds())
            headers = {
                'X-Nova-Access-Key': self.apiKey,
                'X-Nova-Timestamp': timestamp,
            }
            queryString = None
            if method == 'POST':
                body = self.json(query)
                queryString = self.hash(self.encode(body), 'md5')
                headers['Content-Type'] = 'application/json'
            else:
                if query:
                    url += '?' + self.urlencode(query)
                queryString = self.urlencode(self.keysort(query))
            auth = method + "\n" + request + "\n" + queryString + "\n" + timestamp  # eslint-disable-line quotes
            headers['X-Nova-Signature'] = self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha256)
        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
        #
        #     {"code":"A10003","data":[],"message":"Authentication failed, Invalid accessKey."}
        #
        errorCode = self.safe_string(response, 'code')
        if errorCode != 'A10000':
            message = self.safe_string(response, 'message')
            feedback = self.id + ' ' + body
            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
