# -*- 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.aster import ImplicitAPI
import hashlib
from ccxt.base.types import Any, Balances, Currencies, Currency, Int, LedgerEntry, Leverage, Leverages, MarginMode, MarginModes, MarginModification, Market, Num, Order, OrderBook, OrderRequest, OrderSide, OrderType, Position, Str, Strings, Ticker, Tickers, FundingRate, FundingRates, Trade, TradingFeeInterface, 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 OperationRejected
from ccxt.base.errors import NoChange
from ccxt.base.errors import MarketClosed
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import OrderImmediatelyFillable
from ccxt.base.errors import OrderNotFillable
from ccxt.base.errors import DuplicateOrderId
from ccxt.base.errors import NotSupported
from ccxt.base.errors import ExchangeClosedByUser
from ccxt.base.errors import OperationFailed
from ccxt.base.errors import NetworkError
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.errors import InvalidNonce
from ccxt.base.errors import RequestTimeout
from ccxt.base.errors import BadResponse
from ccxt.base.decimal_to_precision import TRUNCATE
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class aster(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(aster, self).describe(), {
            'id': 'aster',
            'name': 'Aster',
            'countries': ['US'],
            # 3 req/s for free
            # 150 req/s for subscribers: https://aster.markets/data
            # for brokers: https://aster.markets/docs/api-references/broker-api/#authentication-and-rate-limit
            'rateLimit': 333,
            'hostname': 'aster.markets',
            'certified': False,
            'pro': True,
            'dex': True,
            'urls': {
                'logo': 'https://github.com/user-attachments/assets/4982201b-73cd-4d7a-8907-e69e239e9609',
                'www': 'https://www.asterdex.com/en',
                'api': {
                    'fapiPublic': 'https://fapi.asterdex.com/fapi',
                    'fapiPrivate': 'https://fapi.asterdex.com/fapi',
                    'sapiPublic': 'https://sapi.asterdex.com/api',
                    'sapiPrivate': 'https://sapi.asterdex.com/api',
                },
                'doc': 'https://github.com/asterdex/api-docs',
                'fees': 'https://docs.asterdex.com/product/asterex-simple/fees-and-slippage',
                'referral': {
                    'url': 'https://www.asterdex.com/en/referral/aA1c2B',
                    'discount': 0.1,
                },
            },
            'has': {
                'CORS': None,
                'spot': False,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'addMargin': True,
                'borrowCrossMargin': False,
                'borrowIsolatedMargin': False,
                'cancelAllOrders': True,
                'cancelOrder': True,
                'cancelOrders': True,
                'closeAllPositions': False,
                'closePosition': False,
                'createConvertTrade': False,
                'createDepositAddress': False,
                'createLimitBuyOrder': False,
                'createLimitSellOrder': False,
                'createMarketBuyOrder': False,
                'createMarketBuyOrderWithCost': False,
                'createMarketOrderWithCost': False,
                'createMarketSellOrder': False,
                'createMarketSellOrderWithCost': False,
                'createOrder': True,
                'createOrders': False,
                'createOrderWithTakeProfitAndStopLoss': False,
                'createPostOnlyOrder': False,
                'createReduceOnlyOrder': False,
                'createStopLimitOrder': False,
                'createStopLossOrder': False,
                'createStopMarketOrder': False,
                'createStopOrder': False,
                'createTakeProfitOrder': False,
                'createTrailingPercentOrder': False,
                'createTriggerOrder': False,
                'editOrder': False,
                'editOrders': False,
                'fetchAccounts': None,
                'fetchBalance': True,
                'fetchBidsAsks': False,
                'fetchBorrowInterest': False,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchCanceledAndClosedOrders': 'emulated',
                'fetchCanceledOrders': 'emulated',
                'fetchClosedOrder': False,
                'fetchClosedOrders': 'emulated',
                'fetchConvertCurrencies': False,
                'fetchConvertQuote': False,
                'fetchConvertTrade': False,
                'fetchConvertTradeHistory': False,
                'fetchCrossBorrowRate': False,
                'fetchCrossBorrowRates': False,
                'fetchCurrencies': True,
                'fetchDeposit': False,
                'fetchDepositAddress': False,
                'fetchDepositAddresses': False,
                'fetchDepositAddressesByNetwork': False,
                'fetchDeposits': False,
                'fetchDepositsWithdrawals': False,
                'fetchDepositWithdrawFee': 'emulated',
                'fetchDepositWithdrawFees': False,
                'fetchFundingHistory': True,
                'fetchFundingInterval': 'emulated',
                'fetchFundingIntervals': True,
                'fetchFundingRate': True,
                'fetchFundingRateHistory': True,
                'fetchFundingRates': True,
                'fetchGreeks': False,
                'fetchIndexOHLCV': False,
                'fetchIsolatedBorrowRate': 'emulated',
                'fetchIsolatedBorrowRates': False,
                'fetchL3OrderBook': False,
                'fetchLastPrices': False,
                'fetchLedger': True,
                'fetchLedgerEntry': False,
                'fetchLeverage': 'emulated',
                'fetchLeverages': True,
                'fetchLeverageTiers': False,
                'fetchLiquidations': False,
                'fetchLongShortRatio': False,
                'fetchLongShortRatioHistory': False,
                'fetchMarginAdjustmentHistory': True,
                'fetchMarginMode': 'emulated',
                'fetchMarginModes': True,
                'fetchMarketLeverageTiers': 'emulated',
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMarkPrice': False,
                'fetchMarkPrices': False,
                'fetchMyLiquidations': False,
                'fetchMySettlementHistory': False,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenInterest': False,
                'fetchOpenInterestHistory': False,
                'fetchOpenOrder': True,
                'fetchOpenOrders': True,
                'fetchOption': False,
                'fetchOptionChain': False,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrderBooks': False,
                'fetchOrders': True,
                'fetchOrderTrades': False,
                'fetchPosition': False,
                'fetchPositionHistory': False,
                'fetchPositionMode': True,
                'fetchPositions': True,
                'fetchPositionsHistory': False,
                'fetchPositionsRisk': True,
                'fetchPremiumIndexOHLCV': False,
                'fetchSettlementHistory': False,
                'fetchStatus': False,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTime': True,
                'fetchTrades': True,
                'fetchTradingFee': True,
                'fetchTradingFees': False,
                'fetchTradingLimits': 'emulated',
                'fetchTransactionFee': 'emulated',
                'fetchTransactionFees': False,
                'fetchTransactions': False,
                'fetchTransfer': False,
                'fetchTransfers': False,
                'fetchUnderlyingAssets': False,
                'fetchVolatilityHistory': False,
                'fetchWithdrawAddresses': False,
                'fetchWithdrawal': False,
                'fetchWithdrawals': False,
                'fetchWithdrawalWhitelist': False,
                'reduceMargin': True,
                'repayCrossMargin': False,
                'repayIsolatedMargin': False,
                'sandbox': False,
                'setLeverage': True,
                'setMargin': False,
                'setMarginMode': True,
                'setPositionMode': True,
                'signIn': False,
                'transfer': True,
                'withdraw': True,
            },
            'api': {
                'fapiPublic': {
                    'get': [
                        'v1/ping',
                        'v1/time',
                        'v1/exchangeInfo',
                        'v1/depth',
                        'v1/trades',
                        'v1/historicalTrades',
                        'v1/aggTrades',
                        'v1/klines',
                        'v1/indexPriceKlines',
                        'v1/markPriceKlines',
                        'v1/premiumIndex',
                        'v1/fundingRate',
                        'v1/fundingInfo',
                        'v1/ticker/24hr',
                        'v1/ticker/price',
                        'v1/ticker/bookTicker',
                        'v1/adlQuantile',
                        'v1/forceOrders',
                    ],
                },
                'fapiPrivate': {
                    'get': [
                        'v1/positionSide/dual',
                        'v1/multiAssetsMargin',
                        'v1/order',
                        'v1/openOrder',
                        'v1/openOrders',
                        'v1/allOrders',
                        'v2/balance',
                        'v3/balance',
                        'v3/account',
                        'v4/account',
                        'v1/positionMargin/history',
                        'v2/positionRisk',
                        'v3/positionRisk',
                        'v1/userTrades',
                        'v1/income',
                        'v1/leverageBracket',
                        'v1/commissionRate',
                    ],
                    'post': [
                        'v1/positionSide/dual',
                        'v1/multiAssetsMargin',
                        'v1/order',
                        'v1/order/test',
                        'v1/batchOrders',
                        'v1/asset/wallet/transfer',
                        'v1/countdownCancelAll',
                        'v1/leverage',
                        'v1/marginType',
                        'v1/positionMargin',
                        'v1/listenKey',
                    ],
                    'put': [
                        'v1/listenKey',
                    ],
                    'delete': [
                        'v1/order',
                        'v1/allOpenOrders',
                        'v1/batchOrders',
                        'v1/listenKey',
                    ],
                },
                'sapiPublic': {
                    'get': [
                        'v1/ping',
                        'v1/time',
                        'v1/exchangeInfo',
                        'v1/depth',
                        'v1/trades',
                        'v1/historicalTrades',
                        'v1/aggTrades',
                        'v1/klines',
                        'v1/ticker/24hr',
                        'v1/ticker/price',
                        'v1/ticker/bookTicker',
                        'v1/aster/withdraw/estimateFee',
                    ],
                },
                'sapiPrivate': {
                    'get': [
                        'v1/commissionRate',
                        'v1/order',
                        'v1/openOrders',
                        'v1/allOrders',
                        'v1/transactionHistory',
                        'v1/account',
                        'v1/userTrades',
                    ],
                    'post': [
                        'v1/order',
                        'v1/asset/wallet/transfer',
                        'v1/asset/sendToAddress',
                        'v1/aster/user-withdraw',
                        'v1/listenKey',
                    ],
                    'put': [
                        'v1/listenKey',
                    ],
                    'delete': [
                        'v1/order',
                        'v1/allOpenOrders',
                        'v1/listenKey',
                    ],
                },
            },
            'timeframes': {
                '1m': '1m',
                '3m': '3m',
                '5m': '5m',
                '15m': '15m',
                '30m': '30m',
                '1h': '1h',
                '2h': '2h',
                '4h': '4h',
                '6h': '6h',
                '8h': '8h',
                '12h': '12h',
                '1d': '1d',
                '3d': '3d',
                '1w': '1w',
                '1M': '1M',
            },
            'precisionMode': TICK_SIZE,
            'requiredCredentials': {
                'apiKey': True,
                'secret': True,
            },
            'fees': {
                'trading': {
                    'tierBased': True,
                    'percentage': True,
                    'maker': self.parse_number('0.0001'),
                    'taker': self.parse_number('0.00035'),
                },
            },
            'options': {
                'defaultType': 'spot',
                'recvWindow': 10 * 1000,  # 10 sec
                'defaultTimeInForce': 'GTC',  # 'GTC' = Good To Cancel(default), 'IOC' = Immediate Or Cancel
                'zeroAddress': '0x0000000000000000000000000000000000000000',
                'quoteOrderQty': True,  # whether market orders support amounts in quote currency
                'accountsByType': {
                    'spot': 'SPOT',
                    'future': 'FUTURE',
                    'linear': 'FUTURE',
                    'swap': 'FUTURE',
                },
                'networks': {
                    'ERC20': 'ETH',
                    'BEP20': 'BSC',
                    'ARB': 'Arbitrum',
                },
                'networksToChainId': {
                    'ETH': 1,
                    'BSC': 56,
                    'Arbitrum': 42161,
                },
            },
            'exceptions': {
                'exact': {
                    # 10xx - General Server or Network issues
                    '-1000': OperationFailed,  # UNKNOWN
                    '-1001': NetworkError,  # DISCONNECTED
                    '-1002': AuthenticationError,  # UNAUTHORIZED
                    '-1003': RateLimitExceeded,  # TOO_MANY_REQUESTS
                    '-1004': DuplicateOrderId,  # DUPLICATE_IP
                    '-1005': BadRequest,  # NO_SUCH_IP
                    '-1006': BadResponse,  # UNEXPECTED_RESP
                    '-1007': RequestTimeout,  # TIMEOUT
                    '-1010': OperationFailed,  # ERROR_MSG_RECEIVED
                    '-1011': PermissionDenied,  # NON_WHITE_LIST
                    '-1013': BadRequest,  # INVALID_MESSAGE
                    '-1014': OrderNotFillable,  # UNKNOWN_ORDER_COMPOSITION
                    '-1015': RateLimitExceeded,  # TOO_MANY_ORDERS
                    '-1016': ExchangeClosedByUser,  # SERVICE_SHUTTING_DOWN
                    '-1020': NotSupported,  # UNSUPPORTED_OPERATION
                    '-1021': InvalidNonce,  # INVALID_TIMESTAMP
                    '-1022': AuthenticationError,  # INVALID_SIGNATURE
                    '-1023': BadRequest,  # START_TIME_GREATER_THAN_END_TIME
                    # 11xx - Request issues
                    '-1100': BadRequest,  # ILLEGAL_CHARS
                    '-1101': BadRequest,  # TOO_MANY_PARAMETERS
                    '-1102': ArgumentsRequired,  # MANDATORY_PARAM_EMPTY_OR_MALFORMED
                    '-1103': BadRequest,  # UNKNOWN_PARAM
                    '-1104': BadRequest,  # UNREAD_PARAMETERS
                    '-1105': ArgumentsRequired,  # PARAM_EMPTY
                    '-1106': BadRequest,  # PARAM_NOT_REQUIRED
                    '-1108': BadRequest,  # BAD_ASSET
                    '-1109': BadRequest,  # BAD_ACCOUNT
                    '-1110': BadSymbol,  # BAD_INSTRUMENT_TYPE
                    '-1111': BadRequest,  # BAD_PRECISION
                    '-1112': BadRequest,  # NO_DEPTH
                    '-1113': BadRequest,  # WITHDRAW_NOT_NEGATIVE
                    '-1114': BadRequest,  # TIF_NOT_REQUIRED
                    '-1115': InvalidOrder,  # INVALID_TIF
                    '-1116': InvalidOrder,  # INVALID_ORDER_TYPE
                    '-1117': InvalidOrder,  # INVALID_SIDE
                    '-1118': InvalidOrder,  # EMPTY_NEW_CL_ORD_ID
                    '-1119': InvalidOrder,  # EMPTY_ORG_CL_ORD_ID
                    '-1120': BadRequest,  # BAD_INTERVAL
                    '-1121': BadSymbol,  # BAD_SYMBOL
                    '-1125': AuthenticationError,  # INVALID_LISTEN_KEY
                    '-1127': BadRequest,  # MORE_THAN_XX_HOURS
                    '-1128': BadRequest,  # OPTIONAL_PARAMS_BAD_COMBO
                    '-1130': BadRequest,  # INVALID_PARAMETER
                    '-1136': InvalidOrder,  # INVALID_NEW_ORDER_RESP_TYPE
                    # 20xx - Processing Issues
                    '-2010': InvalidOrder,  # NEW_ORDER_REJECTED
                    '-2011': OrderNotFound,  # CANCEL_REJECTED
                    '-2013': OrderNotFound,  # NO_SUCH_ORDER
                    '-2014': AuthenticationError,  # BAD_API_KEY_FMT
                    '-2015': AuthenticationError,  # REJECTED_MBX_KEY
                    '-2016': MarketClosed,  # NO_TRADING_WINDOW
                    '-2018': InsufficientFunds,  # BALANCE_NOT_SUFFICIENT
                    '-2019': InsufficientFunds,  # MARGIN_NOT_SUFFICIEN
                    '-2020': OrderNotFillable,  # UNABLE_TO_FILL
                    '-2021': OrderImmediatelyFillable,  # ORDER_WOULD_IMMEDIATELY_TRIGGER
                    '-2022': OperationRejected,  # REDUCE_ONLY_REJECT
                    '-2023': AccountSuspended,  # USER_IN_LIQUIDATION
                    '-2024': InsufficientFunds,  # POSITION_NOT_SUFFICIENT
                    '-2025': RateLimitExceeded,  # MAX_OPEN_ORDER_EXCEEDED
                    '-2026': NotSupported,  # REDUCE_ONLY_ORDER_TYPE_NOT_SUPPORTED
                    '-2027': BadRequest,  # MAX_LEVERAGE_RATIO
                    '-2028': BadRequest,  # MIN_LEVERAGE_RATIO
                    # 40xx - Filters and other Issues
                    '-4000': InvalidOrder,  # INVALID_ORDER_STATUS
                    '-4001': InvalidOrder,  # PRICE_LESS_THAN_ZERO
                    '-4002': InvalidOrder,  # PRICE_GREATER_THAN_MAX_PRICE
                    '-4003': InvalidOrder,  # QTY_LESS_THAN_ZERO
                    '-4004': InvalidOrder,  # QTY_LESS_THAN_MIN_QTY
                    '-4005': InvalidOrder,  # QTY_GREATER_THAN_MAX_QTY
                    '-4006': InvalidOrder,  # STOP_PRICE_LESS_THAN_ZERO
                    '-4007': InvalidOrder,  # STOP_PRICE_GREATER_THAN_MAX_PRICE
                    '-4008': InvalidOrder,  # TICK_SIZE_LESS_THAN_ZERO
                    '-4009': InvalidOrder,  # MAX_PRICE_LESS_THAN_MIN_PRICE
                    '-4010': InvalidOrder,  # MAX_QTY_LESS_THAN_MIN_QTY
                    '-4011': InvalidOrder,  # STEP_SIZE_LESS_THAN_ZERO
                    '-4012': RateLimitExceeded,  # MAX_NUM_ORDERS_LESS_THAN_ZERO
                    '-4013': InvalidOrder,  # PRICE_LESS_THAN_MIN_PRICE
                    '-4014': InvalidOrder,  # PRICE_NOT_INCREASED_BY_TICK_SIZE
                    '-4015': InvalidOrder,  # INVALID_CL_ORD_ID_LEN
                    '-4016': InvalidOrder,  # PRICE_HIGHTER_THAN_MULTIPLIER_UP
                    '-4017': InvalidOrder,  # MULTIPLIER_UP_LESS_THAN_ZERO
                    '-4018': InvalidOrder,  # MULTIPLIER_DOWN_LESS_THAN_ZERO
                    '-4019': BadRequest,  # COMPOSITE_SCALE_OVERFLOW
                    '-4020': BadRequest,  # TARGET_STRATEGY_INVALID
                    '-4021': BadRequest,  # INVALID_DEPTH_LIMIT
                    '-4022': MarketClosed,  # WRONG_MARKET_STATUS
                    '-4023': InvalidOrder,  # QTY_NOT_INCREASED_BY_STEP_SIZE
                    '-4024': InvalidOrder,  # PRICE_LOWER_THAN_MULTIPLIER_DOWN
                    '-4025': BadRequest,  # MULTIPLIER_DECIMAL_LESS_THAN_ZERO
                    '-4026': BadRequest,  # COMMISSION_INVALID
                    '-4027': BadRequest,  # INVALID_ACCOUNT_TYPE
                    '-4028': BadRequest,  # INVALID_LEVERAGE
                    '-4029': BadRequest,  # INVALID_TICK_SIZE_PRECISION
                    '-4030': BadRequest,  # INVALID_STEP_SIZE_PRECISION
                    '-4031': BadRequest,  # INVALID_WORKING_TYPE
                    '-4032': RateLimitExceeded,  # EXCEED_MAX_CANCEL_ORDER_SIZE
                    '-4033': AccountNotEnabled,  # INSURANCE_ACCOUNT_NOT_FOUND
                    '-4044': BadRequest,  # INVALID_BALANCE_TYPE
                    '-4045': RateLimitExceeded,  # MAX_STOP_ORDER_EXCEEDED
                    '-4046': NoChange,  # NO_NEED_TO_CHANGE_MARGIN_TYPE
                    '-4047': OperationRejected,  # THERE_EXISTS_OPEN_ORDERS
                    '-4048': OperationRejected,  # THERE_EXISTS_QUANTITY
                    '-4049': OperationRejected,  # ADD_ISOLATED_MARGIN_REJECT
                    '-4050': InsufficientFunds,  # CROSS_BALANCE_INSUFFICIENT
                    '-4051': InsufficientFunds,  # ISOLATED_BALANCE_INSUFFICIENT
                    '-4052': NoChange,  # NO_NEED_TO_CHANGE_AUTO_ADD_MARGIN
                    '-4053': OperationRejected,  # AUTO_ADD_CROSSED_MARGIN_REJECT
                    '-4054': OperationRejected,  # ADD_ISOLATED_MARGIN_NO_POSITION_REJECT
                    '-4055': ArgumentsRequired,  # AMOUNT_MUST_BE_POSITIVE
                    '-4056': AuthenticationError,  # INVALID_API_KEY_TYPE
                    '-4057': AuthenticationError,  # INVALID_RSA_PUBLIC_KEY
                    '-4058': InvalidOrder,  # MAX_PRICE_TOO_LARGE
                    '-4059': NoChange,  # NO_NEED_TO_CHANGE_POSITION_SIDE
                    '-4060': InvalidOrder,  # INVALID_POSITION_SIDE
                    '-4061': InvalidOrder,  # POSITION_SIDE_NOT_MATCH
                    '-4062': OperationRejected,  # REDUCE_ONLY_CONFLICT
                    '-4063': BadRequest,  # INVALID_OPTIONS_REQUEST_TYPE
                    '-4064': BadRequest,  # INVALID_OPTIONS_TIME_FRAME
                    '-4065': BadRequest,  # INVALID_OPTIONS_AMOUNT
                    '-4066': BadRequest,  # INVALID_OPTIONS_EVENT_TYPE
                    '-4067': OperationRejected,  # POSITION_SIDE_CHANGE_EXISTS_OPEN_ORDERS
                    '-4068': OperationRejected,  # POSITION_SIDE_CHANGE_EXISTS_QUANTITY
                    '-4069': BadRequest,  # INVALID_OPTIONS_PREMIUM_FEE
                    '-4070': InvalidOrder,  # INVALID_CL_OPTIONS_ID_LEN
                    '-4071': InvalidOrder,  # INVALID_OPTIONS_DIRECTION
                    '-4072': NoChange,  # OPTIONS_PREMIUM_NOT_UPDATE
                    '-4073': BadRequest,  # OPTIONS_PREMIUM_INPUT_LESS_THAN_ZERO
                    '-4074': InvalidOrder,  # OPTIONS_AMOUNT_BIGGER_THAN_UPPER
                    '-4075': OperationRejected,  # OPTIONS_PREMIUM_OUTPUT_ZERO
                    '-4076': OperationRejected,  # OPTIONS_PREMIUM_TOO_DIFF
                    '-4077': RateLimitExceeded,  # OPTIONS_PREMIUM_REACH_LIMIT
                    '-4078': BadRequest,  # OPTIONS_COMMON_ERROR
                    '-4079': BadRequest,  # INVALID_OPTIONS_ID
                    '-4080': BadRequest,  # OPTIONS_USER_NOT_FOUND
                    '-4081': BadRequest,  # OPTIONS_NOT_FOUND
                    '-4082': RateLimitExceeded,  # INVALID_BATCH_PLACE_ORDER_SIZE
                    '-4083': OperationFailed,  # PLACE_BATCH_ORDERS_FAIL
                    '-4084': NotSupported,  # UPCOMING_METHOD
                    '-4085': BadRequest,  # INVALID_NOTIONAL_LIMIT_COEF
                    '-4086': BadRequest,  # INVALID_PRICE_SPREAD_THRESHOLD
                    '-4087': PermissionDenied,  # REDUCE_ONLY_ORDER_PERMISSION
                    '-4088': PermissionDenied,  # NO_PLACE_ORDER_PERMISSION
                    '-4104': BadSymbol,  # INVALID_CONTRACT_TYPE
                    '-4114': InvalidOrder,  # INVALID_CLIENT_TRAN_ID_LEN
                    '-4115': DuplicateOrderId,  # DUPLICATED_CLIENT_TRAN_ID
                    '-4118': InsufficientFunds,  # REDUCE_ONLY_MARGIN_CHECK_FAILED
                    '-4131': InvalidOrder,  # MARKET_ORDER_REJECT
                    '-4135': InvalidOrder,  # INVALID_ACTIVATION_PRICE
                    '-4137': InvalidOrder,  # QUANTITY_EXISTS_WITH_CLOSE_POSITION
                    '-4138': OperationRejected,  # REDUCE_ONLY_MUST_BE_TRUE
                    '-4139': InvalidOrder,  # ORDER_TYPE_CANNOT_BE_MKT
                    '-4140': OperationRejected,  # INVALID_OPENING_POSITION_STATUS
                    '-4141': MarketClosed,  # SYMBOL_ALREADY_CLOSED
                    '-4142': InvalidOrder,  # STRATEGY_INVALID_TRIGGER_PRICE
                    '-4144': BadSymbol,  # INVALID_PAIR
                    '-4161': OperationRejected,  # ISOLATED_LEVERAGE_REJECT_WITH_POSITION
                    '-4164': InvalidOrder,  # MIN_NOTIONAL
                    '-4165': BadRequest,  # INVALID_TIME_INTERVAL
                    '-4183': InvalidOrder,  # PRICE_HIGHTER_THAN_STOP_MULTIPLIER_UP
                    '-4184': InvalidOrder,  # PRICE_LOWER_THAN_STOP_MULTIPLIER_DOWN
                    '-5060': OperationRejected,  # {"code":-5060,"msg":"The limit order price does not meet the PERCENT_PRICE filter limit."}
                    '-5076': OperationRejected,  # {"code":-5076,"msg":"Total order value should be more than 5 USDT"}
                },
                'broad': {
                },
            },
        })

    def is_inverse(self, type: str, subType: Str = None) -> bool:
        if subType is None:
            return(type == 'delivery')
        else:
            return subType == 'inverse'

    def is_linear(self, type: str, subType: Str = None) -> bool:
        if subType is None:
            return(type == 'future') or (type == 'swap')
        else:
            return subType == 'linear'

    def fetch_currencies(self, params={}) -> Currencies:
        """
        fetches all available currencies on an exchange

        https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#trading-specification-information
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#exchange-information

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        """
        promises = [
            self.sapiPublicGetV1ExchangeInfo(params),
            self.fapiPublicGetV1ExchangeInfo(params),
        ]
        results = promises
        sapiResult = self.safe_dict(results, 0, {})
        sapiRows = self.safe_list(sapiResult, 'assets', [])
        fapiResult = self.safe_dict(results, 1, {})
        fapiRows = self.safe_list(fapiResult, 'assets', [])
        rows = self.array_concat(sapiRows, fapiRows)
        #
        #     [
        #         {
        #             "asset": "USDT",
        #             "marginAvailable": True,
        #             "autoAssetExchange": "-10000"
        #         }
        #     ]
        #
        result: dict = {}
        for i in range(0, len(rows)):
            currency = rows[i]
            currencyId = self.safe_string(currency, 'asset')
            code = self.safe_currency_code(currencyId)
            result[code] = self.safe_currency_structure({
                'info': currency,
                'code': code,
                'id': currencyId,
                'name': code,
                'active': None,
                'deposit': None,
                'withdraw': None,
                'fee': None,
                'precision': None,
                'limits': {
                    'amount': {
                        'min': None,
                        'max': None,
                    },
                    'withdraw': {
                        'min': None,
                        'max': None,
                    },
                    'deposit': {
                        'min': None,
                        'max': None,
                    },
                },
                'networks': None,
                'type': 'crypto',  # atm exchange api provides only cryptos
            })
        return result

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

        https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#trading-specification-information
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#exchange-information

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        promises = [
            self.sapiPublicGetV1ExchangeInfo(params),
            self.fapiPublicGetV1ExchangeInfo(params),
        ]
        results = promises
        sapiResult = self.safe_dict(results, 0, {})
        sapiRows = self.safe_list(sapiResult, 'symbols', [])
        fapiResult = self.safe_dict(results, 1, {})
        fapiRows = self.safe_list(fapiResult, 'symbols', [])
        rows = self.array_concat(sapiRows, fapiRows)
        #
        #     [
        #         {
        #             "symbol": "BTCUSDT",
        #             "pair": "BTCUSDT",
        #             "contractType": "PERPETUAL",
        #             "deliveryDate": 4133404800000,
        #             "onboardDate": 1627628400000,
        #             "status": "TRADING",
        #             "maintMarginPercent": "2.5000",
        #             "requiredMarginPercent": "5.0000",
        #             "baseAsset": "BTC",
        #             "quoteAsset": "USDT",
        #             "marginAsset": "USDT",
        #             "pricePrecision": 1,
        #             "quantityPrecision": 3,
        #             "baseAssetPrecision": 8,
        #             "quotePrecision": 8,
        #             "underlyingType": "COIN",
        #             "underlyingSubType": [],
        #             "settlePlan": 0,
        #             "triggerProtect": "0.0200",
        #             "liquidationFee": "0.025000",
        #             "marketTakeBound": "0.02",
        #             "filters": [
        #                 {
        #                     "minPrice": "1",
        #                     "maxPrice": "1000000",
        #                     "filterType": "PRICE_FILTER",
        #                     "tickSize": "0.1"
        #                 },
        #                 {
        #                     "stepSize": "0.001",
        #                     "filterType": "LOT_SIZE",
        #                     "maxQty": "100",
        #                     "minQty": "0.001"
        #                 },
        #                 {
        #                     "stepSize": "0.001",
        #                     "filterType": "MARKET_LOT_SIZE",
        #                     "maxQty": "10",
        #                     "minQty": "0.001"
        #                 },
        #                 {
        #                     "limit": 200,
        #                     "filterType": "MAX_NUM_ORDERS"
        #                 },
        #                 {
        #                     "limit": 10,
        #                     "filterType": "MAX_NUM_ALGO_ORDERS"
        #                 },
        #                 {
        #                     "notional": "5",
        #                     "filterType": "MIN_NOTIONAL"
        #                 },
        #                 {
        #                     "multiplierDown": "0.9800",
        #                     "multiplierUp": "1.0200",
        #                     "multiplierDecimal": "4",
        #                     "filterType": "PERCENT_PRICE"
        #                 }
        #             ],
        #             "orderTypes": [
        #                 "LIMIT",
        #                 "MARKET",
        #                 "STOP",
        #                 "STOP_MARKET",
        #                 "TAKE_PROFIT",
        #                 "TAKE_PROFIT_MARKET",
        #                 "TRAILING_STOP_MARKET"
        #             ],
        #             "timeInForce": [
        #                 "GTC",
        #                 "IOC",
        #                 "FOK",
        #                 "GTX",
        #                 "RPI"
        #             ]
        #         }
        #     ]
        #
        fees = self.fees
        result = []
        for i in range(0, len(rows)):
            swap = False
            market = rows[i]
            id = self.safe_string(market, 'symbol')
            baseId = self.safe_string(market, 'baseAsset')
            quoteId = self.safe_string(market, 'quoteAsset')
            base = self.safe_currency_code(baseId)
            quote = self.safe_currency_code(quoteId)
            contractType = self.safe_string(market, 'contractType')
            contract = contractType is not None
            spot = True
            if contractType == 'PERPETUAL':
                swap = True
                spot = False
            contractSize = None
            linear = None
            inverse = None
            symbol = base + '/' + quote
            settle = None
            settleId = None
            if contract:
                settleId = self.safe_string(market, 'marginAsset')
                settle = self.safe_currency_code(settleId)
                if swap:
                    symbol = symbol + ':' + settle
                linear = settle == quote
                inverse = settle == base
                contractSize = self.safe_number_2(market, 'contractSize', 'unit', self.parse_number('1'))
            unifiedType = None
            if spot:
                unifiedType = 'spot'
            elif swap:
                unifiedType = 'swap'
            status = self.safe_string(market, 'status')
            active = status == 'TRADING'
            filters = self.safe_list(market, 'filters', [])
            filtersByType = self.index_by(filters, 'filterType')
            entry = self.safe_market_structure({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'settle': settle,
                'baseId': baseId,
                'quoteId': quoteId,
                'settleId': settleId,
                'type': unifiedType,
                'spot': spot,
                'margin': False,
                'swap': swap,
                'future': False,
                'option': False,
                'active': active,
                'contract': contract,
                'linear': linear,
                'inverse': inverse,
                'taker': fees['trading']['taker'],
                'maker': fees['trading']['maker'],
                'contractSize': contractSize,
                'expiry': None,
                'expiryDatetime': None,
                'strike': None,
                'optionType': None,
                'precision': {
                    'amount': self.parse_number(self.parse_precision(self.safe_string(market, 'quantityPrecision'))),
                    'price': self.parse_number(self.parse_precision(self.safe_string(market, 'pricePrecision'))),
                    'base': self.parse_number(self.parse_precision(self.safe_string(market, 'baseAssetPrecision'))),
                    'quote': self.parse_number(self.parse_precision(self.safe_string(market, 'quotePrecision'))),
                },
                'limits': {
                    'leverage': {
                        'min': None,
                        'max': None,
                    },
                    'amount': {
                        'min': None,
                        'max': None,
                    },
                    'price': {
                        'min': None,
                        'max': None,
                    },
                    'cost': {
                        'min': None,
                        'max': None,
                    },
                },
                'created': self.safe_integer(market, 'onboardDate'),
                'info': market,
            })
            if 'PRICE_FILTER' in filtersByType:
                filter = self.safe_dict(filtersByType, 'PRICE_FILTER', {})
                entry['limits']['price'] = {
                    'min': self.safe_number(filter, 'minPrice'),
                    'max': self.safe_number(filter, 'maxPrice'),
                }
                entry['precision']['price'] = self.safe_number(filter, 'tickSize')
            if 'LOT_SIZE' in filtersByType:
                filter = self.safe_dict(filtersByType, 'LOT_SIZE', {})
                entry['precision']['amount'] = self.safe_number(filter, 'stepSize')
                entry['limits']['amount'] = {
                    'min': self.safe_number(filter, 'minQty'),
                    'max': self.safe_number(filter, 'maxQty'),
                }
            if 'MARKET_LOT_SIZE' in filtersByType:
                filter = self.safe_dict(filtersByType, 'MARKET_LOT_SIZE', {})
                entry['limits']['market'] = {
                    'min': self.safe_number(filter, 'minQty'),
                    'max': self.safe_number(filter, 'maxQty'),
                }
            if ('MIN_NOTIONAL' in filtersByType) or ('NOTIONAL' in filtersByType):
                filter = self.safe_dict_2(filtersByType, 'MIN_NOTIONAL', 'NOTIONAL', {})
                entry['limits']['cost']['min'] = self.safe_number(filter, 'notional')
            result.append(entry)
        return result

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

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#check-server-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.fapiPublicGetV1Time(params)
        #
        #     {
        #         "serverTime": 1499827319559
        #     }
        #
        return self.safe_integer(response, 'serverTime')

    def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
        #
        #     [
        #         1631158560000,
        #         "208.1850",
        #         "208.1850",
        #         "208.1850",
        #         "208.1850",
        #         "11.84",
        #         1631158619999,
        #         "2464.910400",
        #         1,
        #         "11.84",
        #         "2464.910400",
        #         "0"
        #     ]
        #
        return [
            self.safe_integer(ohlcv, 0),
            self.safe_number(ohlcv, 1),
            self.safe_number(ohlcv, 2),
            self.safe_number(ohlcv, 3),
            self.safe_number(ohlcv, 4),
            self.safe_number(ohlcv, 5),
        ]

    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://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#k-line-data
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#klinecandlestick-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
        :param str [params.price]: "mark" or "index" for mark price and index price candles
        :param int [params.until]: the latest time in ms to fetch orders for
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchOHLCV() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {}
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            if limit > 1500:
                limit = 1500  # Default 500; max 1500.
            request['limit'] = limit
        request, params = self.handle_until_option('endTime', request, params)
        request['interval'] = self.safe_string(self.timeframes, timeframe, timeframe)
        price = self.safe_string(params, 'price')
        isMark = (price == 'mark')
        isIndex = (price == 'index')
        params = self.omit(params, 'price')
        response = None
        if isMark:
            request['symbol'] = market['id']
            response = self.fapiPublicGetV1MarkPriceKlines(self.extend(request, params))
        elif isIndex:
            request['pair'] = market['id']
            response = self.fapiPublicGetV1IndexPriceKlines(self.extend(request, params))
        else:
            request['symbol'] = market['id']
            if market['linear']:
                response = self.fapiPublicGetV1Klines(self.extend(request, params))
            else:
                response = self.sapiPublicGetV1Klines(self.extend(request, params))
        #
        #     [
        #         [
        #             1631158560000,
        #             "208.1850",
        #             "208.1850",
        #             "208.1850",
        #             "208.1850",
        #             "11.84",
        #             1631158619999,
        #             "2464.910400",
        #             1,
        #             "11.84",
        #             "2464.910400",
        #             "0"
        #         ]
        #     ]
        #
        return self.parse_ohlcvs(response, market, timeframe, since, limit)

    def parse_trade(self, trade: dict, market: Market = None) -> Trade:
        #
        # fetchTrades
        #
        #     {
        #         "id": 3913206,
        #         "price": "644.100",
        #         "qty": "0.08",
        #         "quoteQty": "51.528",
        #         "time": 1749784506633,
        #         "isBuyerMaker": True
        #     }
        #
        #     {
        #         "id": 657,
        #         "price": "1.01000000",
        #         "qty": "5.00000000",
        #         "baseQty": "4.95049505",
        #         "time": 1755156533943,
        #         "isBuyerMaker": False
        #     }
        #
        # fetchMyTrades
        #
        #     {
        #         "buyer": False,
        #         "commission": "-0.07819010",
        #         "commissionAsset": "USDT",
        #         "id": 698759,
        #         "maker": False,
        #         "orderId": 25851813,
        #         "price": "7819.01",
        #         "qty": "0.002",
        #         "quoteQty": "15.63802",
        #         "realizedPnl": "-0.91539999",
        #         "side": "SELL",
        #         "positionSide": "SHORT",
        #         "symbol": "BTCUSDT",
        #         "time": 1569514978020
        #     }
        #
        id = self.safe_string(trade, 'id')
        symbol = market['symbol']
        currencyId = self.safe_string(trade, 'commissionAsset')
        currencyCode = self.safe_currency_code(currencyId)
        amountString = self.safe_string(trade, 'qty')
        priceString = self.safe_string(trade, 'price')
        costString = self.safe_string_2(trade, 'quoteQty', 'baseQty')
        timestamp = self.safe_integer(trade, 'time')
        side = self.safe_string_lower(trade, 'side')
        isMaker = self.safe_bool(trade, 'maker')
        takerOrMaker = None
        if isMaker is not None:
            takerOrMaker = 'maker' if isMaker else 'taker'
        isBuyerMaker = self.safe_bool(trade, 'isBuyerMaker')
        if isBuyerMaker is not None:
            side = 'sell' if isBuyerMaker else 'buy'
        return self.safe_trade({
            'id': id,
            'info': trade,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': symbol,
            'order': self.safe_string(trade, 'orderId'),
            'type': None,
            'side': side,
            'takerOrMaker': takerOrMaker,
            'price': priceString,
            'amount': amountString,
            'cost': costString,
            'fee': {
                'cost': self.parse_number(Precise.string_abs(self.safe_string(trade, 'commission'))),
                'currency': currencyCode,
            },
        }, 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://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#recent-trades-list
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#recent-trades-list

        :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>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchTrades() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        if limit is not None:
            if limit > 1000:
                limit = 1000  # Default 500; max 1000.
            request['limit'] = limit
        response = None
        if market['swap']:
            response = self.fapiPublicGetV1Trades(self.extend(request, params))
            #
            #     [
            #         {
            #             "id": 3913206,
            #             "price": "644.100",
            #             "qty": "0.08",
            #             "quoteQty": "51.528",
            #             "time": 1749784506633,
            #             "isBuyerMaker": True
            #         }
            #     ]
            #
        else:
            response = self.sapiPublicGetV1Trades(self.extend(request, params))
            #     [
            #         {
            #             "id": 657,
            #             "price": "1.01000000",
            #             "qty": "5.00000000",
            #             "baseQty": "4.95049505",
            #             "time": 1755156533943,
            #             "isBuyerMaker": False
            #         }
            #     ]
        return self.parse_trades(response, market, since, limit)

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

        https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#account-trade-history-user_data
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#account-trade-list-user_data

        :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
        :param int [params.until]: timestamp in ms for the ending date filter, default is None
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchMyTrades() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            if limit > 1000:
                limit = 1000  # Default 500; max 1000.
            request['limit'] = limit
        request, params = self.handle_until_option('endTime', request, params)
        response = None
        if market['swap']:
            response = self.fapiPrivateGetV1UserTrades(self.extend(request, params))
        else:
            response = self.sapiPrivateGetV1UserTrades(self.extend(request, params))
        #
        #     [
        #         {
        #             "buyer": False,
        #             "commission": "-0.07819010",
        #             "commissionAsset": "USDT",
        #             "id": 698759,
        #             "maker": False,
        #             "orderId": 25851813,
        #             "price": "7819.01",
        #             "qty": "0.002",
        #             "quoteQty": "15.63802",
        #             "realizedPnl": "-0.91539999",
        #             "side": "SELL",
        #             "positionSide": "SHORT",
        #             "symbol": "BTCUSDT",
        #             "time": 1569514978020
        #         }
        #     ]
        #
        return self.parse_trades(response, market, since, limit, params)

    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://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#depth-information
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#order-book

        :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
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchOrderBook() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        if limit is not None:
            # limit: [5, 10, 20, 50, 100, 500, 1000]. Default: 500
            if limit > 1000:
                limit = 1000  # Default 500; max 1000.
            request['limit'] = limit
        response = None
        if market['swap']:
            response = self.fapiPublicGetV1Depth(self.extend(request, params))
        else:
            response = self.sapiPublicGetV1Depth(self.extend(request, params))
        #
        #     {
        #         "lastUpdateId": 1027024,
        #         "E": 1589436922972,  #     Message output time
        #         "T": 1589436922959,  #     Transaction time
        #         "bids": [
        #             [
        #                 "4.00000000",  #     PRICE
        #                 "431.00000000"  #     QTY
        #             ]
        #         ],
        #         "asks": [
        #             [
        #                 "4.00000200",
        #                 "12.00000000"
        #             ]
        #         ]
        #     }
        #
        timestamp = self.safe_integer(response, 'T')
        return self.parse_order_book(response, symbol, timestamp, 'bids', 'asks')

    def fetch_funding_rate_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        fetches historical funding rate prices

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#get-funding-rate-history

        :param str symbol: unified symbol of the market to fetch the funding rate history for
        :param int [since]: timestamp in ms of the earliest funding rate to fetch
        :param int [limit]: the maximum amount of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>` to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest funding rate
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
        """
        self.load_markets()
        request: dict = {}
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            if limit > 1000:
                limit = 1000  # Default 100; max 1000
            request['limit'] = limit
        request, params = self.handle_until_option('endTime', request, params)
        response = self.fapiPublicGetV1FundingRate(self.extend(request, params))
        #
        #     [
        #         {
        #             "symbol": "BTCUSDT",
        #             "fundingTime": 1747209600000,
        #             "fundingRate": "0.00010000"
        #         }
        #     ]
        #
        rates = []
        for i in range(0, len(response)):
            entry = response[i]
            timestamp = self.safe_integer(entry, 'fundingTime')
            rates.append({
                'info': entry,
                'symbol': self.safe_symbol(self.safe_string(entry, 'symbol'), None, None, 'swap'),
                'fundingRate': self.safe_number(entry, 'fundingRate'),
                'timestamp': timestamp,
                'datetime': self.iso8601(timestamp),
            })
        sorted = self.sort_by(rates, 'timestamp')
        return self.filter_by_symbol_since_limit(sorted, symbol, since, limit)

    def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
        #
        # spot
        #     {
        #         "symbol": "BTCUSDT",
        #         "priceChange": "-2274.38",
        #         "priceChangePercent": "-2.049",
        #         "weightedAvgPrice": "109524.37084136",
        #         "lastPrice": "108738.78",
        #         "lastQty": "0.00034",
        #         "openPrice": "111013.16",
        #         "highPrice": "111975.81",
        #         "lowPrice": "107459.25",
        #         "volume": "28.67876",
        #         "quoteVolume": "3141023.14551030",
        #         "openTime": "1760578800000",
        #         "closeTime": "1760665024749",
        #         "firstId": "37447",
        #         "lastId": "39698",
        #         "count": "2252",
        #         "baseAsset": "BTC",
        #         "quoteAsset": "USDT",
        #         "bidPrice": "108705.11",
        #         "bidQty": "0.03351",
        #         "askPrice": "108725.99",
        #         "askQty": "0.08724"
        #     }
        # swap
        #     {
        #         "symbol": "BTCUSDT",
        #         "priceChange": "1845.7",
        #         "priceChangePercent": "1.755",
        #         "weightedAvgPrice": "105515.5",
        #         "lastPrice": "107037.7",
        #         "lastQty": "0.004",
        #         "openPrice": "105192.0",
        #         "highPrice": "107223.5",
        #         "lowPrice": "104431.6",
        #         "volume": "8753.286",
        #         "quoteVolume": "923607368.61",
        #         "openTime": 1749976620000,
        #         "closeTime": 1750063053754,
        #         "firstId": 24195078,
        #         "lastId": 24375783,
        #         "count": 180706
        #     }
        #
        timestamp = self.safe_integer(ticker, 'closeTime')
        marketType = None
        if 'bidQty' in ticker:
            marketType = 'spot'
        else:
            marketType = 'contract'
        marketId = self.safe_string(ticker, 'symbol')
        market = self.safe_market(marketId, market, None, marketType)
        symbol = market['symbol']
        last = self.safe_string(ticker, 'lastPrice')
        open = self.safe_string(ticker, 'openPrice')
        percentage = self.safe_string(ticker, 'priceChangePercent')
        percentage = Precise.string_mul(percentage, '100')
        quoteVolume = self.safe_string(ticker, 'quoteVolume')
        baseVolume = self.safe_string(ticker, 'volume')
        high = self.safe_string(ticker, 'highPrice')
        low = self.safe_string(ticker, 'lowPrice')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': high,
            'low': low,
            'bid': self.safe_string(ticker, 'bidPrice'),
            'bidVolume': self.safe_string(ticker, 'bidQty'),
            'ask': self.safe_string(ticker, 'askPrice'),
            'askVolume': self.safe_string(ticker, 'askQty'),
            'vwap': None,
            'open': open,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': None,
            'percentage': percentage,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'markPrice': None,
            'indexPrice': None,
            '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://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#24h-price-change
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#24hr-ticker-price-change-statistics

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchTicker() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = None
        if market['swap']:
            response = self.fapiPublicGetV1Ticker24hr(self.extend(request, params))
            #
            #     {
            #         "symbol": "BTCUSDT",
            #         "priceChange": "1845.7",
            #         "priceChangePercent": "1.755",
            #         "weightedAvgPrice": "105515.5",
            #         "lastPrice": "107037.7",
            #         "lastQty": "0.004",
            #         "openPrice": "105192.0",
            #         "highPrice": "107223.5",
            #         "lowPrice": "104431.6",
            #         "volume": "8753.286",
            #         "quoteVolume": "923607368.61",
            #         "openTime": 1749976620000,
            #         "closeTime": 1750063053754,
            #         "firstId": 24195078,
            #         "lastId": 24375783,
            #         "count": 180706
            #     }
            #
        else:
            response = self.sapiPublicGetV1Ticker24hr(self.extend(request, params))
            #     {
            #         "symbol": "BTCUSDT",
            #         "priceChange": "-2274.38",
            #         "priceChangePercent": "-2.049",
            #         "weightedAvgPrice": "109524.37084136",
            #         "lastPrice": "108738.78",
            #         "lastQty": "0.00034",
            #         "openPrice": "111013.16",
            #         "highPrice": "111975.81",
            #         "lowPrice": "107459.25",
            #         "volume": "28.67876",
            #         "quoteVolume": "3141023.14551030",
            #         "openTime": "1760578800000",
            #         "closeTime": "1760665024749",
            #         "firstId": "37447",
            #         "lastId": "39698",
            #         "count": "2252",
            #         "baseAsset": "BTC",
            #         "quoteAsset": "USDT",
            #         "bidPrice": "108705.11",
            #         "bidQty": "0.03351",
            #         "askPrice": "108725.99",
            #         "askQty": "0.08724"
            #     }
        return self.parse_ticker(response, 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://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#24h-price-change
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#24hr-ticker-price-change-statistics

        :param str[] symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.subType]: "linear" or "inverse"
        :param str [params.type]: 'spot', 'option', use params["subType"] for swap and future markets
        :returns dict: an array of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        self.load_markets()
        symbols = self.market_symbols(symbols, None, True, True, True)
        market = self.get_market_from_symbols(symbols)
        type = None
        type, params = self.handle_market_type_and_params('fetchTickers', market, params)
        subType = None
        subType, params = self.handle_sub_type_and_params('fetchTickers', market, params)
        response = None
        if self.is_linear(type, subType):
            response = self.fapiPublicGetV1Ticker24hr(params)
        elif type == 'spot':
            response = self.sapiPublicGetV1Ticker24hr(params)
        else:
            raise NotSupported(self.id + ' fetchTickers() does not support ' + type + ' markets yet')
        #
        #     [
        #         {
        #             "symbol": "BTCUSDT",
        #             "priceChange": "1845.7",
        #             "priceChangePercent": "1.755",
        #             "weightedAvgPrice": "105515.5",
        #             "lastPrice": "107037.7",
        #             "lastQty": "0.004",
        #             "openPrice": "105192.0",
        #             "highPrice": "107223.5",
        #             "lowPrice": "104431.6",
        #             "volume": "8753.286",
        #             "quoteVolume": "923607368.61",
        #             "openTime": 1749976620000,
        #             "closeTime": 1750063053754,
        #             "firstId": 24195078,
        #             "lastId": 24375783,
        #             "count": 180706
        #         }
        #     ]
        #
        return self.parse_tickers(response, symbols)

    def parse_funding_rate(self, contract, market: Market = None) -> FundingRate:
        #
        #     {
        #         "symbol": "BTCUSDT",
        #         "markPrice": "106729.84047826",
        #         "indexPrice": "106775.72673913",
        #         "estimatedSettlePrice": "106708.84997006",
        #         "lastFundingRate": "0.00010000",
        #         "interestRate": "0.00010000",
        #         "nextFundingTime": 1750147200000,
        #         "time": 1750146970000
        #     }
        #     {
        #         "symbol": "INJUSDT",
        #         "interestRate": "0.00010000",
        #         "time": 1756197479000,
        #         "fundingIntervalHours": 8,
        #         "fundingFeeCap": 0.03,
        #         "fundingFeeFloor": -0.03
        #     }
        #
        marketId = self.safe_string(contract, 'symbol')
        nextFundingTimestamp = self.safe_integer(contract, 'nextFundingTime')
        timestamp = self.safe_integer(contract, 'time')
        interval = self.safe_string(contract, 'fundingIntervalHours')
        intervalString = None
        if interval is not None:
            intervalString = interval + 'h'
        return {
            'info': contract,
            'symbol': self.safe_symbol(marketId, market, None, 'contract'),
            'markPrice': self.safe_number(contract, 'markPrice'),
            'indexPrice': self.safe_number(contract, 'indexPrice'),
            'interestRate': self.safe_number(contract, 'interestRate'),
            'estimatedSettlePrice': self.safe_number(contract, 'estimatedSettlePrice'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'fundingRate': self.safe_number(contract, 'lastFundingRate'),
            'fundingTimestamp': None,
            'fundingDatetime': None,
            'nextFundingRate': None,
            'nextFundingTimestamp': nextFundingTimestamp,
            'nextFundingDatetime': self.iso8601(nextFundingTimestamp),
            'previousFundingRate': None,
            'previousFundingTimestamp': None,
            'previousFundingDatetime': None,
            'interval': intervalString,
        }

    def fetch_funding_rate(self, symbol: str, params={}) -> FundingRate:
        """
        fetch the current funding rate

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#mark-price

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchFundingRate() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = self.fapiPublicGetV1PremiumIndex(self.extend(request, params))
        #
        #     {
        #         "symbol": "BTCUSDT",
        #         "markPrice": "106729.84047826",
        #         "indexPrice": "106775.72673913",
        #         "estimatedSettlePrice": "106708.84997006",
        #         "lastFundingRate": "0.00010000",
        #         "interestRate": "0.00010000",
        #         "nextFundingTime": 1750147200000,
        #         "time": 1750146970000
        #     }
        #
        return self.parse_funding_rate(response, market)

    def fetch_funding_rates(self, symbols: Strings = None, params={}) -> FundingRates:
        """
        fetch the current funding rate for multiple symbols

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#24hr-ticker-price-change-statistics

        :param str[] [symbols]: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        """
        self.load_markets()
        symbols = self.market_symbols(symbols)
        response = self.fapiPublicGetV1PremiumIndex(self.extend(params))
        #
        #     [
        #         {
        #             "symbol": "BTCUSDT",
        #             "markPrice": "106729.84047826",
        #             "indexPrice": "106775.72673913",
        #             "estimatedSettlePrice": "106708.84997006",
        #             "lastFundingRate": "0.00010000",
        #             "interestRate": "0.00010000",
        #             "nextFundingTime": 1750147200000,
        #             "time": 1750146970000
        #         }
        #     ]
        #
        return self.parse_funding_rates(response, symbols)

    def fetch_funding_intervals(self, symbols: Strings = None, params={}) -> FundingRates:
        """
        fetch the funding rate interval for multiple markets

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#get-funding-rate-config

        :param str[] [symbols]: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        """
        self.load_markets()
        if symbols is not None:
            symbols = self.market_symbols(symbols)
        response = self.fapiPublicGetV1FundingInfo(params)
        #
        #     [
        #         {
        #             "symbol": "INJUSDT",
        #             "interestRate": "0.00010000",
        #             "time": 1756197479000,
        #             "fundingIntervalHours": 8,
        #             "fundingFeeCap": 0.03,
        #             "fundingFeeFloor": -0.03
        #         }
        #     ]
        #
        return self.parse_funding_rates(response, symbols)

    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, 'asset')
            code = self.safe_currency_code(currencyId)
            account = self.account()
            account['free'] = self.safe_string_2(balance, 'free', 'maxWithdrawAmount')
            account['used'] = self.safe_string(balance, 'locked')
            account['total'] = self.safe_string(balance, 'walletBalance')
            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://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#account-information-v4-user_data
        https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#account-information-user_data

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.subType]: "linear" or "inverse"
        :param str [params.type]: 'spot', 'option', use params["subType"] for swap and future markets
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        """
        type = None
        type, params = self.handle_market_type_and_params('fetchBalance', None, params)
        subType = None
        subType, params = self.handle_sub_type_and_params('fetchBalance', None, params)
        response = None
        data = None
        if self.is_linear(type, subType):
            response = self.fapiPrivateGetV4Account(params)
            data = self.safe_list(response, 'assets', [])
            #
            #     [
            #         {
            #             "asset": "USDT",  # asset name
            #             "walletBalance": "23.72469206",  # wallet balance
            #             "unrealizedProfit": "0.00000000",  # unrealized profit
            #             "marginBalance": "23.72469206",  # margin balance
            #             "maintMargin": "0.00000000",  # maintenance margin required
            #             "initialMargin": "0.00000000",  # total initial margin required with current mark price
            #             "positionInitialMargin": "0.00000000",  #initial margin required for positions with current mark price
            #             "openOrderInitialMargin": "0.00000000",  # initial margin required for open orders with current mark price
            #             "crossWalletBalance": "23.72469206",  # crossed wallet balance
            #             "crossUnPnl": "0.00000000",  # unrealized profit of crossed positions
            #             "availableBalance": "23.72469206",  # available balance
            #             "maxWithdrawAmount": "23.72469206",  # maximum amount for transfer out
            #             "marginAvailable": True,  # whether the asset can be used in Multi-Assets mode
            #             "updateTime": 1625474304765  # last update time
            #         }
            #     ]
            #
        elif type == 'spot':
            response = self.sapiPrivateGetV1Account(params)
            data = self.safe_list(response, 'balances', [])
            #
            #     [
            #         {
            #             "asset": "BTC",
            #             "free": "4723846.89208129",
            #             "locked": "0.00000000"
            #         }
            #     ]
            #
        else:
            raise NotSupported(self.id + ' fetchBalance() does not support ' + type + ' markets yet')
        return self.parse_balance(data)

    def set_margin_mode(self, marginMode: str, symbol: Str = None, params={}):
        """
        set margin mode to 'cross' or 'isolated'

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#change-margin-type-trade

        :param str marginMode: 'cross' or 'isolated'
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' setMarginMode() requires a symbol argument')
        marginMode = marginMode.upper()
        if marginMode == 'CROSS':
            marginMode = 'CROSSED'
        if (marginMode != 'ISOLATED') and (marginMode != 'CROSSED'):
            raise BadRequest(self.id + ' marginMode must be either isolated or cross')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
            'marginType': marginMode,
        }
        response = self.fapiPrivatePostV1MarginType(self.extend(request, params))
        #
        #     {
        #         "amount": 100.0,
        #         "code": 200,
        #         "msg": "Successfully modify position margin.",
        #         "type": 1
        #     }
        #
        return response

    def fetch_position_mode(self, symbol: Str = None, params={}):
        """
        fetchs the position mode, hedged or one way, hedged for aster is set identically for all linear markets or all inverse markets

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#get-current-position-modeuser_data

        :param str symbol: unified symbol of the market to fetch the order book for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an object detailing whether the market is in hedged or one-way mode
        """
        response = self.fapiPrivateGetV1PositionSideDual(params)
        #
        #     {
        #         "dualSidePosition": True  # "true": Hedge Mode; "false": One-way Mode
        #     }
        #
        dualSidePosition = self.safe_bool(response, 'dualSidePosition')
        return {
            'info': response,
            'hedged': (dualSidePosition is True),
        }

    def set_position_mode(self, hedged: bool, symbol: Str = None, params={}):
        """
        set hedged to True or False for a market

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#change-position-modetrade

        :param bool hedged: set to True to use dualSidePosition
        :param str symbol: not used by bingx setPositionMode()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        """
        request: dict = {
            'dualSidePosition': hedged,
        }
        #
        #     {
        #         "code": 200,
        #         "msg": "success"
        #     }
        #
        return self.fapiPrivatePostV1PositionSideDual(self.extend(request, params))

    def parse_trading_fee(self, fee: dict, market: Market = None) -> TradingFeeInterface:
        marketId = self.safe_string(fee, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = self.safe_symbol(marketId, market)
        return {
            'info': fee,
            'symbol': symbol,
            'maker': self.safe_number(fee, 'makerCommissionRate'),
            'taker': self.safe_number(fee, 'takerCommissionRate'),
            'percentage': False,
            'tierBased': False,
        }

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

        https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#get-symbol-fees
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#user-commission-rate-user_data

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/#/?id=fee-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = None
        if market['swap']:
            response = self.fapiPrivateGetV1CommissionRate(self.extend(request, params))
        else:
            response = self.sapiPrivateGetV1CommissionRate(self.extend(request, params))
        #
        #     {
        #         "symbol": "BTCUSDT",
        #         "makerCommissionRate": "0.0002",
        #         "takerCommissionRate": "0.0004"
        #     }
        #
        return self.parse_trading_fee(response, market)

    def parse_order_status(self, status: Str):
        statuses: dict = {
            'NEW': 'open',
            'PARTIALLY_FILLED': 'open',
            'FILLED': 'closed',
            'CANCELED': 'canceled',
            'REJECTED': 'canceled',
            'EXPIRED': 'canceled',
        }
        return self.safe_string(statuses, status, status)

    def parse_order_type(self, type: Str):
        types: dict = {
            'LIMIT': 'limit',
            'MARKET': 'market',
            'STOP': 'limit',
            'STOP_MARKET': 'market',
            'TAKE_PROFIT': 'limit',
            'TAKE_PROFIT_MARKET': 'market',
            'TRAILING_STOP_MARKET': 'market',
        }
        return self.safe_string(types, type, type)

    def parse_order(self, order: dict, market: Market = None) -> Order:
        #
        # swap
        #     {
        #         "avgPrice": "0.00000",
        #         "clientOrderId": "abc",
        #         "cumQuote": "0",
        #         "executedQty": "0",
        #         "orderId": 1917641,
        #         "origQty": "0.40",
        #         "origType": "TRAILING_STOP_MARKET",
        #         "price": "0",
        #         "reduceOnly": False,
        #         "side": "BUY",
        #         "positionSide": "SHORT",
        #         "status": "NEW",
        #         "stopPrice": "9300",
        #         "closePosition": False,
        #         "symbol": "BTCUSDT",
        #         "time": 1579276756075,
        #         "timeInForce": "GTC",
        #         "type": "TRAILING_STOP_MARKET",
        #         "activatePrice": "9020",
        #         "priceRate": "0.3",
        #         "updateTime": 1579276756075,
        #         "workingType": "CONTRACT_PRICE",
        #         "priceProtect": False
        #     }
        # spot
        #     {
        #         "orderId": 38,
        #         "symbol": "ADA25SLP25",
        #         "status": "FILLED",
        #         "clientOrderId": "afMd4GBQyHkHpGWdiy34Li",
        #         "price": "20",
        #         "avgPrice": "12.0000000000000000",
        #         "origQty": "10",
        #         "executedQty": "10",
        #         "cumQuote": "120",
        #         "timeInForce": "GTC",
        #         "type": "LIMIT",
        #         "side": "BUY",
        #         "stopPrice": "0",
        #         "origType": "LIMIT",
        #         "time": 1649913186270,
        #         "updateTime": 1649913186297
        #     }
        #
        info = order
        marketId = self.safe_string(order, 'symbol')
        market = self.safe_market(marketId, market)
        side = self.safe_string_lower(order, 'side')
        timestamp = self.safe_integer(order, 'time')
        lastTradeTimestamp = self.safe_integer(order, 'updateTime')
        statusId = self.safe_string_upper(order, 'status')
        rawType = self.safe_string_upper(order, 'type')
        stopPriceString = self.safe_string(order, 'stopPrice')
        triggerPrice = self.parse_number(self.omit_zero(stopPriceString))
        return self.safe_order({
            'info': info,
            'id': self.safe_string(order, 'orderId'),
            'clientOrderId': self.safe_string(order, 'clientOrderId'),
            'symbol': self.safe_symbol(marketId, market),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': lastTradeTimestamp,
            'lastUpdateTimestamp': self.safe_integer(order, 'updateTime'),
            'type': self.parse_order_type(rawType),
            'timeInForce': self.safe_string(order, 'timeInForce'),
            'postOnly': None,
            'side': side,
            'price': self.safe_string(order, 'price'),
            'triggerPrice': triggerPrice,
            'average': self.safe_string(order, 'avgPrice'),
            'cost': self.safe_string(order, 'cumQuote'),
            'amount': self.safe_string(order, 'origQty'),
            'filled': self.safe_string(order, 'executedQty'),
            'remaining': None,
            'status': self.parse_order_status(statusId),
            'fee': None,
            'trades': None,
            'reduceOnly': self.safe_bool_2(order, 'reduceOnly', 'ro'),
        }, market)

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

        https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#query-order-user_data
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#query-order-user_data

        :param str id: the order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.clientOrderId]: a unique id for the order
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchOrder() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        clientOrderId = self.safe_string_2(params, 'clientOrderId', 'clientOid')
        params = self.omit(params, ['clientOrderId', 'clientOid'])
        if clientOrderId is not None:
            request['origClientOrderId'] = clientOrderId
        else:
            request['orderId'] = id
        response = None
        if market['swap']:
            response = self.fapiPrivateGetV1Order(self.extend(request, params))
        else:
            response = self.sapiPrivateGetV1Order(self.extend(request, params))
        return self.parse_order(response, market)

    def fetch_open_order(self, id: str, symbol: Str = None, params={}):
        """
        fetch an open order by the id

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#query-current-open-order-user_data

        :param str id: order id
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchOpenOrder() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        clientOrderId = self.safe_string_2(params, 'clientOrderId', 'clientOid')
        params = self.omit(params, ['clientOrderId', 'clientOid'])
        if clientOrderId is not None:
            request['origClientOrderId'] = clientOrderId
        else:
            request['orderId'] = id
        response = self.fapiPrivateGetV1OpenOrder(self.extend(request, params))
        return self.parse_order(response, market)

    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://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#query-all-orders-user_data
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#all-orders-user_data

        :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
        :param int [params.until]: the latest time in ms to fetch orders for
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchOrders() requires a symbol argument')
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            if limit > 1000:
                limit = 1000  # Default 500; max 1000
            request['limit'] = limit
        request, params = self.handle_until_option('endTime', request, params)
        response = None
        if market['swap']:
            response = self.fapiPrivateGetV1AllOrders(self.extend(request, params))
        else:
            response = self.sapiPrivateGetV1AllOrders(self.extend(request, params))
        return self.parse_orders(response, 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://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#current-open-orders-user_data
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#current-all-open-orders-user_data

        :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
        :param str [params.subType]: "linear" or "inverse"
        :param str [params.type]: 'spot', 'option', use params["subType"] for swap and future markets
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        request: dict = {}
        market = None
        type = None
        subType = None
        subType, params = self.handle_sub_type_and_params('fetchOpenOrders', market, params)
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        type, params = self.handle_market_type_and_params('fetchOpenOrders', market, params)
        response = None
        if self.is_linear(type, subType):
            response = self.fapiPrivateGetV1OpenOrders(self.extend(request, params))
        elif type == 'spot':
            response = self.sapiPrivateGetV1OpenOrders(self.extend(request, params))
        else:
            raise NotSupported(self.id + ' fetchOpenOrders() does not support ' + type + ' markets yet')
        #
        #     [
        #         {
        #             "avgPrice": "0.00000",
        #             "clientOrderId": "abc",
        #             "cumQuote": "0",
        #             "executedQty": "0",
        #             "orderId": 1917641,
        #             "origQty": "0.40",
        #             "origType": "TRAILING_STOP_MARKET",
        #             "price": "0",
        #             "reduceOnly": False,
        #             "side": "BUY",
        #             "positionSide": "SHORT",
        #             "status": "NEW",
        #             "stopPrice": "9300",
        #             "closePosition": False,
        #             "symbol": "BTCUSDT",
        #             "time": 1579276756075,
        #             "timeInForce": "GTC",
        #             "type": "TRAILING_STOP_MARKET",
        #             "activatePrice": "9020",
        #             "priceRate": "0.3",
        #             "updateTime": 1579276756075,
        #             "workingType": "CONTRACT_PRICE",
        #             "priceProtect": False
        #         }
        #     ]
        #
        return self.parse_orders(response, market, since, limit)

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

        https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#place-order-trade
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#new-order--trade

        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit' or 'STOP' or 'STOP_MARKET' or 'TAKE_PROFIT' or 'TAKE_PROFIT_MARKET' or 'TRAILING_STOP_MARKET'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of you want to trade in units of the base currency
        :param float [price]: the price that 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 str [params.reduceOnly]: for swap and future reduceOnly is a string 'true' or 'false' that cant be sent with close position set to True or in hedge mode. For spot margin and option reduceOnly is a boolean.
        :param boolean [params.test]: whether to use the test endpoint or not, default is False
        :param float [params.trailingPercent]: the percent to trail away from the current market price
        :param float [params.trailingTriggerPrice]: the price to trigger a trailing order, default uses the price argument
        :param str [params.positionSide]: "BOTH" for one-way mode, "LONG" for buy side of hedged mode, "SHORT" for sell side of hedged mode
        :param float [params.triggerPrice]: the price that a trigger order is triggered at
        :param float [params.stopLossPrice]: the price that a stop loss order is triggered at
        :param float [params.takeProfitPrice]: the price that a take profit order is triggered at
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        test = self.safe_bool(params, 'test', False)
        params = self.omit(params, 'test')
        request = self.create_order_request(symbol, type, side, amount, price, params)
        response = None
        if market['swap']:
            if test:
                response = self.fapiPrivatePostV1OrderTest(request)
            else:
                response = self.fapiPrivatePostV1Order(request)
        else:
            response = self.sapiPrivatePostV1Order(request)
        return self.parse_order(response, market)

    def create_orders(self, orders: List[OrderRequest], params={}):
        """
        create a list of trade orders

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#place-multiple-orders--trade

        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :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()
        ordersRequests = []
        orderSymbols = []
        if len(orders) > 5:
            raise InvalidOrder(self.id + ' createOrders() order list max 5 orders')
        for i in range(0, len(orders)):
            rawOrder = orders[i]
            marketId = self.safe_string(rawOrder, 'symbol')
            type = self.safe_string(rawOrder, 'type')
            side = self.safe_string(rawOrder, 'side')
            amount = self.safe_value(rawOrder, 'amount')
            price = self.safe_value(rawOrder, 'price')
            orderParams = self.safe_dict(rawOrder, 'params', {})
            orderRequest = self.create_order_request(marketId, type, side, amount, price, orderParams)
            ordersRequests.append(orderRequest)
        orderSymbols = self.market_symbols(orderSymbols, None, False, True, True)
        market = self.market(orderSymbols[0])
        if market['spot']:
            raise NotSupported(self.id + ' createOrders() does not support ' + market['type'] + ' orders')
        request: dict = {
            'batchOrders': ordersRequests,
        }
        response = self.fapiPrivatePostV1BatchOrders(self.extend(request, params))
        return self.parse_orders(response)

    def create_order_request(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
        """
 @ignore
        helper function to build the request
        :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 that the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: request to be sent to the exchange
        """
        market = self.market(symbol)
        initialUppercaseType = type.upper()
        isMarketOrder = initialUppercaseType == 'MARKET'
        isLimitOrder = initialUppercaseType == 'LIMIT'
        request: dict = {
            'symbol': market['id'],
            'side': side.upper(),
        }
        clientOrderId = self.safe_string_2(params, 'newClientOrderId', 'clientOrderId')
        if clientOrderId is not None:
            request['newClientOrderId'] = clientOrderId
        triggerPrice = self.safe_string_2(params, 'triggerPrice', 'stopPrice')
        stopLossPrice = self.safe_string(params, 'stopLossPrice', triggerPrice)
        takeProfitPrice = self.safe_string(params, 'takeProfitPrice')
        trailingDelta = self.safe_string(params, 'trailingDelta')
        trailingTriggerPrice = self.safe_string_2(params, 'trailingTriggerPrice', 'activationPrice')
        trailingPercent = self.safe_string_n(params, ['trailingPercent', 'callbackRate', 'trailingDelta'])
        isTrailingPercentOrder = trailingPercent is not None
        isStopLoss = stopLossPrice is not None or trailingDelta is not None
        isTakeProfit = takeProfitPrice is not None
        uppercaseType = initialUppercaseType
        stopPrice = None
        if isTrailingPercentOrder:
            if market['swap']:
                uppercaseType = 'TRAILING_STOP_MARKET'
                request['callbackRate'] = trailingPercent
                if trailingTriggerPrice is not None:
                    request['activationPrice'] = self.price_to_precision(symbol, trailingTriggerPrice)
        elif isStopLoss:
            stopPrice = stopLossPrice
            if isMarketOrder:
                uppercaseType = 'STOP_MARKET'
            elif isLimitOrder:
                uppercaseType = 'STOP'
        elif isTakeProfit:
            stopPrice = takeProfitPrice
            if isMarketOrder:
                uppercaseType = 'TAKE_PROFIT_MARKET'
            elif isLimitOrder:
                uppercaseType = 'TAKE_PROFIT'
        postOnly = self.is_post_only(isMarketOrder, None, params)
        if postOnly:
            request['timeInForce'] = 'GTX'
        #
        # spot
        # LIMIT timeInForce, quantity, price
        # MARKET quantity or quoteOrderQty
        # STOP and TAKE_PROFIT quantity, price, stopPrice
        # STOP_MARKET and TAKE_PROFIT_MARKET quantity, stopPrice
        # future
        # LIMIT timeInForce, quantity, price
        # MARKET quantity
        # STOP/TAKE_PROFIT quantity, price, stopPrice
        # STOP_MARKET/TAKE_PROFIT_MARKET stopPrice
        # TRAILING_STOP_MARKET callbackRate
        #
        # additional required fields depending on the order type
        closePosition = self.safe_bool(params, 'closePosition', False)
        timeInForceIsRequired = False
        priceIsRequired = False
        triggerPriceIsRequired = False
        quantityIsRequired = False
        request['type'] = uppercaseType
        if uppercaseType == 'MARKET':
            if market['spot']:
                quoteOrderQty = self.safe_bool(self.options, 'quoteOrderQty', True)
                if quoteOrderQty:
                    quoteOrderQtyNew = self.safe_string_2(params, 'quoteOrderQty', 'cost')
                    precision = market['precision']['price']
                    if quoteOrderQtyNew is not None:
                        request['quoteOrderQty'] = self.decimal_to_precision(quoteOrderQtyNew, TRUNCATE, precision, self.precisionMode)
                    elif price is not None:
                        amountString = self.number_to_string(amount)
                        priceString = self.number_to_string(price)
                        quoteOrderQuantity = Precise.string_mul(amountString, priceString)
                        request['quoteOrderQty'] = self.decimal_to_precision(quoteOrderQuantity, TRUNCATE, precision, self.precisionMode)
                    else:
                        quantityIsRequired = True
                else:
                    quantityIsRequired = True
            else:
                quantityIsRequired = True
        elif uppercaseType == 'LIMIT':
            timeInForceIsRequired = True
            quantityIsRequired = True
            priceIsRequired = True
        elif (uppercaseType == 'STOP') or (uppercaseType == 'TAKE_PROFIT'):
            quantityIsRequired = True
            priceIsRequired = True
            triggerPriceIsRequired = True
        elif (uppercaseType == 'STOP_MARKET') or (uppercaseType == 'TAKE_PROFIT_MARKET'):
            if not closePosition:
                quantityIsRequired = True
            triggerPriceIsRequired = True
        elif uppercaseType == 'TRAILING_STOP_MARKET':
            request['callbackRate'] = trailingPercent
            if trailingTriggerPrice is not None:
                request['activationPrice'] = self.price_to_precision(symbol, trailingTriggerPrice)
        if quantityIsRequired:
            marketAmountPrecision = self.safe_string(market['precision'], 'amount')
            isPrecisionAvailable = (marketAmountPrecision is not None)
            if isPrecisionAvailable:
                request['quantity'] = self.amount_to_precision(symbol, amount)
            else:
                request['quantity'] = self.parse_to_numeric(amount)
        if priceIsRequired:
            if price is None:
                raise InvalidOrder(self.id + ' createOrder() requires a price argument for a ' + type + ' order')
            pricePrecision = self.safe_string(market['precision'], 'price')
            isPricePrecisionAvailable = (pricePrecision is not None)
            if isPricePrecisionAvailable:
                request['price'] = self.price_to_precision(symbol, price)
            else:
                request['price'] = self.parse_to_numeric(price)
        if triggerPriceIsRequired:
            if stopPrice is None:
                raise InvalidOrder(self.id + ' createOrder() requires a stopPrice extra param for a ' + type + ' order')
            if stopPrice is not None:
                request['stopPrice'] = self.price_to_precision(symbol, stopPrice)
        if timeInForceIsRequired and (self.safe_string(params, 'timeInForce') is None) and (self.safe_string(request, 'timeInForce') is None):
            request['timeInForce'] = self.safe_string(self.options, 'defaultTimeInForce')  # 'GTC' = Good To Cancel(default), 'IOC' = Immediate Or Cancel
        requestParams = self.omit(params, ['newClientOrderId', 'clientOrderId', 'stopPrice', 'triggerPrice', 'trailingTriggerPrice', 'trailingPercent', 'trailingDelta', 'stopPrice', 'stopLossPrice', 'takeProfitPrice'])
        return self.extend(request, requestParams)

    def cancel_all_orders(self, symbol: Str = None, params={}):
        """
        cancel all open orders in a market

        https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#cancel-all-open-orders-trade
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#cancel-all-open-orders-trade

        :param str symbol: unified market symbol of the market to cancel orders in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' cancelAllOrders() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = None
        if market['swap']:
            response = self.fapiPrivateDeleteV1AllOpenOrders(self.extend(request, params))
        else:
            response = self.sapiPrivateDeleteV1AllOpenOrders(self.extend(request, params))
        #
        #     {
        #         "code": "200",
        #         "msg": "The operation of cancel all open order is done."
        #     }
        #
        return [
            self.safe_order({
                'info': response,
            }),
        ]

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

        https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#cancel-order-trade
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#cancel-order-trade

        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        clientOrderId = self.safe_string_n(params, ['origClientOrderId', 'clientOrderId', 'newClientStrategyId'])
        if clientOrderId is not None:
            request['origClientOrderId'] = clientOrderId
        else:
            request['orderId'] = id
        params = self.omit(params, ['origClientOrderId', 'clientOrderId', 'newClientStrategyId'])
        response = None
        if market['swap']:
            response = self.fapiPrivateDeleteV1Order(self.extend(request, params))
        else:
            response = self.sapiPrivateDeleteV1Order(self.extend(request, params))
        return self.parse_order(response, market)

    def cancel_orders(self, ids: List[str], symbol: Str = None, params={}):
        """
        cancel multiple orders

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#cancel-multiple-orders-trade

        :param str[] ids: order ids
        :param str [symbol]: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint

 EXCHANGE SPECIFIC PARAMETERS
        :param str[] [params.origClientOrderIdList]: max length 10 e.g. ["my_id_1","my_id_2"], encode the double quotes. No space after comma
        :param int[] [params.recvWindow]:
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' cancelOrders() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        if market['spot']:
            raise NotSupported(self.id + ' cancelOrders() does not support ' + market['type'] + ' orders')
        request: dict = {
            'symbol': market['id'],
        }
        clientOrderIdList = self.safe_list(params, 'origClientOrderIdList')
        if clientOrderIdList is not None:
            request['origClientOrderIdList'] = clientOrderIdList
        else:
            request['orderIdList'] = ids
        response = self.fapiPrivateDeleteV1BatchOrders(self.extend(request, params))
        #
        #    [
        #        {
        #            "clientOrderId": "myOrder1",
        #            "cumQty": "0",
        #            "cumQuote": "0",
        #            "executedQty": "0",
        #            "orderId": 283194212,
        #            "origQty": "11",
        #            "origType": "TRAILING_STOP_MARKET",
        #            "price": "0",
        #            "reduceOnly": False,
        #            "side": "BUY",
        #            "positionSide": "SHORT",
        #            "status": "CANCELED",
        #            "stopPrice": "9300",                  # please ignore when order type is TRAILING_STOP_MARKET
        #            "closePosition": False,               # if Close-All
        #            "symbol": "BTCUSDT",
        #            "timeInForce": "GTC",
        #            "type": "TRAILING_STOP_MARKET",
        #            "activatePrice": "9020",              # activation price, only return with TRAILING_STOP_MARKET order
        #            "priceRate": "0.3",                   # callback rate, only return with TRAILING_STOP_MARKET order
        #            "updateTime": 1571110484038,
        #            "workingType": "CONTRACT_PRICE",
        #            "priceProtect": False,                # if conditional order trigger is protected
        #        },
        #        {
        #            "code": -2011,
        #            "msg": "Unknown order sent."
        #        }
        #    ]
        #
        return self.parse_orders(response, market)

    def set_leverage(self, leverage: int, symbol: Str = None, params={}):
        """
        set the level of leverage for a market

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#change-initial-leverage-trade

        :param float leverage: the rate of leverage
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' setLeverage() requires a symbol argument')
        if (leverage < 1) or (leverage > 125):
            raise BadRequest(self.id + ' leverage should be between 1 and 125')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
            'leverage': leverage,
        }
        response = self.fapiPrivatePostV1Leverage(self.extend(request, params))
        #
        #     {
        #         "leverage": 21,
        #         "maxNotionalValue": "1000000",
        #         "symbol": "BTCUSDT"
        #     }
        #
        return response

    def fetch_leverages(self, symbols: Strings = None, params={}) -> Leverages:
        """
        fetch the set leverage for all markets

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#position-information-v2-user_data

        :param str[] [symbols]: a list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `leverage structures <https://docs.ccxt.com/#/?id=leverage-structure>`
        """
        self.load_markets()
        response = self.fapiPrivateGetV2PositionRisk(params)
        #
        #     [
        #         {
        #             "symbol": "INJUSDT",
        #             "positionAmt": "0.0",
        #             "entryPrice": "0.0",
        #             "markPrice": "0.00000000",
        #             "unRealizedProfit": "0.00000000",
        #             "liquidationPrice": "0",
        #             "leverage": "20",
        #             "maxNotionalValue": "25000",
        #             "marginType": "cross",
        #             "isolatedMargin": "0.00000000",
        #             "isAutoAddMargin": "false",
        #             "positionSide": "BOTH",
        #             "notional": "0",
        #             "isolatedWallet": "0",
        #             "updateTime": 0
        #         }
        #     ]
        #
        return self.parse_leverages(response, symbols, 'symbol')

    def parse_leverage(self, leverage: dict, market: Market = None) -> Leverage:
        #
        #     {
        #         "symbol": "INJUSDT",
        #         "positionAmt": "0.0",
        #         "entryPrice": "0.0",
        #         "markPrice": "0.00000000",
        #         "unRealizedProfit": "0.00000000",
        #         "liquidationPrice": "0",
        #         "leverage": "20",
        #         "maxNotionalValue": "25000",
        #         "marginType": "cross",
        #         "isolatedMargin": "0.00000000",
        #         "isAutoAddMargin": "false",
        #         "positionSide": "BOTH",
        #         "notional": "0",
        #         "isolatedWallet": "0",
        #         "updateTime": 0
        #     }
        #
        marketId = self.safe_string(leverage, 'symbol')
        marginMode = self.safe_string_lower(leverage, 'marginType')
        side = self.safe_string_lower(leverage, 'positionSide')
        longLeverage = None
        shortLeverage = None
        leverageValue = self.safe_integer(leverage, 'leverage')
        if (side is None) or (side == 'both'):
            longLeverage = leverageValue
            shortLeverage = leverageValue
        elif side == 'long':
            longLeverage = leverageValue
        elif side == 'short':
            shortLeverage = leverageValue
        return {
            'info': leverage,
            'symbol': self.safe_symbol(marketId, market),
            'marginMode': marginMode,
            'longLeverage': longLeverage,
            'shortLeverage': shortLeverage,
        }

    def fetch_margin_modes(self, symbols: Strings = None, params={}) -> MarginModes:
        """
        fetches margin mode of the user

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#position-information-v2-user_data

        :param str[] symbols: unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `margin mode structures <https://docs.ccxt.com/#/?id=margin-mode-structure>`
        """
        self.load_markets()
        response = self.fapiPrivateGetV2PositionRisk(params)
        #
        #
        #     [
        #         {
        #             "symbol": "INJUSDT",
        #             "positionAmt": "0.0",
        #             "entryPrice": "0.0",
        #             "markPrice": "0.00000000",
        #             "unRealizedProfit": "0.00000000",
        #             "liquidationPrice": "0",
        #             "leverage": "20",
        #             "maxNotionalValue": "25000",
        #             "marginType": "cross",
        #             "isolatedMargin": "0.00000000",
        #             "isAutoAddMargin": "false",
        #             "positionSide": "BOTH",
        #             "notional": "0",
        #             "isolatedWallet": "0",
        #             "updateTime": 0
        #         }
        #     ]
        #
        #
        return self.parse_margin_modes(response, symbols, 'symbol', 'swap')

    def parse_margin_mode(self, marginMode: dict, market=None) -> MarginMode:
        #
        #     {
        #         "symbol": "INJUSDT",
        #         "positionAmt": "0.0",
        #         "entryPrice": "0.0",
        #         "markPrice": "0.00000000",
        #         "unRealizedProfit": "0.00000000",
        #         "liquidationPrice": "0",
        #         "leverage": "20",
        #         "maxNotionalValue": "25000",
        #         "marginType": "cross",
        #         "isolatedMargin": "0.00000000",
        #         "isAutoAddMargin": "false",
        #         "positionSide": "BOTH",
        #         "notional": "0",
        #         "isolatedWallet": "0",
        #         "updateTime": 0
        #     }
        #
        marketId = self.safe_string(marginMode, 'symbol')
        market = self.safe_market(marketId, market)
        return {
            'info': marginMode,
            'symbol': market['symbol'],
            'marginMode': self.safe_string_lower(marginMode, 'marginType'),
        }

    def fetch_margin_adjustment_history(self, symbol: Str = None, type: Str = None, since: Num = None, limit: Num = None, params={}) -> List[MarginModification]:
        """
        fetches the history of margin added or reduced from contract isolated positions

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#get-position-margin-change-history-trade

        :param str symbol: unified market symbol
        :param str [type]: "add" or "reduce"
        :param int [since]: timestamp in ms of the earliest change to fetch
        :param int [limit]: the maximum amount of changes to fetch
        :param dict params: extra parameters specific to the exchange api endpoint
        :param int [params.until]: timestamp in ms of the latest change to fetch
        :returns dict[]: a list of `margin structures <https://docs.ccxt.com/#/?id=margin-loan-structure>`
        """
        self.load_markets()
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchMarginAdjustmentHistory() requires a symbol argument')
        market = self.market(symbol)
        until = self.safe_integer(params, 'until')
        params = self.omit(params, 'until')
        request: dict = {
            'symbol': market['id'],
        }
        if type is not None:
            request['type'] = 1 if (type == 'add') else 2
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            request['limit'] = limit
        if until is not None:
            request['endTime'] = until
        response = self.fapiPrivateGetV1PositionMarginHistory(self.extend(request, params))
        #
        #     [
        #         {
        #             "amount": "23.36332311",
        #             "asset": "USDT",
        #             "symbol": "BTCUSDT",
        #             "time": 1578047897183,
        #             "type": 1,
        #             "positionSide": "BOTH"
        #         }
        #     ]
        #
        modifications = self.parse_margin_modifications(response)
        return self.filter_by_symbol_since_limit(modifications, symbol, since, limit)

    def parse_margin_modification(self, data: dict, market: Market = None) -> MarginModification:
        #
        #     {
        #         "amount": "100",
        #         "asset": "USDT",
        #         "symbol": "BTCUSDT",
        #         "time": 1578047900425,
        #         "type": 1,
        #         "positionSide": "LONG"
        #     }
        #
        #     {
        #         "amount": 100.0,
        #         "code": 200,
        #         "msg": "Successfully modify position margin.",
        #         "type": 1
        #     }
        #
        rawType = self.safe_integer(data, 'type')
        errorCode = self.safe_string(data, 'code')
        marketId = self.safe_string(data, 'symbol')
        timestamp = self.safe_integer(data, 'time')
        market = self.safe_market(marketId, market, None, 'swap')
        noErrorCode = errorCode is None
        success = errorCode == '200'
        return {
            'info': data,
            'symbol': market['symbol'],
            'type': 'add' if (rawType == 1) else 'reduce',
            'marginMode': 'isolated',
            'amount': self.safe_number(data, 'amount'),
            'code': self.safe_string(data, 'asset'),
            'total': None,
            'status': 'ok' if (success or noErrorCode) else 'failed',
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
        }

    def modify_margin_helper(self, symbol: str, amount, addOrReduce, params={}):
        self.load_markets()
        market = self.market(symbol)
        amount = self.amount_to_precision(symbol, amount)
        request: dict = {
            'type': addOrReduce,
            'symbol': market['id'],
            'amount': amount,
        }
        code = market['quote']
        response = self.fapiPrivatePostV1PositionMargin(self.extend(request, params))
        #
        #     {
        #         "amount": 100.0,
        #         "code": 200,
        #         "msg": "Successfully modify position margin.",
        #         "type": 1
        #     }
        #
        return self.extend(self.parse_margin_modification(response, market), {
            'code': code,
        })

    def reduce_margin(self, symbol: str, amount: float, params={}) -> MarginModification:
        """
        remove margin from a position

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#modify-isolated-position-margin-trade

        :param str symbol: unified market symbol
        :param float amount: the amount of margin to remove
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=reduce-margin-structure>`
        """
        return self.modify_margin_helper(symbol, amount, 2, params)

    def add_margin(self, symbol: str, amount: float, params={}) -> MarginModification:
        """
        add margin

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#modify-isolated-position-margin-trade

        :param str symbol: unified market symbol
        :param float amount: amount of margin to add
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=add-margin-structure>`
        """
        return self.modify_margin_helper(symbol, amount, 1, params)

    def parse_income(self, income, market: Market = None):
        #
        #     {
        #       "symbol": "ETHUSDT",
        #       "incomeType": "FUNDING_FEE",
        #       "income": "0.00134317",
        #       "asset": "USDT",
        #       "time": "1621584000000",
        #       "info": "FUNDING_FEE",
        #       "tranId": "4480321991774044580",
        #       "tradeId": ""
        #     }
        #
        marketId = self.safe_string(income, 'symbol')
        currencyId = self.safe_string(income, 'asset')
        timestamp = self.safe_integer(income, 'time')
        return {
            'info': income,
            'symbol': self.safe_symbol(marketId, market, None, 'swap'),
            'code': self.safe_currency_code(currencyId),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'id': self.safe_string(income, 'tranId'),
            'amount': self.safe_number(income, 'income'),
        }

    def fetch_funding_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        fetch the history of funding payments paid and received on self account

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#get-income-historyuser_data

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch funding history for
        :param int [limit]: the maximum number of funding history structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest funding history entry
        :param boolean [params.portfolioMargin]: set to True if you would like to fetch the funding history for a portfolio margin account
        :param str [params.subType]: "linear" or "inverse"
        :returns dict: a `funding history structure <https://docs.ccxt.com/#/?id=funding-history-structure>`
        """
        self.load_markets()
        market = None
        request: dict = {
            'incomeType': 'FUNDING_FEE',  # "TRANSFER"，"WELCOME_BONUS", "REALIZED_PNL"，"FUNDING_FEE", "COMMISSION", "INSURANCE_CLEAR", and "MARKET_MERCHANT_RETURN_REWARD"
        }
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        request, params = self.handle_until_option('endTime', request, params)
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            request['limit'] = min(limit, 1000)  # max 1000
        response = self.fapiPrivateGetV1Income(self.extend(request, params))
        return self.parse_incomes(response, market, since, limit)

    def parse_ledger_entry(self, item: dict, currency: Currency = None) -> LedgerEntry:
        #
        #     {
        #         "symbol": "",
        #         "incomeType": "TRANSFER",
        #         "income": "10.00000000",
        #         "asset": "USDT",
        #         "time": 1677645250000,
        #         "info": "TRANSFER",
        #         "tranId": 131001573082,
        #         "tradeId": ""
        #     }
        #
        amount = self.safe_string(item, 'income')
        direction = None
        if Precise.string_le(amount, '0'):
            direction = 'out'
            amount = Precise.string_mul('-1', amount)
        else:
            direction = 'in'
        currencyId = self.safe_string(item, 'asset')
        code = self.safe_currency_code(currencyId, currency)
        currency = self.safe_currency(currencyId, currency)
        timestamp = self.safe_integer(item, 'time')
        type = self.safe_string(item, 'incomeType')
        return self.safe_ledger_entry({
            'info': item,
            'id': self.safe_string(item, 'tranId'),
            'direction': direction,
            'account': None,
            'referenceAccount': None,
            'referenceId': self.safe_string(item, 'tradeId'),
            'type': self.parse_ledger_entry_type(type),
            'currency': code,
            'amount': self.parse_number(amount),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'before': None,
            'after': None,
            'status': None,
            'fee': None,
        }, currency)

    def parse_ledger_entry_type(self, type):
        ledgerType: dict = {
            'TRANSFER': 'transfer',
            'WELCOME_BONUS': 'cashback',
            'REALIZED_PNL': 'trade',
            'FUNDING_FEE': 'fee',
            'COMMISSION': 'commission',
            'INSURANCE_CLEAR': 'settlement',
            'MARKET_MERCHANT_RETURN_REWARD': 'cashback',
        }
        return self.safe_string(ledgerType, type, type)

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

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#get-income-historyuser_data

        :param str [code]: unified currency code
        :param int [since]: timestamp in ms of the earliest ledger entry
        :param int [limit]: max number of ledger entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest ledger entry
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
        """
        self.load_markets()
        currency = None
        if code is not None:
            currency = self.currency(code)
        request: dict = {}
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            request['limit'] = min(limit, 1000)  # max 1000
        until = self.safe_integer(params, 'until')
        if until is not None:
            params = self.omit(params, 'until')
            request['endTime'] = until
        response = self.fapiPrivateGetV1Income(self.extend(request, params))
        #
        #     [
        #         {
        #             "symbol": "",
        #             "incomeType": "TRANSFER",
        #             "income": "10.00000000",
        #             "asset": "USDT",
        #             "time": 1677645250000,
        #             "info": "TRANSFER",
        #             "tranId": 131001573082,
        #             "tradeId": ""
        #         }
        #     ]
        #
        return self.parse_ledger(response, currency, since, limit)

    def parse_position_risk(self, position, market: Market = None):
        #
        #     {
        #         "entryPrice": "6563.66500",
        #         "marginType": "isolated",
        #         "isAutoAddMargin": "false",
        #         "isolatedMargin": "15517.54150468",
        #         "leverage": "10",
        #         "liquidationPrice": "5930.78",
        #         "markPrice": "6679.50671178",
        #         "maxNotionalValue": "20000000",
        #         "positionSide": "LONG",
        #         "positionAmt": "20.000",
        #         "symbol": "BTCUSDT",
        #         "unRealizedProfit": "2316.83423560",
        #         "updateTime": 1625474304765
        #     }
        #
        marketId = self.safe_string(position, 'symbol')
        market = self.safe_market(marketId, market, None, 'contract')
        symbol = self.safe_string(market, 'symbol')
        isolatedMarginString = self.safe_string(position, 'isolatedMargin')
        leverageBrackets = self.safe_dict(self.options, 'leverageBrackets', {})
        leverageBracket = self.safe_list(leverageBrackets, symbol, [])
        notionalString = self.safe_string_2(position, 'notional', 'notionalValue')
        notionalStringAbs = Precise.string_abs(notionalString)
        maintenanceMarginPercentageString = None
        for i in range(0, len(leverageBracket)):
            bracket = leverageBracket[i]
            if Precise.string_lt(notionalStringAbs, bracket[0]):
                break
            maintenanceMarginPercentageString = bracket[1]
        notional = self.parse_number(notionalStringAbs)
        contractsAbs = Precise.string_abs(self.safe_string(position, 'positionAmt'))
        contracts = self.parse_number(contractsAbs)
        unrealizedPnlString = self.safe_string(position, 'unRealizedProfit')
        unrealizedPnl = self.parse_number(unrealizedPnlString)
        liquidationPriceString = self.omit_zero(self.safe_string(position, 'liquidationPrice'))
        liquidationPrice = self.parse_number(liquidationPriceString)
        collateralString = None
        marginMode = self.safe_string(position, 'marginType')
        if marginMode is None and isolatedMarginString is not None:
            marginMode = 'cross' if Precise.string_eq(isolatedMarginString, '0') else 'isolated'
        side = None
        if Precise.string_gt(notionalString, '0'):
            side = 'long'
        elif Precise.string_lt(notionalString, '0'):
            side = 'short'
        entryPriceString = self.safe_string(position, 'entryPrice')
        entryPrice = self.parse_number(entryPriceString)
        contractSize = self.safe_value(market, 'contractSize')
        contractSizeString = self.number_to_string(contractSize)
        # to notionalValue
        linear = ('notional' in position)
        if marginMode == 'cross':
            # calculate collateral
            precision = self.safe_dict(market, 'precision', {})
            basePrecisionValue = self.safe_string(precision, 'base')
            quotePrecisionValue = self.safe_string_2(precision, 'quote', 'price')
            precisionIsUndefined = (basePrecisionValue is None) and (quotePrecisionValue is None)
            if not precisionIsUndefined:
                if linear:
                    # walletBalance = (liquidationPrice * (±1 + mmp) ± entryPrice) * contracts
                    onePlusMaintenanceMarginPercentageString = None
                    entryPriceSignString = entryPriceString
                    if side == 'short':
                        onePlusMaintenanceMarginPercentageString = Precise.string_add('1', maintenanceMarginPercentageString)
                        entryPriceSignString = Precise.string_mul('-1', entryPriceSignString)
                    else:
                        onePlusMaintenanceMarginPercentageString = Precise.string_add('-1', maintenanceMarginPercentageString)
                    inner = Precise.string_mul(liquidationPriceString, onePlusMaintenanceMarginPercentageString)
                    leftSide = Precise.string_add(inner, entryPriceSignString)
                    quotePrecision = self.precision_from_string(self.safe_string_2(precision, 'quote', 'price'))
                    if quotePrecision is not None:
                        collateralString = Precise.string_div(Precise.string_mul(leftSide, contractsAbs), '1', quotePrecision)
                else:
                    # walletBalance = (contracts * contractSize) * (±1/entryPrice - (±1 - mmp) / liquidationPrice)
                    onePlusMaintenanceMarginPercentageString = None
                    entryPriceSignString = entryPriceString
                    if side == 'short':
                        onePlusMaintenanceMarginPercentageString = Precise.string_sub('1', maintenanceMarginPercentageString)
                    else:
                        onePlusMaintenanceMarginPercentageString = Precise.string_sub('-1', maintenanceMarginPercentageString)
                        entryPriceSignString = Precise.string_mul('-1', entryPriceSignString)
                    leftSide = Precise.string_mul(contractsAbs, contractSizeString)
                    rightSide = Precise.string_sub(Precise.string_div('1', entryPriceSignString), Precise.string_div(onePlusMaintenanceMarginPercentageString, liquidationPriceString))
                    basePrecision = self.precision_from_string(self.safe_string(precision, 'base'))
                    if basePrecision is not None:
                        collateralString = Precise.string_div(Precise.string_mul(leftSide, rightSide), '1', basePrecision)
        else:
            collateralString = self.safe_string(position, 'isolatedMargin')
        collateralString = '0' if (collateralString is None) else collateralString
        collateral = self.parse_number(collateralString)
        markPrice = self.parse_number(self.omit_zero(self.safe_string(position, 'markPrice')))
        timestamp = self.safe_integer(position, 'updateTime')
        if timestamp == 0:
            timestamp = None
        maintenanceMarginPercentage = self.parse_number(maintenanceMarginPercentageString)
        maintenanceMarginString = Precise.string_mul(maintenanceMarginPercentageString, notionalStringAbs)
        if maintenanceMarginString is None:
            # for a while, self new value was a backup to the existing calculations, but in future we might prioritize self
            maintenanceMarginString = self.safe_string(position, 'maintMargin')
        maintenanceMargin = self.parse_number(maintenanceMarginString)
        initialMarginString = None
        initialMarginPercentageString = None
        leverageString = self.safe_string(position, 'leverage')
        if leverageString is not None:
            leverage = int(leverageString)
            rational = self.is_round_number(1000 % leverage)
            initialMarginPercentageString = Precise.string_div('1', leverageString, 8)
            if not rational:
                initialMarginPercentageString = Precise.string_add(initialMarginPercentageString, '1e-8')
            unrounded = Precise.string_mul(notionalStringAbs, initialMarginPercentageString)
            initialMarginString = Precise.string_div(unrounded, '1', 8)
        else:
            initialMarginString = self.safe_string(position, 'initialMargin')
            unrounded = Precise.string_mul(initialMarginString, '1')
            initialMarginPercentageString = Precise.string_div(unrounded, notionalStringAbs, 8)
        marginRatio = None
        percentage = None
        if not Precise.string_equals(collateralString, '0'):
            marginRatio = self.parse_number(Precise.string_div(Precise.string_add(Precise.string_div(maintenanceMarginString, collateralString), '5e-5'), '1', 4))
            percentage = self.parse_number(Precise.string_mul(Precise.string_div(unrealizedPnlString, initialMarginString, 4), '100'))
        positionSide = self.safe_string(position, 'positionSide')
        hedged = positionSide != 'BOTH'
        return self.safe_position({
            'info': position,
            'id': None,
            'symbol': symbol,
            'contracts': contracts,
            'contractSize': contractSize,
            'unrealizedPnl': unrealizedPnl,
            'leverage': self.parse_number(leverageString),
            'liquidationPrice': liquidationPrice,
            'collateral': collateral,
            'notional': notional,
            'markPrice': markPrice,
            'entryPrice': entryPrice,
            'timestamp': timestamp,
            'initialMargin': self.parse_number(initialMarginString),
            'initialMarginPercentage': self.parse_number(initialMarginPercentageString),
            'maintenanceMargin': maintenanceMargin,
            'maintenanceMarginPercentage': maintenanceMarginPercentage,
            'marginRatio': marginRatio,
            'datetime': self.iso8601(timestamp),
            'marginMode': marginMode,
            'side': side,
            'hedged': hedged,
            'percentage': percentage,
            'stopLossPrice': None,
            'takeProfitPrice': None,
        })

    def fetch_positions_risk(self, symbols: Strings = None, params={}):
        """
        fetch positions risk

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#position-information-v2-user_data

        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: data on the positions risk
        """
        if symbols is not None:
            if not isinstance(symbols, list):
                raise ArgumentsRequired(self.id + ' fetchPositionsRisk() requires an array argument for symbols')
        self.load_markets()
        self.load_leverage_brackets(False, params)
        request: dict = {}
        response = self.fapiPrivateGetV2PositionRisk(self.extend(request, params))
        #
        #     [
        #         {
        #             "entryPrice": "6563.66500",
        #             "marginType": "isolated",
        #             "isAutoAddMargin": "false",
        #             "isolatedMargin": "15517.54150468",
        #             "leverage": "10",
        #             "liquidationPrice": "5930.78",
        #             "markPrice": "6679.50671178",
        #             "maxNotionalValue": "20000000",
        #             "positionSide": "LONG",
        #             "positionAmt": "20.000",  # negative value for 'SHORT'
        #             "symbol": "BTCUSDT",
        #             "unRealizedProfit": "2316.83423560",
        #             "updateTime": 1625474304765
        #         }
        #     ]
        #
        result = []
        for i in range(0, len(response)):
            rawPosition = response[i]
            entryPriceString = self.safe_string(rawPosition, 'entryPrice')
            if Precise.string_gt(entryPriceString, '0'):
                result.append(self.parse_position_risk(response[i]))
        symbols = self.market_symbols(symbols)
        return self.filter_by_array_positions(result, 'symbol', symbols, False)

    def fetch_positions(self, symbols: Strings = None, params={}) -> List[Position]:
        """
        fetch all open positions

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#position-information-v2-user_data

        :param str[] [symbols]: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.method]: method name to call, "positionRisk", "account" or "option", default is "positionRisk"
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        """
        defaultMethod = None
        defaultMethod, params = self.handle_option_and_params(params, 'fetchPositions', 'method')
        if defaultMethod is None:
            options = self.safe_dict(self.options, 'fetchPositions')
            if options is None:
                defaultMethod = self.safe_string(self.options, 'fetchPositions', 'positionRisk')
            else:
                defaultMethod = 'positionRisk'
        if defaultMethod == 'positionRisk':
            return self.fetch_positions_risk(symbols, params)
        elif defaultMethod == 'account':
            return self.fetch_account_positions(symbols, params)
        else:
            raise NotSupported(self.id + '.options["fetchPositions"]["method"] or params["method"] = "' + defaultMethod + '" is invalid, please choose between "account" and "positionRisk"')

    def parse_account_positions(self, account, filterClosed=False):
        positions = self.safe_list(account, 'positions')
        assets = self.safe_list(account, 'assets', [])
        balances: dict = {}
        for i in range(0, len(assets)):
            entry = assets[i]
            currencyId = self.safe_string(entry, 'asset')
            code = self.safe_currency_code(currencyId)
            crossWalletBalance = self.safe_string(entry, 'crossWalletBalance')
            crossUnPnl = self.safe_string(entry, 'crossUnPnl')
            balances[code] = {
                'crossMargin': Precise.string_add(crossWalletBalance, crossUnPnl),
                'crossWalletBalance': crossWalletBalance,
            }
        result = []
        for i in range(0, len(positions)):
            position = positions[i]
            marketId = self.safe_string(position, 'symbol')
            market = self.safe_market(marketId, None, None, 'contract')
            code = market['quote'] if market['linear'] else market['base']
            maintenanceMargin = self.safe_string(position, 'maintMargin')
            # check for maintenance margin so empty positions are not returned
            isPositionOpen = (maintenanceMargin != '0') and (maintenanceMargin != '0.00000000')
            if not filterClosed or isPositionOpen:
                # sometimes not all the codes are correctly returned...
                if code in balances:
                    parsed = self.parse_account_position(self.extend(position, {
                        'crossMargin': balances[code]['crossMargin'],
                        'crossWalletBalance': balances[code]['crossWalletBalance'],
                    }), market)
                    result.append(parsed)
        return result

    def parse_account_position(self, position, market: Market = None):
        marketId = self.safe_string(position, 'symbol')
        market = self.safe_market(marketId, market, None, 'contract')
        symbol = self.safe_string(market, 'symbol')
        leverageString = self.safe_string(position, 'leverage')
        leverage = int(leverageString) if (leverageString is not None) else None
        initialMarginString = self.safe_string(position, 'initialMargin')
        initialMargin = self.parse_number(initialMarginString)
        initialMarginPercentageString = None
        if leverageString is not None:
            initialMarginPercentageString = Precise.string_div('1', leverageString, 8)
            rational = self.is_round_number(1000 % leverage)
            if not rational:
                initialMarginPercentageString = Precise.string_div(Precise.string_add(initialMarginPercentageString, '1e-8'), '1', 8)
        # to notionalValue
        usdm = ('notional' in position)
        maintenanceMarginString = self.safe_string(position, 'maintMargin')
        maintenanceMargin = self.parse_number(maintenanceMarginString)
        entryPriceString = self.safe_string(position, 'entryPrice')
        entryPrice = self.parse_number(entryPriceString)
        notionalString = self.safe_string_2(position, 'notional', 'notionalValue')
        notionalStringAbs = Precise.string_abs(notionalString)
        notional = self.parse_number(notionalStringAbs)
        contractsString = self.safe_string(position, 'positionAmt')
        contractsStringAbs = Precise.string_abs(contractsString)
        if contractsString is None:
            entryNotional = Precise.string_mul(Precise.string_mul(leverageString, initialMarginString), entryPriceString)
            contractSizeNew = self.safe_string(market, 'contractSize')
            contractsString = Precise.string_div(entryNotional, contractSizeNew)
            contractsStringAbs = Precise.string_div(Precise.string_add(contractsString, '0.5'), '1', 0)
        contracts = self.parse_number(contractsStringAbs)
        leverageBrackets = self.safe_dict(self.options, 'leverageBrackets', {})
        leverageBracket = self.safe_list(leverageBrackets, symbol, [])
        maintenanceMarginPercentageString = None
        for i in range(0, len(leverageBracket)):
            bracket = leverageBracket[i]
            if Precise.string_lt(notionalStringAbs, bracket[0]):
                break
            maintenanceMarginPercentageString = bracket[1]
        maintenanceMarginPercentage = self.parse_number(maintenanceMarginPercentageString)
        unrealizedPnlString = self.safe_string(position, 'unrealizedProfit')
        unrealizedPnl = self.parse_number(unrealizedPnlString)
        timestamp = self.safe_integer(position, 'updateTime')
        if timestamp == 0:
            timestamp = None
        isolated = self.safe_bool(position, 'isolated')
        if isolated is None:
            isolatedMarginRaw = self.safe_string(position, 'isolatedMargin')
            isolated = not Precise.string_eq(isolatedMarginRaw, '0')
        marginMode = None
        collateralString = None
        walletBalance = None
        if isolated:
            marginMode = 'isolated'
            walletBalance = self.safe_string(position, 'isolatedWallet')
            collateralString = Precise.string_add(walletBalance, unrealizedPnlString)
        else:
            marginMode = 'cross'
            walletBalance = self.safe_string(position, 'crossWalletBalance')
            collateralString = self.safe_string(position, 'crossMargin')
        collateral = self.parse_number(collateralString)
        marginRatio = None
        side = None
        percentage = None
        liquidationPriceStringRaw = None
        liquidationPrice = None
        contractSize = self.safe_value(market, 'contractSize')
        contractSizeString = self.number_to_string(contractSize)
        if Precise.string_equals(notionalString, '0'):
            entryPrice = None
        else:
            side = 'short' if Precise.string_lt(notionalString, '0') else 'long'
            marginRatio = self.parse_number(Precise.string_div(Precise.string_add(Precise.string_div(maintenanceMarginString, collateralString), '5e-5'), '1', 4))
            percentage = self.parse_number(Precise.string_mul(Precise.string_div(unrealizedPnlString, initialMarginString, 4), '100'))
            if usdm:
                # calculate liquidation price
                #
                # liquidationPrice = (walletBalance / (contracts * (±1 + mmp))) + (±entryPrice / (±1 + mmp))
                #
                # mmp = maintenanceMarginPercentage
                # where ± is negative for long and positive for short
                # TODO: calculate liquidation price for coinm contracts
                onePlusMaintenanceMarginPercentageString = None
                entryPriceSignString = entryPriceString
                if side == 'short':
                    onePlusMaintenanceMarginPercentageString = Precise.string_add('1', maintenanceMarginPercentageString)
                else:
                    onePlusMaintenanceMarginPercentageString = Precise.string_add('-1', maintenanceMarginPercentageString)
                    entryPriceSignString = Precise.string_mul('-1', entryPriceSignString)
                leftSide = Precise.string_div(walletBalance, Precise.string_mul(contractsStringAbs, onePlusMaintenanceMarginPercentageString))
                rightSide = Precise.string_div(entryPriceSignString, onePlusMaintenanceMarginPercentageString)
                liquidationPriceStringRaw = Precise.string_add(leftSide, rightSide)
            else:
                # calculate liquidation price
                #
                # liquidationPrice = (contracts * contractSize(±1 - mmp)) / (±1/entryPrice * contracts * contractSize - walletBalance)
                #
                onePlusMaintenanceMarginPercentageString = None
                entryPriceSignString = entryPriceString
                if side == 'short':
                    onePlusMaintenanceMarginPercentageString = Precise.string_sub('1', maintenanceMarginPercentageString)
                else:
                    onePlusMaintenanceMarginPercentageString = Precise.string_sub('-1', maintenanceMarginPercentageString)
                    entryPriceSignString = Precise.string_mul('-1', entryPriceSignString)
                size = Precise.string_mul(contractsStringAbs, contractSizeString)
                leftSide = Precise.string_mul(size, onePlusMaintenanceMarginPercentageString)
                rightSide = Precise.string_sub(Precise.string_mul(Precise.string_div('1', entryPriceSignString), size), walletBalance)
                liquidationPriceStringRaw = Precise.string_div(leftSide, rightSide)
            pricePrecision = self.precision_from_string(self.safe_string(market['precision'], 'price'))
            pricePrecisionPlusOne = pricePrecision + 1
            pricePrecisionPlusOneString = str(pricePrecisionPlusOne)
            # round half up
            rounder = Precise('5e-' + pricePrecisionPlusOneString)
            rounderString = str(rounder)
            liquidationPriceRoundedString = Precise.string_add(rounderString, liquidationPriceStringRaw)
            truncatedLiquidationPrice = Precise.string_div(liquidationPriceRoundedString, '1', pricePrecision)
            if truncatedLiquidationPrice[0] == '-':
                # user cannot be liquidated
                # since he has more collateral than the size of the position
                truncatedLiquidationPrice = None
            liquidationPrice = self.parse_number(truncatedLiquidationPrice)
        positionSide = self.safe_string(position, 'positionSide')
        hedged = positionSide != 'BOTH'
        return {
            'info': position,
            'id': None,
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'initialMargin': initialMargin,
            'initialMarginPercentage': self.parse_number(initialMarginPercentageString),
            'maintenanceMargin': maintenanceMargin,
            'maintenanceMarginPercentage': maintenanceMarginPercentage,
            'entryPrice': entryPrice,
            'notional': notional,
            'leverage': self.parse_number(leverageString),
            'unrealizedPnl': unrealizedPnl,
            'contracts': contracts,
            'contractSize': contractSize,
            'marginRatio': marginRatio,
            'liquidationPrice': liquidationPrice,
            'markPrice': None,
            'collateral': collateral,
            'marginMode': marginMode,
            'side': side,
            'hedged': hedged,
            'percentage': percentage,
        }

    def fetch_account_positions(self, symbols: Strings = None, params={}):
        """
 @ignore
        fetch account positions

        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#position-information-v2-user_data

        :param str[] [symbols]: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: data on account positions
        """
        if symbols is not None:
            if not isinstance(symbols, list):
                raise ArgumentsRequired(self.id + ' fetchPositions() requires an array argument for symbols')
        self.load_markets()
        self.load_leverage_brackets(False, params)
        response = self.fapiPrivateGetV4Account(params)
        filterClosed = None
        filterClosed, params = self.handle_option_and_params(params, 'fetchAccountPositions', 'filterClosed', False)
        result = self.parse_account_positions(response, filterClosed)
        symbols = self.market_symbols(symbols)
        return self.filter_by_array_positions(result, 'symbol', symbols, False)

    def load_leverage_brackets(self, reload=False, params={}):
        self.load_markets()
        # by default cache the leverage bracket
        # it contains useful stuff like the maintenance margin and initial margin for positions
        leverageBrackets = self.safe_dict(self.options, 'leverageBrackets')
        if (leverageBrackets is None) or (reload):
            response = self.fapiPrivateGetV1LeverageBracket(params)
            self.options['leverageBrackets'] = self.create_safe_dictionary()
            for i in range(0, len(response)):
                entry = response[i]
                marketId = self.safe_string(entry, 'symbol')
                symbol = self.safe_symbol(marketId, None, None, 'contract')
                brackets = self.safe_list(entry, 'brackets', [])
                result = []
                for j in range(0, len(brackets)):
                    bracket = brackets[j]
                    floorValue = self.safe_string(bracket, 'notionalFloor')
                    maintenanceMarginPercentage = self.safe_string(bracket, 'maintMarginRatio')
                    result.append([floorValue, maintenanceMarginPercentage])
                self.options['leverageBrackets'][symbol] = result
        return self.options['leverageBrackets']

    def keccak_message(self, message):
        return '0x' + self.hash(message, 'keccak', 'hex')

    def sign_message(self, message, privateKey):
        return self.sign_hash(self.keccak_message(message), privateKey[-64:])

    def sign_withdraw_payload(self, withdrawPayload, network) -> str:
        zeroAddress = self.safe_string(self.options, 'zeroAddress')
        chainId = self.safe_integer(withdrawPayload, 'chainId')
        domain: dict = {
            'chainId': chainId,
            'name': 'Aster',
            'verifyingContract': zeroAddress,
            'version': '1',
        }
        messageTypes: dict = {
            'Action': [
                {'name': 'type', 'type': 'string'},
                {'name': 'destination', 'type': 'address'},
                {'name': 'destination Chain', 'type': 'string'},
                {'name': 'token', 'type': 'string'},
                {'name': 'amount', 'type': 'string'},
                {'name': 'fee', 'type': 'string'},
                {'name': 'nonce', 'type': 'uint256'},
                {'name': 'aster chain', 'type': 'string'},
            ],
        }
        withdraw = {
            'type': 'Withdraw',
            'destination': self.safe_string(withdrawPayload, 'receiver'),
            'destination Chain': network,
            'token': self.safe_string(withdrawPayload, 'asset'),
            'amount': self.safe_string(withdrawPayload, 'amount'),
            'fee': self.safe_string(withdrawPayload, 'fee'),
            'nonce': self.safe_integer(withdrawPayload, 'nonce'),
            'aster chain': 'Mainnet',
        }
        msg = self.eth_encode_structured_data(domain, messageTypes, withdraw)
        signature = self.sign_message(msg, self.privateKey)
        return signature

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

        https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#withdraw-user_data

        :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.check_address(address)
        self.load_markets()
        currency = self.currency(code)
        request: dict = {
            'asset': currency['id'],
            'receiver': address,
            'nonce': self.milliseconds() * 1000,
        }
        chainId = self.safe_integer(params, 'chainId')
        # TODO: check how ARBI signature would work
        networks = self.safe_dict(self.options, 'networks', {})
        network = self.safe_string_upper(params, 'network')
        network = self.safe_string(networks, network, network)
        if (chainId is None) and (network is not None):
            chainIds = self.safe_dict(self.options, 'networksToChainId', {})
            chainId = self.safe_integer(chainIds, network)
        if chainId is None:
            raise ArgumentsRequired(self.id + ' withdraw require chainId or network parameter')
        request['chainId'] = chainId
        fee = self.safe_string(params, 'fee')
        if fee is None:
            raise ArgumentsRequired(self.id + ' withdraw require fee parameter')
        request['fee'] = fee
        params = self.omit(params, ['chainId', 'network', 'fee'])
        request['amount'] = self.currency_to_precision(code, amount, network)
        request['userSignature'] = self.sign_withdraw_payload(request, network)
        response = self.sapiPrivatePostV1AsterUserWithdraw(self.extend(request, params))
        return {
            'info': response,
            'id': self.safe_string(response, 'withdrawId'),
            'txid': self.safe_string(response, 'hash'),
            'timestamp': None,
            'datetime': None,
            'network': network,
            'address': address,
            'addressTo': address,
            'addressFrom': None,
            'tag': tag,
            'tagTo': tag,
            'tagFrom': None,
            'type': 'withdrawal',
            'amount': amount,
            'currency': code,
            'status': None,
            'updated': None,
            'internal': None,
            'comment': None,
            'fee': None,
        }

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

        https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api.md#transfer-asset-to-other-address-trade
        https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api.md#transfer-between-futures-and-spot-user_data

        :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)
        request: dict = {
            'asset': currency['id'],
            'amount': self.currency_to_precision(code, amount),
        }
        type = None
        fromId = None
        if fromAccount is not None:
            fromId = self.convert_type_to_account(fromAccount).upper()
        toId = None
        if toAccount is not None:
            toId = self.convert_type_to_account(toAccount).upper()
        if fromId == 'SPOT' and toId == 'FUTURE':
            type = 'SPOT_FUTURE'
        elif fromId == 'FUTURE' and toId == 'SPOT':
            type = 'FUTURE_SPOT'
        response = None
        if type is not None:
            defaultClientTranId = self.number_to_string(self.milliseconds())
            clientTranId = self.safe_string(params, 'clientTranId', defaultClientTranId)
            request['kindType'] = type
            request['clientTranId'] = clientTranId
            response = self.fapiPrivatePostV1AssetWalletTransfer(self.extend(request, params))
        else:
            # transfer asset to other address
            request['toAddress'] = toAccount
            response = self.sapiPrivatePostV1AssetSendToAddress(self.extend(request, params))
        #
        #     {
        #         "tranId":13526853623,
        #         "status": "SUCCESS"
        #     }
        #
        return {
            'info': response,
            'id': self.safe_string(response, 'tranId'),
            'txid': None,
            'timestamp': None,
            'datetime': None,
            'network': None,
            'address': None,
            'addressTo': fromAccount,
            'addressFrom': toAccount,
            'tag': None,
            'tagTo': None,
            'tagFrom': None,
            'type': 'transfer',
            'amount': amount,
            'currency': code,
            'status': None,
            'updated': None,
            'internal': None,
            'comment': None,
            'fee': None,
        }

    def hash_message(self, binaryMessage):
        # binaryMessage = self.encode(message)
        binaryMessageLength = self.binary_length(binaryMessage)
        x19 = self.base16_to_binary('19')
        newline = self.base16_to_binary('0a')
        prefix = self.binary_concat(x19, self.encode('Ethereum Signed Message:'), newline, self.encode(self.number_to_string(binaryMessageLength)))
        return '0x' + self.hash(self.binary_concat(prefix, binaryMessage), 'keccak', 'hex')

    def sign_hash(self, hash, privateKey):
        self.check_required_credentials()
        signature = self.ecdsa(hash[-64:], privateKey[-64:], 'secp256k1', None)
        r = signature['r']
        s = signature['s']
        v = self.int_to_base16(self.sum(27, signature['v']))
        return '0x' + r.rjust(64, '0') + s.rjust(64, '0') + v

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = self.implode_hostname(self.urls['api'][api]) + '/' + path
        if api == 'fapiPublic' or api == 'sapiPublic':
            if params:
                url += '?' + self.rawencode(params)
        elif api == 'fapiPrivate' or api == 'sapiPrivate':
            self.check_required_credentials()
            headers = {
                'X-MBX-APIKEY': self.apiKey,
            }
            timestamp = self.milliseconds()
            # Nonce is in microseconds
            nonce = self.microseconds()
            defaultRecvWindow = self.safe_integer(self.options, 'recvWindow')
            extendedParams = self.extend({
                'timestamp': timestamp,
            }, params)
            if defaultRecvWindow is not None:
                extendedParams['recvWindow'] = defaultRecvWindow
            recvWindow = self.safe_integer(params, 'recvWindow')
            if recvWindow is not None:
                extendedParams['recvWindow'] = recvWindow
            query = None
            if (method == 'DELETE') and (path == 'v1/batchOrders'):
                orderidlist = self.safe_list(extendedParams, 'orderIdList', [])
                origclientorderidlist = self.safe_list(extendedParams, 'origClientOrderIdList', [])
                extendedParams = self.omit(extendedParams, ['orderIdList', 'origClientOrderIdList'])
                query = self.rawencode(extendedParams)
                orderidlistLength = len(orderidlist)
                origclientorderidlistLength = len(origclientorderidlist)
                if orderidlistLength > 0:
                    query = query + '&' + 'orderidlist=%5B' + '%2C'.join(orderidlist) + '%5D'
                if origclientorderidlistLength > 0:
                    query = query + '&' + 'origclientorderidlist=%5B' + '%2C'.join(origclientorderidlist) + '%5D'
            else:
                query = self.rawencode(extendedParams)
            signature = ''
            if path.find('v3') >= 0:
                signerAddress = self.options['signerAddress']
                if signerAddress is None:
                    raise ArgumentsRequired(self.id + ' requires signerAddress in options when use v3 api')
                # the keys order matter
                keys = list(extendedParams.keys())
                sortedKeys = self.sort(keys)
                signingPayload = {}
                for i in range(0, len(sortedKeys)):
                    key = sortedKeys[i]
                    signingPayload[key] = str(extendedParams[key])
                signingHash = self.hash_message(self.hash(self.eth_abi_encode([
                    'string', 'address', 'address', 'uint256',
                ], [self.json(signingPayload), self.walletAddress, signerAddress, nonce]), 'keccak', 'binary'))
                signature = self.sign_hash(signingHash, self.privateKey)
                extendedParams['user'] = self.walletAddress
                extendedParams['signer'] = signerAddress
                extendedParams['nonce'] = nonce
                query = self.rawencode(extendedParams)
            else:
                signature = self.hmac(self.encode(query), self.encode(self.secret), hashlib.sha256)
            query += '&' + 'signature=' + signature
            if method == 'GET':
                url += '?' + query
            else:
                body = query
                headers['Content-Type'] = 'application/x-www-form-urlencoded'
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, httpCode: int, reason: str, url: str, method: str, headers: dict, body: str, response, requestHeaders, requestBody):
        if response is None:
            return None  # fallback to default error handler
        #
        #    {
        #        "code": -1121,
        #        "msg": "Invalid symbol.",
        #    }
        #
        code = self.safe_string(response, 'code')
        message = self.safe_string(response, 'msg')
        if code is not None and code != '200':
            feedback = self.id + ' ' + body
            self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
            self.throw_exactly_matched_exception(self.exceptions['exact'], code, feedback)
            self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback)
            raise ExchangeError(feedback)  # unknown message
        return None
