# -*- 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.astros import ImplicitAPI
import hashlib
from ccxt.base.types import Any, Balances, Int, MarginModification, Market, Num, Order, OrderBook, OrderRequest, OrderSide, OrderType, Position, Str, Strings, Ticker, Tickers, FundingRate, Trade
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 AccountSuspended
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidAddress
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import DDoSProtection
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import OnMaintenance
from ccxt.base.errors import InvalidNonce
from ccxt.base.errors import RequestTimeout
from ccxt.base.errors import CancelPending
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class astros(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(astros, self).describe(), {
            'id': 'astros',
            'name': 'Astros',
            'countries': ['SG'],
            'version': 'v1',
            'rateLimit': 75,
            'certified': True,
            'pro': True,
            'userAgent': self.userAgents['chrome'],
            'has': {
                'CORS': None,
                'spot': False,
                'margin': False,
                'swap': True,
                'future': False,
                'option': False,
                'addMargin': True,
                'borrowCrossMargin': False,
                'borrowIsolatedMargin': False,
                'cancelAllOrders': True,
                'cancelOrder': True,
                'cancelOrders': True,
                'closeAllPositions': False,
                'closePosition': False,
                'createConvertTrade': False,
                'createDepositAddress': False,
                'createMarketBuyOrderWithCost': False,
                'createMarketOrderWithCost': False,
                'createMarketSellOrderWithCost': False,
                'createOrder': True,
                'createOrders': True,
                'createOrderWithTakeProfitAndStopLoss': False,
                'createPostOnlyOrder': True,
                'createReduceOnlyOrder': False,
                'createStopLimitOrder': False,
                'createStopLossOrder': False,
                'createStopMarketOrder': False,
                'createStopOrder': False,
                'createTakeProfitOrder': False,
                'createTrailingAmountOrder': False,
                'createTrailingPercentOrder': False,
                'createTriggerOrder': False,
                'editOrder': False,
                'fetchAccounts': False,
                'fetchBalance': True,
                'fetchBorrowInterest': False,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchCanceledAndClosedOrders': False,
                'fetchCanceledOrders': False,
                'fetchClosedOrders': False,
                'fetchConvertCurrencies': True,
                'fetchConvertQuote': True,
                'fetchConvertTrade': False,
                'fetchConvertTradeHistory': True,
                'fetchCrossBorrowRate': False,
                'fetchCrossBorrowRates': False,
                'fetchCurrencies': False,
                'fetchDeposit': False,
                'fetchDepositAddress': False,
                'fetchDepositAddresses': False,
                'fetchDepositAddressesByNetwork': False,
                'fetchDeposits': False,
                'fetchDepositsWithdrawals': False,
                'fetchDepositWithdrawFee': 'emulated',
                'fetchDepositWithdrawFees': False,
                'fetchFundingHistory': False,
                'fetchFundingInterval': False,
                'fetchFundingIntervals': False,
                'fetchFundingRate': True,
                'fetchFundingRateHistory': True,
                'fetchFundingRates': False,
                'fetchIndexOHLCV': False,
                'fetchIsolatedBorrowRate': False,
                'fetchIsolatedBorrowRates': False,
                'fetchLedger': False,
                'fetchLeverage': False,
                'fetchLeverageTiers': False,
                'fetchLiquidations': False,
                'fetchLongShortRatio': False,
                'fetchLongShortRatioHistory': False,
                'fetchMarginAdjustmentHistory': False,
                'fetchMarginMode': False,
                'fetchMarketLeverageTiers': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': True,
                'fetchMarkPrice': True,
                'fetchMyLiquidations': False,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenInterest': False,
                'fetchOpenInterestHistory': False,
                'fetchOpenOrders': True,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrderBooks': False,
                'fetchOrders': False,
                'fetchOrderTrades': False,
                'fetchPosition': True,
                'fetchPositionHistory': 'emulated',
                'fetchPositionMode': False,
                'fetchPositions': True,
                'fetchPositionsHistory': False,
                'fetchPositionsRisk': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchStatus': False,
                'fetchTicker': False,
                'fetchTickers': False,
                'fetchTime': True,
                'fetchTrades': True,
                'fetchTradingFee': False,
                'fetchTradingFees': False,
                'fetchTransactions': False,
                'fetchTransfer': False,
                'fetchTransfers': False,
                'fetchWithdrawAddresses': False,
                'fetchWithdrawal': False,
                'fetchWithdrawals': False,
                'reduceMargin': True,
                'repayCrossMargin': False,
                'repayIsolatedMargin': False,
                'setLeverage': False,
                'setMargin': False,
                'setMarginMode': False,
                'setPositionMode': False,
                'signIn': False,
                'transfer': False,
                'withdraw': None,
            },
            'timeframes': {
                '1m': '1MIN',
                '5m': '5MIN',
                '15m': '15MIN',
                '30m': '30MIN',
                '1h': '1HOUR',
                '2h': '2HOUR',
                '4h': '4HOUR',
                '8h': '8HOUR',
                '12h': '12HOUR',
                '1d': '1DAY',
                '1w': '1WEEK',
                '1M': '1MONTH',
            },
            'urls': {
                'logo': 'https://dex-aggregator-front-git-perp-navi-fd9a1df6.vercel.app/_next/image?url=%2Fassets%2Fbeta-logo.png&w=384&q=75',
                'www': 'https://dex-aggregator-front-git-perp-navi-fd9a1df6.vercel.app/',
                'doc': [
                    'https://www.astros.com/api-doc/common/intro',
                    'https://www.astros.com/api-doc/spot/intro',
                ],
                'api': {
                    'public': 'https://dasprkkzjjkl7.cloudfront.net/api/third',
                    'private': 'https://dasprkkzjjkl7.cloudfront.net/api/third',
                },
                'referral': 'https://dex-aggregator-front-git-perp-navi-fd9a1df6.vercel.app/perp?referralCode=WK4OQL',
            },
            'api': {
                'public': {
                    'get': {
                        'info/ping': 1,
                        'info/time': 1,
                        'info/markPrice': 1,
                        'info/trades': 1,
                        'info/pairs': 1,
                        'info/depth': 1,
                        'info/kline': 1,
                        'v1/market/funding/history': 1,
                        'v1/market/funding/current': 1,
                    },
                },
                'private': {
                    'get': {
                        'v1/trade/fillHistory': 1,
                    },
                    'post': {
                        'hot/order/balance': 1,
                        'order/selectContractCurrentEntrustList': 1,
                        'order/selectContractMatchPairList': 1,
                        'order/queryOrder': 1,
                        'hot/order/selectContractPositionList': 1,
                        'hot/order/create': 1,
                        'hot/order/batchCreate': 1,
                        'order/cancelEntrust': 1,
                        'order/cancelEntrustByCli': 1,
                        'order/batchCancelEntrust': 1,
                        'order/cancelAll': 1,
                        'order/callMarginAmount': 1,
                        'hot/order/closeOrder': 1,
                    },
                },
            },
            'fees': {
                'swap': {
                    'taker': self.parse_number('0.006'),
                    'maker': self.parse_number('0.004'),
                },
            },
            'requiredCredentials': {
                'apiKey': True,
                'secret': True,
                'password': False,
            },
            'exceptions': {
                # http error codes
                # 400 Bad Request — Invalid request format
                # 401 Unauthorized — Invalid API Key
                # 403 Forbidden — You do not have access to the requested resource
                # 404 Not Found
                # 500 Internal Server Error — We had a problem with our server
                'exact': {
                    '1': ExchangeError,  # {"code": 1, "message": "System error"}
                    # undocumented
                    'failure to get a peer from the ring-balancer': ExchangeNotAvailable,  # {"message": "failure to get a peer from the ring-balancer"}
                    '4010': PermissionDenied,  # {"code": 4010, "message": "For the security of your funds, withdrawals are not permitted within 24 hours after changing fund password  / mobile number / Google Authenticator settings "}
                    # common
                    # '0': ExchangeError,  # 200 successful,when the order placement / cancellation / operation is successful
                    '4001': ExchangeError,  # no data received in 30s
                    '4002': ExchangeError,  # Buffer full. cannot write data
                    # --------------------------------------------------------
                    '30001': AuthenticationError,  # {"code": 30001, "message": 'request header "OK_ACCESS_KEY" cannot be blank'}
                    '30002': AuthenticationError,  # {"code": 30002, "message": 'request header "OK_ACCESS_SIGN" cannot be blank'}
                    '30003': AuthenticationError,  # {"code": 30003, "message": 'request header "OK_ACCESS_TIMESTAMP" cannot be blank'}
                    '30004': AuthenticationError,  # {"code": 30004, "message": 'request header "OK_ACCESS_PASSPHRASE" cannot be blank'}
                    '30005': InvalidNonce,  # {"code": 30005, "message": "invalid OK_ACCESS_TIMESTAMP"}
                    '30006': AuthenticationError,  # {"code": 30006, "message": "invalid OK_ACCESS_KEY"}
                    '30007': BadRequest,  # {"code": 30007, "message": 'invalid Content_Type, please use "application/json" format'}
                    '30008': RequestTimeout,  # {"code": 30008, "message": "timestamp request expired"}
                    '30009': ExchangeError,  # {"code": 30009, "message": "system error"}
                    '30010': AuthenticationError,  # {"code": 30010, "message": "API validation failed"}
                    '30011': PermissionDenied,  # {"code": 30011, "message": "invalid IP"}
                    '30012': AuthenticationError,  # {"code": 30012, "message": "invalid authorization"}
                    '30013': AuthenticationError,  # {"code": 30013, "message": "invalid sign"}
                    '30014': DDoSProtection,  # {"code": 30014, "message": "request too frequent"}
                    '30015': AuthenticationError,  # {"code": 30015, "message": 'request header "OK_ACCESS_PASSPHRASE" incorrect'}
                    '30016': ExchangeError,  # {"code": 30015, "message": "you are using v1 apiKey, please use v1 endpoint. If you would like to use v3 endpoint, please subscribe to v3 apiKey"}
                    '30017': ExchangeError,  # {"code": 30017, "message": "apikey's broker id does not match"}
                    '30018': ExchangeError,  # {"code": 30018, "message": "apikey's domain does not match"}
                    '30019': ExchangeNotAvailable,  # {"code": 30019, "message": "Api is offline or unavailable"}
                    '30020': BadRequest,  # {"code": 30020, "message": "body cannot be blank"}
                    '30021': BadRequest,  # {"code": 30021, "message": "Json data format error"}, {"code": 30021, "message": "json data format error"}
                    '30022': PermissionDenied,  # {"code": 30022, "message": "Api has been frozen"}
                    '30023': BadRequest,  # {"code": 30023, "message": "{0} parameter cannot be blank"}
                    '30024': BadSymbol,  # {"code":30024,"message":"\"instrument_id\" is an invalid parameter"}
                    '30025': BadRequest,  # {"code": 30025, "message": "{0} parameter category error"}
                    '30026': DDoSProtection,  # {"code": 30026, "message": "requested too frequent"}
                    '30027': AuthenticationError,  # {"code": 30027, "message": "login failure"}
                    '30028': PermissionDenied,  # {"code": 30028, "message": "unauthorized execution"}
                    '30029': AccountSuspended,  # {"code": 30029, "message": "account suspended"}
                    '30030': ExchangeError,  # {"code": 30030, "message": "endpoint request failed. Please try again"}
                    '30031': BadRequest,  # {"code": 30031, "message": "token does not exist"}
                    '30032': BadSymbol,  # {"code": 30032, "message": "pair does not exist"}
                    '30033': BadRequest,  # {"code": 30033, "message": "exchange domain does not exist"}
                    '30034': ExchangeError,  # {"code": 30034, "message": "exchange ID does not exist"}
                    '30035': ExchangeError,  # {"code": 30035, "message": "trading is not hasattr(self, supported) website"}
                    '30036': ExchangeError,  # {"code": 30036, "message": "no relevant data"}
                    '30037': ExchangeNotAvailable,  # {"code": 30037, "message": "endpoint is offline or unavailable"}
                    # '30038': AuthenticationError,  # {"code": 30038, "message": "user does not exist"}
                    '30038': OnMaintenance,  # {"client_oid":"","code":"30038","error_code":"30038","error_message":"Matching engine is being upgraded. Please try in about 1 minute.","message":"Matching engine is being upgraded. Please try in about 1 minute.","order_id":"-1","result":false}
                    # futures
                    '32001': AccountSuspended,  # {"code": 32001, "message": "futures account suspended"}
                    '32002': PermissionDenied,  # {"code": 32002, "message": "futures account does not exist"}
                    '32003': CancelPending,  # {"code": 32003, "message": "canceling, please wait"}
                    '32004': ExchangeError,  # {"code": 32004, "message": "you have no unfilled orders"}
                    '32005': InvalidOrder,  # {"code": 32005, "message": "max order quantity"}
                    '32006': InvalidOrder,  # {"code": 32006, "message": "the order price or trigger price exceeds USD 1 million"}
                    '32007': InvalidOrder,  # {"code": 32007, "message": "leverage level must be the same for orders on the same side of the contract"}
                    '32008': InvalidOrder,  # {"code": 32008, "message": "Max. positions to open(cross margin)"}
                    '32009': InvalidOrder,  # {"code": 32009, "message": "Max. positions to open(fixed margin)"}
                    '32010': ExchangeError,  # {"code": 32010, "message": "leverage cannot be changed with open positions"}
                    '32011': ExchangeError,  # {"code": 32011, "message": "futures status error"}
                    '32012': ExchangeError,  # {"code": 32012, "message": "futures order update error"}
                    '32013': ExchangeError,  # {"code": 32013, "message": "token type is blank"}
                    '32014': ExchangeError,  # {"code": 32014, "message": "your number of contracts closing is larger than the number of contracts available"}
                    '32015': ExchangeError,  # {"code": 32015, "message": "margin ratio is lower than 100% before opening positions"}
                    '32016': ExchangeError,  # {"code": 32016, "message": "margin ratio is lower than 100% after opening position"}
                    '32017': ExchangeError,  # {"code": 32017, "message": "no BBO"}
                    '32018': ExchangeError,  # {"code": 32018, "message": "the order quantity is less than 1, please try again"}
                    '32019': ExchangeError,  # {"code": 32019, "message": "the order price deviates from the price of the previous minute by more than 3%"}
                    '32020': ExchangeError,  # {"code": 32020, "message": "the price is not in the range of the price limit"}
                    '32021': ExchangeError,  # {"code": 32021, "message": "leverage error"}
                    '32022': ExchangeError,  # {"code": 32022, "message": "self function is not supported in your country or region according to the regulations"}
                    '32023': ExchangeError,  # {"code": 32023, "message": "self account has outstanding loan"}
                    '32024': ExchangeError,  # {"code": 32024, "message": "order cannot be placed during delivery"}
                    '32025': ExchangeError,  # {"code": 32025, "message": "order cannot be placed during settlement"}
                    '32026': ExchangeError,  # {"code": 32026, "message": "your account is restricted from opening positions"}
                    '32027': ExchangeError,  # {"code": 32027, "message": "cancelled over 20 orders"}
                    '32028': AccountSuspended,  # {"code": 32028, "message": "account is suspended and liquidated"}
                    '32029': ExchangeError,  # {"code": 32029, "message": "order info does not exist"}
                    '32030': InvalidOrder,  # The order cannot be cancelled
                    '32031': ArgumentsRequired,  # client_oid or order_id is required.
                    '32038': AuthenticationError,  # User does not exist
                    '32040': ExchangeError,  # User have open contract orders or position
                    '32044': ExchangeError,  # {"code": 32044, "message": "The margin ratio after submitting self order is lower than the minimum requirement({0}) for your tier."}
                    '32045': ExchangeError,  # str of commission over 1 million
                    '32046': ExchangeError,  # Each user can hold up to 10 trade plans at the same time
                    '32047': ExchangeError,  # system error
                    '32048': InvalidOrder,  # Order strategy track range error
                    '32049': ExchangeError,  # Each user can hold up to 10 track plans at the same time
                    '32050': InvalidOrder,  # Order strategy rang error
                    '32051': InvalidOrder,  # Order strategy ice depth error
                    '32052': ExchangeError,  # str of commission over 100 thousand
                    '32053': ExchangeError,  # Each user can hold up to 6 ice plans at the same time
                    '32057': ExchangeError,  # The order price is zero. Market-close-all function cannot be executed
                    '32054': ExchangeError,  # Trade not allow
                    '32055': InvalidOrder,  # cancel order error
                    '32056': ExchangeError,  # iceberg per order average should between {0}-{1} contracts
                    '32058': ExchangeError,  # Each user can hold up to 6 initiative plans at the same time
                    '32059': InvalidOrder,  # Total amount should exceed per order amount
                    '32060': InvalidOrder,  # Order strategy type error
                    '32061': InvalidOrder,  # Order strategy initiative limit error
                    '32062': InvalidOrder,  # Order strategy initiative range error
                    '32063': InvalidOrder,  # Order strategy initiative rate error
                    '32064': ExchangeError,  # Time Stringerval of orders should set between 5-120s
                    '32065': ExchangeError,  # Close amount exceeds the limit of Market-close-all(999 for BTC, and 9999 for the rest tokens)
                    '32066': ExchangeError,  # You have open orders. Please cancel all open orders before changing your leverage level.
                    '32067': ExchangeError,  # Account equity < required hasattr(self, margin) setting. Please adjust your leverage level again.
                    '32068': ExchangeError,  # The margin for self position will fall short of the required hasattr(self, margin) setting. Please adjust your leverage level or increase your margin to proceed.
                    '32069': ExchangeError,  # Target leverage level too low. Your account balance is insufficient to cover the margin required. Please adjust the leverage level again.
                    '32070': ExchangeError,  # Please check open position or unfilled order
                    '32071': ExchangeError,  # Your current liquidation mode does not support self action.
                    '32072': ExchangeError,  # The highest available margin for your order’s tier is {0}. Please edit your margin and place a new order.
                    '32073': ExchangeError,  # The action does not apply to the token
                    '32074': ExchangeError,  # The number of contracts of your position, open orders, and the current order has exceeded the maximum order limit of self asset.
                    '32075': ExchangeError,  # Account risk rate breach
                    '32076': ExchangeError,  # Liquidation of the holding position(s) at market price will require cancellation of all pending close orders of the contracts.
                    '32077': ExchangeError,  # Your margin for self asset in futures account is insufficient and the position has been taken over for liquidation.(You will not be able to place orders, close positions, transfer funds, or add margin during self period of time. Your account will be restored after the liquidation is complete.)
                    '32078': ExchangeError,  # Please cancel all open orders before switching the liquidation mode(Please cancel all open orders before switching the liquidation mode)
                    '32079': ExchangeError,  # Your open positions are at high risk.(Please add margin or reduce positions before switching the mode)
                    '32080': ExchangeError,  # Funds cannot be transferred out within 30 minutes after futures settlement
                    '32083': ExchangeError,  # The number of contracts should be a positive multiple of %%. Please place your order again
                    # token and margin trading
                    '33001': PermissionDenied,  # {"code": 33001, "message": "margin account for self pair is not enabled yet"}
                    '33002': AccountSuspended,  # {"code": 33002, "message": "margin account for self pair is suspended"}
                    '33003': InsufficientFunds,  # {"code": 33003, "message": "no loan balance"}
                    '33004': ExchangeError,  # {"code": 33004, "message": "loan amount cannot be smaller than the minimum limit"}
                    '33005': ExchangeError,  # {"code": 33005, "message": "repayment amount must exceed 0"}
                    '33006': ExchangeError,  # {"code": 33006, "message": "loan order not found"}
                    '33007': ExchangeError,  # {"code": 33007, "message": "status not found"}
                    '33008': InsufficientFunds,  # {"code": 33008, "message": "loan amount cannot exceed the maximum limit"}
                    '33009': ExchangeError,  # {"code": 33009, "message": "user ID is blank"}
                    '33010': ExchangeError,  # {"code": 33010, "message": "you cannot cancel an order during session 2 of call auction"}
                    '33011': ExchangeError,  # {"code": 33011, "message": "no new market data"}
                    '33012': ExchangeError,  # {"code": 33012, "message": "order cancellation failed"}
                    '33013': InvalidOrder,  # {"code": 33013, "message": "order placement failed"}
                    '33014': OrderNotFound,  # {"code": 33014, "message": "order does not exist"}
                    '33015': InvalidOrder,  # {"code": 33015, "message": "exceeded maximum limit"}
                    '33016': ExchangeError,  # {"code": 33016, "message": "margin trading is not open for self token"}
                    '33017': InsufficientFunds,  # {"code": 33017, "message": "insufficient balance"}
                    '33018': ExchangeError,  # {"code": 33018, "message": "self parameter must be smaller than 1"}
                    '33020': ExchangeError,  # {"code": 33020, "message": "request not supported"}
                    '33021': BadRequest,  # {"code": 33021, "message": "token and the pair do not match"}
                    '33022': InvalidOrder,  # {"code": 33022, "message": "pair and the order do not match"}
                    '33023': ExchangeError,  # {"code": 33023, "message": "you can only place market orders during call auction"}
                    '33024': InvalidOrder,  # {"code": 33024, "message": "trading amount too small"}
                    '33025': InvalidOrder,  # {"code": 33025, "message": "base token amount is blank"}
                    '33026': ExchangeError,  # {"code": 33026, "message": "transaction completed"}
                    '33027': InvalidOrder,  # {"code": 33027, "message": "cancelled order or order cancelling"}
                    '33028': InvalidOrder,  # {"code": 33028, "message": "the decimal places of the trading price exceeded the limit"}
                    '33029': InvalidOrder,  # {"code": 33029, "message": "the decimal places of the trading size exceeded the limit"}
                    '33034': ExchangeError,  # {"code": 33034, "message": "You can only place limit order after Call Auction has started"}
                    '33035': ExchangeError,  # This type of order cannot be canceled(This type of order cannot be canceled)
                    '33036': ExchangeError,  # Exceeding the limit of entrust order
                    '33037': ExchangeError,  # The buy order price should be lower than 130% of the trigger price
                    '33038': ExchangeError,  # The sell order price should be higher than 70% of the trigger price
                    '33039': ExchangeError,  # The limit of callback rate is 0 < x <= 5%
                    '33040': ExchangeError,  # The trigger price of a buy order should be lower than the latest transaction price
                    '33041': ExchangeError,  # The trigger price of a sell order should be higher than the latest transaction price
                    '33042': ExchangeError,  # The limit of price variance is 0 < x <= 1%
                    '33043': ExchangeError,  # The total amount must be larger than 0
                    '33044': ExchangeError,  # The average amount should be 1/1000 * total amount <= x <= total amount
                    '33045': ExchangeError,  # The price should not be 0, including trigger price, order price, and price limit
                    '33046': ExchangeError,  # Price variance should be 0 < x <= 1%
                    '33047': ExchangeError,  # Sweep ratio should be 0 < x <= 100%
                    '33048': ExchangeError,  # Per order limit: Total amount/1000 < x <= Total amount
                    '33049': ExchangeError,  # Total amount should be X > 0
                    '33050': ExchangeError,  # Time interval should be 5 <= x <= 120s
                    '33051': ExchangeError,  # cancel order number not higher limit: plan and track entrust no more than 10, ice and time entrust no more than 6
                    '33059': BadRequest,  # {"code": 33059, "message": "client_oid or order_id is required"}
                    '33060': BadRequest,  # {"code": 33060, "message": "Only fill in either parameter client_oid or order_id"}
                    '33061': ExchangeError,  # Value of a single market price order cannot exceed 100,000 USD
                    '33062': ExchangeError,  # The leverage ratio is too high. The borrowed position has exceeded the maximum position of self leverage ratio. Please readjust the leverage ratio
                    '33063': ExchangeError,  # Leverage multiple is too low, there is insufficient margin in the account, please readjust the leverage ratio
                    '33064': ExchangeError,  # The setting of the leverage ratio cannot be less than 2, please readjust the leverage ratio
                    '33065': ExchangeError,  # Leverage ratio exceeds maximum leverage ratio, please readjust leverage ratio
                    # account
                    '21009': ExchangeError,  # Funds cannot be transferred out within 30 minutes after swap settlement(Funds cannot be transferred out within 30 minutes after swap settlement)
                    '34001': PermissionDenied,  # {"code": 34001, "message": "withdrawal suspended"}
                    '34002': InvalidAddress,  # {"code": 34002, "message": "please add a withdrawal address"}
                    '34003': ExchangeError,  # {"code": 34003, "message": "sorry, self token cannot be withdrawn to xx at the moment"}
                    '34004': ExchangeError,  # {"code": 34004, "message": "withdrawal fee is smaller than minimum limit"}
                    '34005': ExchangeError,  # {"code": 34005, "message": "withdrawal fee exceeds the maximum limit"}
                    '34006': ExchangeError,  # {"code": 34006, "message": "withdrawal amount is lower than the minimum limit"}
                    '34007': ExchangeError,  # {"code": 34007, "message": "withdrawal amount exceeds the maximum limit"}
                    '34008': InsufficientFunds,  # {"code": 34008, "message": "insufficient balance"}
                    '34009': ExchangeError,  # {"code": 34009, "message": "your withdrawal amount exceeds the daily limit"}
                    '34010': ExchangeError,  # {"code": 34010, "message": "transfer amount must be larger than 0"}
                    '34011': ExchangeError,  # {"code": 34011, "message": "conditions not met"}
                    '34012': ExchangeError,  # {"code": 34012, "message": "the minimum withdrawal amount for NEO is 1, and the amount must be an integer"}
                    '34013': ExchangeError,  # {"code": 34013, "message": "please transfer"}
                    '34014': ExchangeError,  # {"code": 34014, "message": "transfer limited"}
                    '34015': ExchangeError,  # {"code": 34015, "message": "subaccount does not exist"}
                    '34016': PermissionDenied,  # {"code": 34016, "message": "transfer suspended"}
                    '34017': AccountSuspended,  # {"code": 34017, "message": "account suspended"}
                    '34018': AuthenticationError,  # {"code": 34018, "message": "incorrect trades password"}
                    '34019': PermissionDenied,  # {"code": 34019, "message": "please bind your email before withdrawal"}
                    '34020': PermissionDenied,  # {"code": 34020, "message": "please bind your funds password before withdrawal"}
                    '34021': InvalidAddress,  # {"code": 34021, "message": "Not verified address"}
                    '34022': ExchangeError,  # {"code": 34022, "message": "Withdrawals are not available for sub accounts"}
                    '34023': PermissionDenied,  # {"code": 34023, "message": "Please enable futures trading before transferring your funds"}
                    '34026': ExchangeError,  # transfer too frequently(transfer too frequently)
                    '34036': ExchangeError,  # Parameter is incorrect, please refer to API documentation
                    '34037': ExchangeError,  # Get the sub-account balance interface, account type is not supported
                    '34038': ExchangeError,  # Since your C2C transaction is unusual, you are restricted from fund transfer. Please contact our customer support to cancel the restriction
                    '34039': ExchangeError,  # You are now restricted from transferring out your funds due to abnormal trades on C2C Market. Please transfer your fund on our website or app instead to verify your identity
                    # swap
                    '35001': ExchangeError,  # {"code": 35001, "message": "Contract does not exist"}
                    '35002': ExchangeError,  # {"code": 35002, "message": "Contract settling"}
                    '35003': ExchangeError,  # {"code": 35003, "message": "Contract paused"}
                    '35004': ExchangeError,  # {"code": 35004, "message": "Contract pending settlement"}
                    '35005': AuthenticationError,  # {"code": 35005, "message": "User does not exist"}
                    '35008': InvalidOrder,  # {"code": 35008, "message": "Risk ratio too high"}
                    '35010': InvalidOrder,  # {"code": 35010, "message": "Position closing too large"}
                    '35012': InvalidOrder,  # {"code": 35012, "message": "Incorrect order size"}
                    '35014': InvalidOrder,  # {"code": 35014, "message": "Order price is not within limit"}
                    '35015': InvalidOrder,  # {"code": 35015, "message": "Invalid leverage level"}
                    '35017': ExchangeError,  # {"code": 35017, "message": "Open orders exist"}
                    '35019': InvalidOrder,  # {"code": 35019, "message": "Order size too large"}
                    '35020': InvalidOrder,  # {"code": 35020, "message": "Order price too high"}
                    '35021': InvalidOrder,  # {"code": 35021, "message": "Order size exceeded current tier limit"}
                    '35022': ExchangeError,  # {"code": 35022, "message": "Contract status error"}
                    '35024': ExchangeError,  # {"code": 35024, "message": "Contract not initialized"}
                    '35025': InsufficientFunds,  # {"code": 35025, "message": "No account balance"}
                    '35026': ExchangeError,  # {"code": 35026, "message": "Contract settings not initialized"}
                    '35029': OrderNotFound,  # {"code": 35029, "message": "Order does not exist"}
                    '35030': InvalidOrder,  # {"code": 35030, "message": "Order size too large"}
                    '35031': InvalidOrder,  # {"code": 35031, "message": "Cancel order size too large"}
                    '35032': ExchangeError,  # {"code": 35032, "message": "Invalid user status"}
                    '35037': ExchangeError,  # No last traded price in cache
                    '35039': ExchangeError,  # {"code": 35039, "message": "Open order quantity exceeds limit"}
                    '35040': InvalidOrder,  # {"error_message":"Invalid order type","result":"true","error_code":"35040","order_id":"-1"}
                    '35044': ExchangeError,  # {"code": 35044, "message": "Invalid order status"}
                    '35046': InsufficientFunds,  # {"code": 35046, "message": "Negative account balance"}
                    '35047': InsufficientFunds,  # {"code": 35047, "message": "Insufficient account balance"}
                    '35048': ExchangeError,  # {"code": 35048, "message": "User contract is frozen and liquidating"}
                    '35049': InvalidOrder,  # {"code": 35049, "message": "Invalid order type"}
                    '35050': InvalidOrder,  # {"code": 35050, "message": "Position settings are blank"}
                    '35052': InsufficientFunds,  # {"code": 35052, "message": "Insufficient cross margin"}
                    '35053': ExchangeError,  # {"code": 35053, "message": "Account risk too high"}
                    '35055': InsufficientFunds,  # {"code": 35055, "message": "Insufficient account balance"}
                    '35057': ExchangeError,  # {"code": 35057, "message": "No last traded price"}
                    '35058': ExchangeError,  # {"code": 35058, "message": "No limit"}
                    '35059': BadRequest,  # {"code": 35059, "message": "client_oid or order_id is required"}
                    '35060': BadRequest,  # {"code": 35060, "message": "Only fill in either parameter client_oid or order_id"}
                    '35061': BadRequest,  # {"code": 35061, "message": "Invalid instrument_id"}
                    '35062': InvalidOrder,  # {"code": 35062, "message": "Invalid match_price"}
                    '35063': InvalidOrder,  # {"code": 35063, "message": "Invalid order_size"}
                    '35064': InvalidOrder,  # {"code": 35064, "message": "Invalid client_oid"}
                    '35066': InvalidOrder,  # Order interval error
                    '35067': InvalidOrder,  # Time-weighted order ratio error
                    '35068': InvalidOrder,  # Time-weighted order range error
                    '35069': InvalidOrder,  # Time-weighted single transaction limit error
                    '35070': InvalidOrder,  # Algo order type error
                    '35071': InvalidOrder,  # Order total must be larger than single order limit
                    '35072': InvalidOrder,  # Maximum 6 unfulfilled time-weighted orders can be held at the same time
                    '35073': InvalidOrder,  # Order price is 0. Market-close-all not available
                    '35074': InvalidOrder,  # Iceberg order single transaction average error
                    '35075': InvalidOrder,  # Failed to cancel order
                    '35076': InvalidOrder,  # LTC 20x leverage. Not allowed to open position
                    '35077': InvalidOrder,  # Maximum 6 unfulfilled iceberg orders can be held at the same time
                    '35078': InvalidOrder,  # Order amount exceeded 100,000
                    '35079': InvalidOrder,  # Iceberg order price variance error
                    '35080': InvalidOrder,  # Callback rate error
                    '35081': InvalidOrder,  # Maximum 10 unfulfilled trail orders can be held at the same time
                    '35082': InvalidOrder,  # Trail order callback rate error
                    '35083': InvalidOrder,  # Each user can only hold a maximum of 10 unfulfilled stop-limit orders at the same time
                    '35084': InvalidOrder,  # Order amount exceeded 1 million
                    '35085': InvalidOrder,  # Order amount is not in the correct range
                    '35086': InvalidOrder,  # Price exceeds 100 thousand
                    '35087': InvalidOrder,  # Price exceeds 100 thousand
                    '35088': InvalidOrder,  # Average amount error
                    '35089': InvalidOrder,  # Price exceeds 100 thousand
                    '35090': ExchangeError,  # No stop-limit orders available for cancelation
                    '35091': ExchangeError,  # No trail orders available for cancellation
                    '35092': ExchangeError,  # No iceberg orders available for cancellation
                    '35093': ExchangeError,  # No trail orders available for cancellation
                    '35094': ExchangeError,  # Stop-limit order last traded price error
                    '35095': BadRequest,  # Instrument_id error
                    '35096': ExchangeError,  # Algo order status error
                    '35097': ExchangeError,  # Order status and order ID cannot exist at the same time
                    '35098': ExchangeError,  # An order status or order ID must exist
                    '35099': ExchangeError,  # Algo order ID error
                    # option
                    '36001': BadRequest,  # Invalid underlying index.
                    '36002': BadRequest,  # Instrument does not exist.
                    '36005': ExchangeError,  # Instrument status is invalid.
                    '36101': AuthenticationError,  # Account does not exist.
                    '36102': PermissionDenied,  # Account status is invalid.
                    '36103': AccountSuspended,  # Account is suspended due to ongoing liquidation.
                    '36104': PermissionDenied,  # Account is not enabled for options trading.
                    '36105': PermissionDenied,  # Please enable the account for option contract.
                    '36106': AccountSuspended,  # Funds cannot be transferred in or out, is suspended.
                    '36107': PermissionDenied,  # Funds cannot be transferred out within 30 minutes after option exercising or settlement.
                    '36108': InsufficientFunds,  # Funds cannot be transferred in or out, of the account is less than zero.
                    '36109': PermissionDenied,  # Funds cannot be transferred in or out during option exercising or settlement.
                    '36201': PermissionDenied,  # New order function is blocked.
                    '36202': PermissionDenied,  # Account does not have permission to short option.
                    '36203': InvalidOrder,  # Invalid format for client_oid.
                    '36204': ExchangeError,  # Invalid format for request_id.
                    '36205': BadRequest,  # Instrument id does not match underlying index.
                    '36206': BadRequest,  # Order_id and client_oid can not be used at the same time.
                    '36207': InvalidOrder,  # Either order price or fartouch price must be present.
                    '36208': InvalidOrder,  # Either order price or size must be present.
                    '36209': InvalidOrder,  # Either order_id or client_oid must be present.
                    '36210': InvalidOrder,  # Either order_ids or client_oids must be present.
                    '36211': InvalidOrder,  # Exceeding max batch size for order submission.
                    '36212': InvalidOrder,  # Exceeding max batch size for oder cancellation.
                    '36213': InvalidOrder,  # Exceeding max batch size for order amendment.
                    '36214': ExchangeError,  # Instrument does not have valid bid/ask quote.
                    '36216': OrderNotFound,  # Order does not exist.
                    '36217': InvalidOrder,  # Order submission failed.
                    '36218': InvalidOrder,  # Order cancellation failed.
                    '36219': InvalidOrder,  # Order amendment failed.
                    '36220': InvalidOrder,  # Order is pending cancel.
                    '36221': InvalidOrder,  # Order qty is not valid multiple of lot size.
                    '36222': InvalidOrder,  # Order price is breaching highest buy limit.
                    '36223': InvalidOrder,  # Order price is breaching lowest sell limit.
                    '36224': InvalidOrder,  # Exceeding max order size.
                    '36225': InvalidOrder,  # Exceeding max open order count for instrument.
                    '36226': InvalidOrder,  # Exceeding max open order count for underlying.
                    '36227': InvalidOrder,  # Exceeding max open size across all orders for underlying
                    '36228': InvalidOrder,  # Exceeding max available qty for instrument.
                    '36229': InvalidOrder,  # Exceeding max available qty for underlying.
                    '36230': InvalidOrder,  # Exceeding max position limit for underlying.
                    # --------------------------------------------------------
                    # swap
                    '400': BadRequest,  # Bad Request
                    '401': AuthenticationError,  # Unauthorized access
                    '403': PermissionDenied,  # Access prohibited
                    '404': BadRequest,  # Request address does not exist
                    '405': BadRequest,  # The HTTP Method is not supported
                    '415': BadRequest,  # The current media type is not supported
                    '429': DDoSProtection,  # Too many requests
                    '500': ExchangeNotAvailable,  # System busy
                    '1001': RateLimitExceeded,  # The request is too frequent and has been throttled
                    '1002': ExchangeError,  # {0} verifications within 24 hours
                    '1003': ExchangeError,  # You failed more than {0} times today, the current operation is locked, please try again in 24 hours
                    # '00000': ExchangeError,  # success
                    '40001': AuthenticationError,  # ACCESS_KEY cannot be empty
                    '40002': AuthenticationError,  # SECRET_KEY cannot be empty
                    '40003': AuthenticationError,  # Signature cannot be empty
                    '40004': InvalidNonce,  # Request timestamp expired
                    '40005': InvalidNonce,  # Invalid ACCESS_TIMESTAMP
                    '40006': AuthenticationError,  # Invalid ACCESS_KEY
                    '40007': BadRequest,  # Invalid Content_Type
                    '40008': InvalidNonce,  # Request timestamp expired
                    '40009': AuthenticationError,  # sign signature error
                    '40010': AuthenticationError,  # sign signature error
                    '40011': AuthenticationError,  # ACCESS_PASSPHRASE cannot be empty
                    '40012': AuthenticationError,  # apikey/password is incorrect
                    '40013': ExchangeError,  # User status is abnormal
                    '40014': PermissionDenied,  # Incorrect permissions
                    '40015': ExchangeError,  # System is abnormal, please try again later
                    '40016': PermissionDenied,  # The user must bind the phone or Google
                    '40017': ExchangeError,  # Parameter verification failed
                    '40018': PermissionDenied,  # Invalid IP
                    '40019': BadRequest,  # {"code":"40019","msg":"Parameter QLCUSDT_SPBL cannot be empty","requestTime":1679196063659,"data":null}
                    '40031': AccountSuspended,  # The account has been cancelled and cannot be used again
                    '40037': AuthenticationError,  # Apikey does not exist
                    '40102': BadRequest,  # Contract configuration does not exist, please check the parameters
                    '40103': BadRequest,  # Request method cannot be empty
                    '40104': ExchangeError,  # Lever adjustment failure
                    '40105': ExchangeError,  # Abnormal access to current price limit data
                    '40106': ExchangeError,  # Abnormal get next settlement time
                    '40107': ExchangeError,  # Abnormal access to index price data
                    '40108': InvalidOrder,  # Wrong order quantity
                    '40109': OrderNotFound,  # The data of the order cannot be found, please confirm the order number
                    '40200': OnMaintenance,  # Server upgrade, please try again later
                    '40201': InvalidOrder,  # Order number cannot be empty
                    '40202': ExchangeError,  # User information cannot be empty
                    '40203': BadRequest,  # The amount of adjustment margin cannot be empty or negative
                    '40204': BadRequest,  # Adjustment margin type cannot be empty
                    '40205': BadRequest,  # Adjusted margin type data is wrong
                    '40206': BadRequest,  # The direction of the adjustment margin cannot be empty
                    '40207': BadRequest,  # The adjustment margin data is wrong
                    '40208': BadRequest,  # The accuracy of the adjustment margin amount is incorrect
                    '40209': BadRequest,  # The current page number is wrong, please confirm
                    '40300': ExchangeError,  # User does not exist
                    '40301': PermissionDenied,  # Permission has not been obtained yet. If you need to use it, please contact customer service
                    '40302': BadRequest,  # Parameter abnormality
                    '40303': BadRequest,  # Can only query up to 20,000 data
                    '40304': BadRequest,  # Parameter type is abnormal
                    '40305': BadRequest,  # Client_oid length is not greater than 50, and cannot be Martian characters
                    '40306': ExchangeError,  # Batch processing orders can only process up to 20
                    '40308': OnMaintenance,  # The contract is being temporarily maintained
                    '40309': BadSymbol,  # The contract has been removed
                    '40400': ExchangeError,  # Status check abnormal
                    '40401': ExchangeError,  # The operation cannot be performed
                    '40402': BadRequest,  # The opening direction cannot be empty
                    '40403': BadRequest,  # Wrong opening direction format
                    '40404': BadRequest,  # Whether to enable automatic margin call parameters cannot be empty
                    '40405': BadRequest,  # Whether to enable the automatic margin call parameter type is wrong
                    '40406': BadRequest,  # Whether to enable automatic margin call parameters is of unknown type
                    '40407': ExchangeError,  # The query direction is not the direction entrusted by the plan
                    '40408': ExchangeError,  # Wrong time range
                    '40409': ExchangeError,  # Time format error
                    '40500': InvalidOrder,  # Client_oid check error
                    '40501': ExchangeError,  # Channel name error
                    '40502': ExchangeError,  # If it is a copy user, you must pass the copy to whom
                    '40503': ExchangeError,  # With the single type
                    '40504': ExchangeError,  # Platform code must pass
                    '40505': ExchangeError,  # Not the same type
                    '40506': AuthenticationError,  # Platform signature error
                    '40507': AuthenticationError,  # Api signature error
                    '40508': ExchangeError,  # KOL is not authorized
                    '40509': ExchangeError,  # Abnormal copy end
                    '40600': ExchangeError,  # Copy function suspended
                    '40601': ExchangeError,  # Followers cannot be KOL
                    '40602': ExchangeError,  # The number of copies has reached the limit and cannot process the request
                    '40603': ExchangeError,  # Abnormal copy end
                    '40604': ExchangeNotAvailable,  # Server is busy, please try again later
                    '40605': ExchangeError,  # Copy type, the copy number must be passed
                    '40606': ExchangeError,  # The type of document number is wrong
                    '40607': ExchangeError,  # Document number must be passed
                    '40608': ExchangeError,  # No documented products currently supported
                    '40609': ExchangeError,  # The contract product does not support copying
                    '40700': BadRequest,  # Cursor parameters are incorrect
                    '40701': ExchangeError,  # KOL is not authorized
                    '40702': ExchangeError,  # Unauthorized copying user
                    '40703': ExchangeError,  # Bill inquiry start and end time cannot be empty
                    '40704': ExchangeError,  # Can only check the data of the last three months
                    '40705': BadRequest,  # The start and end time cannot exceed 90 days
                    '40706': InvalidOrder,  # Wrong order price
                    '40707': BadRequest,  # Start time is greater than end time
                    '40708': BadRequest,  # Parameter verification is abnormal
                    '40709': ExchangeError,  # There is no hasattr(self, position) position, and no automatic margin call can be set
                    '40710': ExchangeError,  # Abnormal account status
                    '40711': InsufficientFunds,  # Insufficient contract account balance
                    '40712': InsufficientFunds,  # Insufficient margin
                    '40713': ExchangeError,  # Cannot exceed the maximum transferable margin amount
                    '40714': ExchangeError,  # No direct margin call is allowed
                    '40762': InsufficientFunds,  # {"code":"40762","msg":"The order amount exceeds the balance","requestTime":1716572156622,"data":null}
                    '40768': OrderNotFound,  # Order does not exist
                    '40808': InvalidOrder,  # {"code":"40808","msg":"Parameter verification exception size checkBDScale error value=2293.577 checkScale=2","requestTime":1725638500052,"data":null}
                    '41103': InvalidOrder,  # {"code":"41103","msg":"param price scale error error","requestTime":1725635883561,"data":null}
                    '41114': OnMaintenance,  # {"code":"41114","msg":"The current trading pair is under maintenance, please refer to the official announcement for the opening time","requestTime":1679196062544,"data":null}
                    '43011': InvalidOrder,  # The parameter does not meet the specification executePrice <= 0
                    '43001': OrderNotFound,
                    '43012': InsufficientFunds,  # {"code":"43012","msg":"Insufficient balance","requestTime":1711648951774,"data":null}
                    '43025': InvalidOrder,  # Plan order does not exist
                    '43115': OnMaintenance,  # {"code":"43115","msg":"The current trading pair is opening soon, please refer to the official announcement for the opening time","requestTime":1688907202434,"data":null}
                    '45110': InvalidOrder,  # {"code":"45110","msg":"less than the minimum amount 5 USDT","requestTime":1669911118932,"data":null}
                    # spot
                    'invalid sign': AuthenticationError,
                    'invalid currency': BadSymbol,  # invalid trading pair
                    'invalid symbol': BadSymbol,
                    'invalid period': BadRequest,  # invalid Kline type
                    'invalid user': ExchangeError,
                    'invalid amount': InvalidOrder,
                    'invalid type': InvalidOrder,  # {"status":"error","ts":1595700344504,"err_code":"invalid-parameter","err_msg":"invalid type"}
                    'invalid orderId': InvalidOrder,
                    'invalid record': ExchangeError,
                    'invalid accountId': BadRequest,
                    'invalid address': BadRequest,
                    'accesskey not None': AuthenticationError,  # {"status":"error","ts":1595704360508,"err_code":"invalid-parameter","err_msg":"accesskey not null"}
                    'illegal accesskey': AuthenticationError,
                    'sign not null': AuthenticationError,
                    'req_time is too much difference from server time': InvalidNonce,
                    'permissions not right': PermissionDenied,  # {"status":"error","ts":1595704490084,"err_code":"invalid-parameter","err_msg":"permissions not right"}
                    'illegal sign invalid': AuthenticationError,  # {"status":"error","ts":1595684716042,"err_code":"invalid-parameter","err_msg":"illegal sign invalid"}
                    'user locked': AccountSuspended,
                    'Request Frequency Is Too High': RateLimitExceeded,
                    'more than a daily rate of cash': BadRequest,
                    'more than the maximum daily withdrawal amount': BadRequest,
                    'need to bind email or mobile': ExchangeError,
                    'user forbid': PermissionDenied,
                    'User Prohibited Cash Withdrawal': PermissionDenied,
                    'Cash Withdrawal Is Less Than The Minimum Value': BadRequest,
                    'Cash Withdrawal Is More Than The Maximum Value': BadRequest,
                    'the account with in 24 hours ban coin': PermissionDenied,
                    'order cancel fail': BadRequest,  # {"status":"error","ts":1595703343035,"err_code":"bad-request","err_msg":"order cancel fail"}
                    'base symbol error': BadSymbol,
                    'base date error': ExchangeError,
                    'api signature not valid': AuthenticationError,
                    'gateway internal error': ExchangeError,
                    'audit failed': ExchangeError,
                    'order queryorder invalid': BadRequest,
                    'market no need price': InvalidOrder,
                    'limit need price': InvalidOrder,
                    'userid not equal to account_id': ExchangeError,
                    'your balance is low': InsufficientFunds,  # {"status":"error","ts":1595594160149,"err_code":"invalid-parameter","err_msg":"invalid size, valid range: [1,2000]"}
                    'address invalid cointype': ExchangeError,
                    'system exception': ExchangeError,  # {"status":"error","ts":1595711862763,"err_code":"system exception","err_msg":"system exception"}
                    '50003': ExchangeError,  # No record
                    '50004': BadSymbol,  # The transaction pair is currently not supported or has been suspended
                    '50006': PermissionDenied,  # The account is forbidden to withdraw. If you have any questions, please contact customer service.
                    '50007': PermissionDenied,  # The account is forbidden to withdraw within 24 hours. If you have any questions, please contact customer service.
                    '50008': RequestTimeout,  # network timeout
                    '50009': RateLimitExceeded,  # The operation is too frequent, please try again later
                    '50010': ExchangeError,  # The account is abnormally frozen. If you have any questions, please contact customer service.
                    '50014': InvalidOrder,  # The transaction amount under minimum limits
                    '50015': InvalidOrder,  # The transaction amount exceed maximum limits
                    '50016': InvalidOrder,  # The price can't be higher than the current price
                    '50017': InvalidOrder,  # Price under minimum limits
                    '50018': InvalidOrder,  # The price exceed maximum limits
                    '50019': InvalidOrder,  # The amount under minimum limits
                    '50020': InsufficientFunds,  # Insufficient balance
                    '50021': InvalidOrder,  # Price is under minimum limits
                    '50026': InvalidOrder,  # Market price parameter error
                    'invalid order query time': ExchangeError,  # start time is greater than end time; or the time interval between start time and end time is greater than 48 hours
                    'invalid start time': BadRequest,  # start time is a date 30 days ago; or start time is a date in the future
                    'invalid end time': BadRequest,  # end time is a date 30 days ago; or end time is a date in the future
                    '20003': ExchangeError,  # operation failed, {"status":"error","ts":1595730308979,"err_code":"bad-request","err_msg":"20003"}
                    '01001': ExchangeError,  # order failed, {"status":"fail","err_code":"01001","err_msg":"系统异常，请稍后重试"}
                    '43111': PermissionDenied,  # {"code":"43111","msg":"参数错误 address not in address book","requestTime":1665394201164,"data":null}
                },
                'broad': {
                    'invalid size, valid range': ExchangeError,
                },
            },
            'precisionMode': TICK_SIZE,
            'commonCurrencies': {},
            'options': {
                'timeDifference': 0,  # the difference between system clock and Binance clock
                'adjustForTimeDifference': False,  # controls the adjustment logic upon instantiation
                'timeframes': {
                    'swap': {
                        '1m': '1m',
                        '3m': '3m',
                        '5m': '5m',
                        '15m': '15m',
                        '30m': '30m',
                        '1h': '1H',
                        '2h': '2H',
                        '4h': '4H',
                        '6h': '6Hutc',
                        '12h': '12Hutc',
                        '1d': '1Dutc',
                        '3d': '3Dutc',
                        '1w': '1Wutc',
                        '1M': '1Mutc',
                    },
                },
                'fetchMarkets': [
                    'swap',  # there is future markets but they use the same endpoints
                ],
                'defaultType': 'swap',  # 'spot', 'swap', 'future'
                'createMarketBuyOrderRequiresPrice': True,
                'broker': None,
                'sandboxMode': False,
                'defaultTimeInForce': 'GTC',  # 'GTC' = Good To Cancel(default), 'IOC' = Immediate Or Cancel
            },
            'features': {
                'default': {
                    'sandbox': True,
                    'createOrder': {
                        'marginMode': True,
                        'triggerPrice': None,
                        'triggerPriceType': None,
                        'triggerDirection': None,
                        'stopLossPrice': False,  # todo by triggerPrice
                        'takeProfitPrice': False,  # todo by triggerPrice
                        'attachedStopLossTakeProfit': None,
                        'timeInForce': {
                            'GTC': True,
                            'IOC': True,
                            'FOK': True,
                            'PO': True,
                            'GTD': False,
                        },
                        'hedged': False,
                        'trailing': False,
                        'leverage': True,  # todo implement
                        'marketBuyByCost': False,
                        'marketBuyRequiresPrice': False,
                        'selfTradePrevention': False,
                        'iceberg': False,  # todo implement
                    },
                    'createOrders': {
                        'max': 10,
                    },
                    'fetchMyTrades': {
                        'marginMode': False,
                        'limit': 100,
                        'daysBack': None,
                        'untilDays': 7,
                        'symbolRequired': False,
                    },
                    'fetchOrder': {
                        'marginMode': False,
                        'trigger': True,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOpenOrders': {
                        'marginMode': False,
                        'limit': 500,
                        'trigger': True,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOrders': None,
                    'fetchClosedOrders': None,
                    'fetchOHLCV': {
                        'limit': 1000,
                    },
                },
                'spot': {
                    'extends': 'default',
                },
                'forDerivatives': {
                    'extends': 'default',
                    'createOrder': {
                        # todo: implementation needs unification
                        'triggerPriceType': None,
                        'attachedStopLossTakeProfit': {
                            # todo: implementation needs unification
                            'triggerPriceType': None,
                            'price': False,
                        },
                    },
                },
                'swap': {
                    'linear': {
                        'extends': 'forDerivatives',
                    },
                    'inverse': None,
                },
                'future': {
                    'linear': None,
                    'inverse': None,
                },
            },
        })

    def fetch_status(self, params={}):
        """
        the latest known information on the availability of the exchange API

        https://dex-aggregator-front-git-perp-navi-fd9a1df6.vercel.app/

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
        """
        response = self.publicGetInfoPing(params)
        # {
        #     "error": False,
        #     "code": 200,
        #     "msg": "SUCCESS",
        #     "data": "pong",
        #     "sid": "1748419173585-001-f784"
        # }
        status = self.safe_string(response, 'data')
        if status is None:
            status = 'error'
        elif status == 'pong':
            status = 'ok'
        else:
            status = 'maintenance'
        return {
            'status': status,
            'updated': None,
            'eta': None,
            'url': None,
            'info': response,
        }

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

        https://dex-aggregator-front-git-perp-navi-fd9a1df6.vercel.app/

        :param dict [params]: extra parameters specific to the exchange api endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = self.publicGetInfoPairs(params)
        # {
        #     "error": False,
        #     "code": 200,
        #     "msg": "SUCCESS",
        #     "data": [
        #         {
        #             "id": 1,
        #             "tradeCoinId": 2,
        #             "tradeCoinName": "ETH",
        #             "tradeDecimal": 3,
        #             "priceDecimal": 2,
        #             "settleDecimal": 6,
        #             "settleCoinId": 4,
        #             "settleCoinName": "USD",
        #             "swapCoinId": 2,
        #             "swapCoinName": null,
        #             "symbol": "ETH-USD",
        #             "classifyId": null,
        #             "categoryId": null,
        #             "visible": 0,
        #             "tradable": True,
        #             "status": null,
        #             "sort": null,
        #             "isDual": False,
        #             "faceMultiplier": "1",
        #             "isDelivery": False,
        #             "deliveryTime": null,
        #             "deliveryMarketPrice": null,
        #             "deliveryStatus": null,
        #             "takerTradeFeeRate": "0.02",
        #             "makerTradeFeeRate": "0.015",
        #             "pair": "ETH-USD",
        #             "minCount": "0.01",
        #             "maxCount": "1000000",
        #             "brandExchange": null,
        #             "platform": null,
        #             "preMarket": null,
        #             "initMarkPrice": null,
        #             "releaseTime": null,
        #             "createTime": null
        #         }
        #     ],
        #     "sid": "1748419418733-001-5610"
        # }
        rows = self.safe_list(response, 'data', [])
        return self.parse_markets(rows)

    def parse_market(self, market: dict) -> Market:
        #         {
        #             "id": 1,
        #             "tradeCoinId": 2,
        #             "tradeCoinName": "ETH",
        #             "tradeDecimal": 3,
        #             "priceDecimal": 2,
        #             "settleDecimal": 6,
        #             "settleCoinId": 4,
        #             "settleCoinName": "USD",
        #             "swapCoinId": 2,
        #             "swapCoinName": null,
        #             "symbol": "ETH-USD",
        #             "classifyId": null,
        #             "categoryId": null,
        #             "visible": 0,
        #             "tradable": True,
        #             "status": null,
        #             "sort": null,
        #             "isDual": False,
        #             "faceMultiplier": "1",
        #             "isDelivery": False,
        #             "deliveryTime": null,
        #             "deliveryMarketPrice": null,
        #             "deliveryStatus": null,
        #             "takerTradeFeeRate": "0.02",
        #             "makerTradeFeeRate": "0.015",
        #             "pair": "ETH-USD",
        #             "minCount": "0.01",
        #             "maxCount": "1000000",
        #             "brandExchange": null,
        #             "platform": null,
        #             "preMarket": null,
        #             "initMarkPrice": null,
        #             "releaseTime": null,
        #             "createTime": null
        #         }
        marketId = self.safe_string(market, 'symbol')
        marketType = 'swap'
        baseId = self.safe_string(market, 'tradeCoinName')
        quoteId = self.safe_string(market, 'settleCoinName')
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        settleId: Str = self.safe_string(market, 'settleCoinName')
        settle: Str = self.safe_currency_code(settleId)
        symbol = base + '/' + quote + ':' + settle
        status = self.safe_bool(market, 'tradable')
        active = None
        if status is not None:
            active = status
        return {
            'id': marketId,
            'symbol': symbol,
            'base': base,
            'quote': quote,
            'settle': settle,
            'baseId': baseId,
            'quoteId': quoteId,
            'settleId': settleId,
            'type': marketType,
            'spot': False,
            'margin': False,
            'swap': True,
            'future': False,
            'option': False,
            'active': active,
            'contract': True,
            'linear': True,
            'inverse': False,
            'taker': self.safe_number(market, 'takerTradeFeeRate'),
            'maker': self.safe_number(market, 'makerTradeFeeRate'),
            'contractSize': self.parse_number('1'),
            'expiry': None,
            'expiryDatetime': None,
            'strike': None,
            'optionType': None,
            'precision': {
                'amount': self.parse_number(self.parse_precision(self.safe_string(market, 'settleDecimal'))),
                'price': self.parse_number(self.parse_precision(self.safe_string(market, 'priceDecimal'))),
            },
            'limits': {
                'leverage': {
                    'min': None,
                    'max': None,
                },
                'amount': {
                    'min': self.safe_number(market, 'minCount'),
                    'max': self.safe_number(market, 'maxCount'),
                },
                'price': {
                    'min': None,
                    'max': None,
                },
                'cost': {
                    'min': None,
                    'max': None,
                },
            },
            'created': self.safe_integer(market, 'createTime'),
            'info': market,
        }

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

        https://dex-aggregator-front-git-perp-navi-fd9a1df6.vercel.app/

        :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.publicGetInfoTime(params)
        #  {
        #     "error": False,
        #     "code": 200,
        #     "msg": "SUCCESS",
        #     "data": 1714988294487,
        #     "sid": "1798295565880098817"
        #  }
        return self.safe_integer(response, 'data')

    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://dex-aggregator-front-git-perp-navi-fd9a1df6.vercel.app/

        :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 boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'pairName': market['id'],
            'period': self.safe_string(self.timeframes, timeframe, timeframe),
        }
        if limit is not None:
            request['limit'] = min(limit, 1000)
        response = self.publicGetInfoKline(self.extend(request, params))
        # {
        #     "error": False,
        #     "code": 200,
        #     "msg": "SUCCESS",
        #     "data": [
        #         {
        #             "contractPairId": 1,
        #             "period": "15MIN",
        #             "time": 1748484900000,
        #             "open": "2709.24",
        #             "close": "2712.27",
        #             "low": "2708.45",
        #             "hight": "2713.09",
        #             "count": 11,
        #             "quantity": "9.554",
        #             "amount": "25917.27064"
        #         }
        #     ],
        #     "sid": "1748485042969-001-05f4"
        # }
        rows = self.safe_list(response, 'data', [])
        return self.parse_ohlcvs(rows, market, timeframe, since, limit)

    def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
        #         {
        #             "contractPairId": 1,
        #             "period": "15MIN",
        #             "time": 1748484900000,
        #             "open": "2709.24",
        #             "close": "2712.27",
        #             "low": "2708.45",
        #             "hight": "2713.09",
        #             "count": 11,
        #             "quantity": "9.554",
        #             "amount": "25917.27064"
        #         }
        return [
            self.safe_integer(ohlcv, 'time'),
            self.safe_number(ohlcv, 'open'),
            self.safe_number(ohlcv, 'hight'),
            self.safe_number(ohlcv, 'low'),
            self.safe_number(ohlcv, 'close'),
            self.safe_number(ohlcv, 'amount'),
        ]

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

        https://www.astros.com/docs/rest/futures-trading/market-data/get-part-order-book-level-2

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'pairName': market['id'],
        }
        if limit is not None:
            if (limit == 20) or (limit == 100):
                request['limit'] = limit
            else:
                raise BadRequest(self.id + ' fetchOrderBook() limit argument must be 20 or 100')
        else:
            request['limit'] = 20
        response = self.publicGetInfoDepth(self.extend(request, params))
        # {
        #     "error": False,
        #     "code": 200,
        #     "msg": "SUCCESS",
        #     "data": {
        #         "bids": [
        #             {
        #                 "price": "2731.48",
        #                 "quantity": "12.383"
        #             },
        #             {
        #                 "price": "2731.21",
        #                 "quantity": "12.169"
        #             }
        #         ],
        #         "asks": [
        #             {
        #                 "price": "2734.13",
        #                 "quantity": "13.802"
        #             },
        #             {
        #                 "price": "2734.33",
        #                 "quantity": "11.364"
        #             }
        #         ]
        #     },
        #     "sid": "1748485574687-001-4f31"
        # }
        orderbook = self.safe_dict(response, 'data', {})
        timestamp = self.milliseconds()  # the exchange does not provide timestamp for self.
        return self.parse_order_book(orderbook, market['symbol'], timestamp, 'bids', 'asks', 'price', 'quantity')

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

        https://www.astros.com/docs/rest/futures-trading/market-data/get-current-mark-price

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'pairName': market['id'],
        }
        response = self.publicGetInfoMarkPrice(self.extend(request, params))
        #
        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://www.astros.com/docs/rest/futures-trading/market-data/get-symbols-list

        :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.method]: the method to use, futuresPublicGetAllTickers or publicGetInfoPairs
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        self.load_markets()
        symbols = self.market_symbols(symbols)
        params = self.handle_option_and_params(params, 'fetchTickers', 'method', 'publicGetInfoPairs')
        response: dict = None
        response = self.publicGetInfoPairs(params)
        # {
        #     "error": False,
        #     "code": 200,
        #     "msg": "SUCCESS",
        #     "data": [
        #         {
        #             "id": 1,
        #             "tradeCoinId": 2,
        #             "tradeCoinName": "ETH",
        #             "tradeDecimal": 3,
        #             "priceDecimal": 2,
        #             "settleDecimal": 6,
        #             "settleCoinId": 4,
        #             "settleCoinName": "USD",
        #             "swapCoinId": 2,
        #             "swapCoinName": null,
        #             "symbol": "ETH-USD",
        #             "classifyId": null,
        #             "categoryId": null,
        #             "visible": 0,
        #             "tradable": True,
        #             "status": null,
        #             "sort": null,
        #             "isDual": False,
        #             "faceMultiplier": "1",
        #             "isDelivery": False,
        #             "deliveryTime": null,
        #             "deliveryMarketPrice": null,
        #             "deliveryStatus": null,
        #             "takerTradeFeeRate": "0.02",
        #             "makerTradeFeeRate": "0",
        #             "pair": "ETH-USD",
        #             "minCount": "0.01",
        #             "maxCount": "1000000",
        #             "brandExchange": null,
        #             "platform": null,
        #             "preMarket": null,
        #             "initMarkPrice": null,
        #             "releaseTime": null,
        #             "createTime": null
        #         }
        #     ],
        #     "sid": "1833508475824193537"
        # }
        data = self.safe_list(response, 'data')
        tickers = self.parse_tickers(data, symbols)
        return self.filter_by_array_tickers(tickers, 'symbol', symbols)

    def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
        #
        # from fetchMarkPrice
        # {
        #     "error": False,
        #     "code": 200,
        #     "msg": "SUCCESS",
        #     "data": "2626.1085932222",
        #     "sid": "1833512508879224833"
        # }
        #
        # from fetchTickers
        #
        # {
        #     "id": 2,
        #     "tradeCoinId": 1,
        #     "tradeCoinName": "BTC",
        #     "tradeDecimal": 3,
        #     "priceDecimal": 1,
        #     "settleDecimal": 6,
        #     "settleCoinId": 4,
        #     "settleCoinName": "USD",
        #     "swapCoinId": 1,
        #     "swapCoinName": null,
        #     "symbol": "BTC-USD",
        #     "classifyId": null,
        #     "categoryId": null,
        #     "visible": 0,
        #     "tradable": True,
        #     "status": null,
        #     "sort": null,
        #     "isDual": False,
        #     "faceMultiplier": "1",
        #     "isDelivery": False,
        #     "deliveryTime": null,
        #     "deliveryMarketPrice": null,
        #     "deliveryStatus": null,
        #     "takerTradeFeeRate": "0.02",
        #     "makerTradeFeeRate": "0",
        #     "pair": "BTC-USD",
        #     "minCount": "0.001",
        #     "maxCount": "1000000",
        #     "brandExchange": null,
        #     "platform": null,
        #     "preMarket": null,
        #     "initMarkPrice": null,
        #     "releaseTime": null,
        #     "createTime": null
        # }
        #
        marketId = self.safe_string(ticker, 'symbol')
        market = self.safe_market(marketId, market, '-')
        last = self.safe_string_2(ticker, 'price', 'lastTradePrice')
        timestamp = self.safe_integer_product(ticker, 'createTime', 0.000001)
        return self.safe_ticker({
            'symbol': market['symbol'],
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': self.safe_string(ticker, 'highPrice'),
            'low': self.safe_string(ticker, 'lowPrice'),
            'bid': self.safe_string(ticker, 'bestBidPrice'),
            'bidVolume': self.safe_string(ticker, 'bestBidSize'),
            'ask': self.safe_string(ticker, 'bestAskPrice'),
            'askVolume': self.safe_string(ticker, 'bestAskSize'),
            'vwap': None,
            'open': None,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': self.safe_string(ticker, 'priceChg'),
            'percentage': self.safe_string(ticker, 'priceChgPct'),
            'average': None,
            'baseVolume': self.safe_string(ticker, 'volumeOf24h'),
            'quoteVolume': self.safe_string(ticker, 'turnoverOf24h'),
            'markPrice': self.safe_string_2(ticker, 'markPrice', 'data'),
            'indexPrice': self.safe_string(ticker, 'indexPrice'),
            'info': ticker,
        }, 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://www.astros.com/docs/rest/futures-trading/market-data/get-transaction-history

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'pairName': market['id'],
        }
        if limit is not None:
            request['limit'] = min(limit, 1000)
        response = self.publicGetInfoTrades(self.extend(request, params))
        # {
        #     "error": False,
        #     "code": 200,
        #     "msg": "SUCCESS",
        #     "data": [
        #         {
        #             "contractMatchPairId": 4739473,
        #             "contractPairId": 2,
        #             "pair": null,
        #             "price": "106035.8",
        #             "quantity": "0.313",
        #             "amount": "33189.2054",
        #             "isLong": True,
        #             "time": "03:46:53",
        #             "timestamp": 1748576813000
        #         }
        #     ],
        #     "sid": "1833515680823721985"
        # }
        trades = self.safe_list(response, 'data', [])
        return self.parse_trades(trades, market, since, limit)

    def parse_trade(self, trade: dict, market: Market = None) -> Trade:
        # fetchMyTrades
        # {
        #     "id": 19862817,
        #     "entrustId": 180577696,
        #     "contractPositionId": 0,
        #     "contractPairId": 1,
        #     "createTime": "2024-09-09 07:08:26",
        #     "createTimeStamp": 1725865706000,
        #     "symbol": "ETH-USD",
        #     "accountCoinSymbol": null,
        #     "accountSettleDecimal": null,
        #     "lever": null,
        #     "isMarket": True,
        #     "isClose": False,
        #     "isLong": True,
        #     "isTaker": True,
        #     "averagePrice": "2315.09",
        #     "quantity": "0.02",
        #     "amount": "46.3018",
        #     "tradeFee": "0.027781",
        #     "positionFee": null,
        #     "profitLoss": "0",
        #     "isDelivery": null,
        #     "deliveryTime": null,
        #     "deliveryTimeStamp": null,
        #     "address": null,
        #     "openingPrice": null,
        #     "type": null,
        #     "restrictPrice": null
        # }
        #
        # fetchTrades(public)
        #
        # {
        #     "contractMatchPairId": 4739473,
        #     "contractPairId": 2,
        #     "pair": null,
        #     "price": "106035.8",
        #     "quantity": "0.313",
        #     "amount": "33189.2054",
        #     "isLong": True,
        #     "time": "03:46:53",
        #     "timestamp": 1748576813000
        # }
        marketId = self.safe_string(trade, 'symbol')
        market = self.safe_market(marketId, market, '-')
        id = self.safe_string_2(trade, 'contractMatchPairId', 'id')
        amountString = self.safe_string_n(trade, ['size', 'amount', 'quantity'])
        orderId = self.safe_string(trade, 'entrustId')
        takerOrMaker = self.parse_taker_or_maker(self.safe_bool(trade, 'isTaker'))
        timestamp = self.safe_integer(trade, 'createTimeStamp')
        typeRaw = self.safe_integer_2(trade, 'type', 'orderType')
        type = self.parse_order_type_for_trade(typeRaw)
        priceString = self.safe_string_n(trade, ['price', 'dealPrice', 'averagePrice'])
        return self.safe_trade({
            'info': trade,
            'id': id,
            'order': orderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': market['symbol'],
            'type': type,
            'takerOrMaker': takerOrMaker,
            'side': self.parse_order_side(self.safe_bool(trade, 'isLong')),
            'price': priceString,
            'amount': amountString,
            'cost': self.safe_string(trade, 'amount'),
            'fee': {
                'currency': None,
                'cost': self.safe_string(trade, 'tradeFee'),
                'rate': None,
            },
        }, market)

    def parse_side(self, side):
        sides: dict = {
            'SHORT': 'sell',
            'LONG': 'buy',
        }
        return self.safe_string(sides, side, side)

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

        https://www.astros.com/docs/rest/futures-trading/funding-fees/get-current-funding-rate

        :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>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = self.publicGetV1MarketFundingCurrent(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #            "symbol": ".ETHUSDTMFPI8H",
        #            "granularity": 28800000,
        #            "timePoint": 1637380800000,
        #            "value": 0.0001,
        #            "predictedValue": 0.0001,
        #        },
        #    }
        #
        data = self.safe_dict(response, 'data', {})
        # the website displayes the previous funding rate as "funding rate"
        return self.parse_funding_rate(data, market)

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

        https://www.astros.com/docs/rest/futures-trading/funding-fees/get-current-funding-rate

        :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>`
        """
        return self.fetch_funding_rate(symbol, params)

    def parse_funding_rate(self, data, market: Market = None) -> FundingRate:
        #
        #     {
        #         "symbol": ".ETHUSDTMFPI8H",
        #         "granularity": 28800000,
        #         "timePoint": 1637380800000,
        #         "value": 0.0001,
        #         "predictedValue": 0.0001,
        #     }
        #
        fundingTimestamp = self.safe_integer(data, 'timePoint')
        marketId = self.safe_string(data, 'symbol')
        return {
            'info': data,
            'symbol': self.safe_symbol(marketId, market, None, 'contract'),
            'markPrice': None,
            'indexPrice': None,
            'interestRate': None,
            'estimatedSettlePrice': None,
            'timestamp': None,
            'datetime': None,
            'fundingRate': self.safe_number(data, 'value'),
            'fundingTimestamp': fundingTimestamp,
            'fundingDatetime': self.iso8601(fundingTimestamp),
            'nextFundingRate': self.safe_number(data, 'predictedValue'),
            'nextFundingTimestamp': None,
            'nextFundingDatetime': None,
            'previousFundingRate': None,
            'previousFundingTimestamp': None,
            'previousFundingDatetime': None,
            'interval': self.parse_funding_interval(self.safe_string(data, 'granularity')),
        }

    def parse_funding_interval(self, interval):
        intervals: dict = {
            '3600000': '1h',
            '14400000': '4h',
            '28800000': '8h',
            '57600000': '16h',
            '86400000': '24h',
        }
        return self.safe_string(intervals, interval, interval)

    def fetch_funding_rate_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """

        https://www.astros.com/docs/rest/futures-trading/funding-fees/get-public-funding-history#request-url

        fetches historical funding rate prices
        :param str symbol: unified symbol of the market to fetch the funding rate history for
        :param int [since]: not used by kucuoinfutures
        :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]: end time in ms
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchFundingRateHistory() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
            'from': 0,
            'to': self.milliseconds(),
        }
        until = self.safe_integer(params, 'until')
        params = self.omit(params, ['until'])
        if since is not None:
            request['from'] = since
            if until is None:
                request['to'] = since + 1000 * 8 * 60 * 60 * 100
        if until is not None:
            request['to'] = until
            if since is None:
                request['to'] = until - 1000 * 8 * 60 * 60 * 100
        response = self.publicGetV1MarketFundingHistory(self.extend(request, params))
        #
        #     {
        #         "code": "200000",
        #         "data": [
        #             {
        #                 "symbol": "IDUSDTM",
        #                 "fundingRate": 2.26E-4,
        #                 "timepoint": 1702296000000
        #             }
        #         ]
        #     }
        #
        data = self.safe_value(response, 'data')
        return self.parse_funding_rate_histories(data, market, since, limit)

    def parse_funding_rate_history(self, info, market: Market = None):
        timestamp = self.safe_integer(info, 'timepoint')
        marketId = self.safe_string(info, 'symbol')
        return {
            'info': info,
            'symbol': self.safe_symbol(marketId, market),
            'fundingRate': self.safe_number(info, 'fundingRate'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
        }

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

        https://www.astros.com/docs/rest/funding/funding-overview/get-account-detail-futures

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        """
        self.load_markets()
        # only fetches one balance at a time
        defaultCode = self.safe_string(self.options, 'code')
        fetchBalanceOptions = self.safe_value(self.options, 'fetchBalance', {})
        defaultCode = self.safe_string(fetchBalanceOptions, 'code', defaultCode)
        code = self.safe_string(params, 'code', defaultCode)
        request: dict = {
            'symbol': code,
            'timestamp': self.milliseconds(),
        }
        response = self.privatePostHotOrderBalance(self.extend(request))
        # {
        #     "error": False,
        #     "code": 200,
        #     "msg": "SUCCESS",
        #     "data": {
        #         "userId": 2372,
        #         "coinId": 4,
        #         "availableAmount": "5923162.009578",
        #         "frozenAmount": "3882121.614357",
        #         "symbol": "USD"
        #     },
        #     "sid": "1748585753652-001-49e0"
        # }
        return self.parse_balance(response)

    def parse_balance(self, response) -> Balances:
        result: dict = {
            'info': response,
            'timestamp': None,
            'datetime': None,
        }
        data = self.safe_value(response, 'data')
        currencyId = self.safe_string(data, 'symbol')
        code = self.safe_currency_code(currencyId)
        account = self.account()
        account['free'] = self.safe_string(data, 'availableAmount')
        account['used'] = self.safe_string(data, 'frozenAmount')
        account['total'] = Precise.string_add(account['free'], account['used'])
        result[code] = account
        return self.safe_balance(result)

    def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
        """
        Create an order on the exchange

        https://www.astros.com/docs/rest/futures-trading/orders/place-order
        https://www.astros.com/docs/rest/futures-trading/orders/place-take-profit-and-stop-loss-order#http-request

        :param str symbol: Unified CCXT market symbol
        :param str type: 'limit' or 'market'
        :param str side: 'buy' or 'sell'
        :param float amount: the amount of currency to trade
        :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]:  extra parameters specific to the exchange API endpoint
        :param dict [params.takeProfit]: *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered and the triggerPriceType
        :param dict [params.stopLoss]: *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered and the triggerPriceType
        :param float [params.triggerPrice]: The price a trigger order is triggered at
        :param float [params.stopLossPrice]: price to trigger stop-loss orders
        :param float [params.takeProfitPrice]: price to trigger take-profit orders
        :param bool [params.reduceOnly]: A mark to reduce the position size only. Set to False by default. Need to set the position size when reduceOnly is True.
        :param str [params.timeInForce]: GTC, GTT, IOC, or FOK, default is GTC, limit orders only
        :param str [params.postOnly]: Post only flag, invalid when timeInForce is IOC or FOK
        :param float [params.cost]: the cost of the order in units of USDT
        :param str [params.marginMode]: 'cross' or 'isolated', default is 'isolated'
 ----------------- Exchange Specific Parameters -----------------
        :param float [params.leverage]: Leverage size of the order(mandatory param in request, default is 1)
        :param str [params.clientOid]: client order id, defaults to uuid if not passed
        :param str [params.remark]: remark for the order, length cannot exceed 100 utf8 characters
        :param str [params.stop]: 'up' or 'down', the direction the triggerPrice is triggered from, requires triggerPrice. down: Triggers when the price reaches or goes below the triggerPrice. up: Triggers when the price reaches or goes above the triggerPrice.
        :param str [params.triggerPriceType]: "last", "mark", "index" - defaults to "mark"
        :param str [params.stopPriceType]: exchange-specific alternative for triggerPriceType: TP, IP or MP
        :param bool [params.closeOrder]: set to True to close position
        :param bool [params.test]: set to True to use the test order endpoint(does not submit order, use to validate params)
        :param bool [params.forceHold]: A mark to forcely hold the funds for an order, even though it's an order to reduce the position size. This helps the order stay on the order book and not get canceled when the position size changes. Set to False by default.
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        params = self.omit(params, 'test')
        orderRequest = self.create_contract_order_request(symbol, type, side, amount, price, params)
        response = None
        response = self.privatePostHotOrderCreate(orderRequest)
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #            "orderId": "619717484f1d010001510cde",
        #        },
        #    }
        #
        data = self.safe_dict(response, 'data', {})
        return self.parse_order(data, market)

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

        https://www.astros.com/docs/rest/futures-trading/orders/place-multiple-orders

        :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 = []
        for i in range(0, len(orders)):
            rawOrder = orders[i]
            symbol = self.safe_string(rawOrder, 'symbol')
            market = self.market(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_value(rawOrder, 'params', {})
            orderRequest = self.create_contract_order_request(market['id'], type, side, amount, price, orderParams)
            ordersRequests.append(orderRequest)
        response = self.privatePostHotOrderBatchCreate(ordersRequests)
        #
        #     {
        #         "code": "200000",
        #         "data": [
        #             {
        #                 "orderId": "135241412609331200",
        #                 "clientOid": "3d8fcc13-0b13-447f-ad30-4b3441e05213",
        #                 "symbol": "LTCUSDTM",
        #                 "code": "200000",
        #                 "msg": "success"
        #             },
        #             {
        #                 "orderId": "135241412747743234",
        #                 "clientOid": "b878c7ee-ae3e-4d63-a20b-038acbb7306f",
        #                 "symbol": "LTCUSDTM",
        #                 "code": "200000",
        #                 "msg": "success"
        #             }
        #         ]
        #     }
        #
        data = self.safe_list(response, 'data', [])
        return self.parse_orders(data)

    def create_contract_order_request(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
        market = self.market(symbol)
        # required param, cannot be used twice
        clientOrderId = self.safe_string_2(params, 'clientOid', 'clientOrderId', self.uuid())
        params = self.omit(params, ['clientOid', 'clientOrderId'])
        request: dict = {
            'clientOid': clientOrderId,
            'side': side,
            'symbol': market['id'],
            'type': type,  # limit or market
            'leverage': 1,
        }
        marginModeUpper = self.safe_string_upper(params, 'marginMode')
        if marginModeUpper is not None:
            params = self.omit(params, 'marginMode')
            request['marginMode'] = marginModeUpper
        cost = self.safe_string(params, 'cost')
        params = self.omit(params, 'cost')
        if cost is not None:
            request['valueQty'] = self.cost_to_precision(symbol, cost)
        else:
            if amount < 1:
                raise InvalidOrder(self.id + ' createOrder() minimum contract order amount is 1')
            request['size'] = int(self.amount_to_precision(symbol, amount))
        triggerPrice, stopLossPrice, takeProfitPrice = self.handle_trigger_prices(params)
        stopLoss = self.safe_dict(params, 'stopLoss')
        takeProfit = self.safe_dict(params, 'takeProfit')
        # isTpAndSl = stopLossPrice and takeProfitPrice
        triggerPriceTypes: dict = {
            'mark': 'MP',
            'last': 'TP',
            'index': 'IP',
        }
        triggerPriceType = self.safe_string(params, 'triggerPriceType', 'mark')
        triggerPriceTypeValue = self.safe_string(triggerPriceTypes, triggerPriceType, triggerPriceType)
        params = self.omit(params, ['stopLossPrice', 'takeProfitPrice', 'triggerPrice', 'stopPrice', 'takeProfit', 'stopLoss'])
        if triggerPrice:
            request['stop'] = 'up' if (side == 'buy') else 'down'
            request['stopPrice'] = self.price_to_precision(symbol, triggerPrice)
            request['stopPriceType'] = triggerPriceTypeValue
        elif stopLoss is not None or takeProfit is not None:
            priceType = triggerPriceTypeValue
            if stopLoss is not None:
                slPrice = self.safe_string_2(stopLoss, 'triggerPrice', 'stopPrice')
                request['triggerStopDownPrice'] = self.price_to_precision(symbol, slPrice)
                priceType = self.safe_string(stopLoss, 'triggerPriceType', 'mark')
                priceType = self.safe_string(triggerPriceTypes, priceType, priceType)
            if takeProfit is not None:
                tpPrice = self.safe_string_2(takeProfit, 'triggerPrice', 'takeProfitPrice')
                request['triggerStopUpPrice'] = self.price_to_precision(symbol, tpPrice)
                priceType = self.safe_string(takeProfit, 'triggerPriceType', 'mark')
                priceType = self.safe_string(triggerPriceTypes, priceType, priceType)
            request['stopPriceType'] = priceType
        elif stopLossPrice or takeProfitPrice:
            if stopLossPrice:
                request['stop'] = 'up' if (side == 'buy') else 'down'
                request['stopPrice'] = self.price_to_precision(symbol, stopLossPrice)
            else:
                request['stop'] = 'down' if (side == 'buy') else 'up'
                request['stopPrice'] = self.price_to_precision(symbol, takeProfitPrice)
            request['reduceOnly'] = True
            request['stopPriceType'] = triggerPriceTypeValue
        uppercaseType = type.upper()
        timeInForce = self.safe_string_upper(params, 'timeInForce')
        if uppercaseType == 'LIMIT':
            if price is None:
                raise ArgumentsRequired(self.id + ' createOrder() requires a price argument for limit orders')
            else:
                request['price'] = self.price_to_precision(symbol, price)
            if timeInForce is not None:
                request['timeInForce'] = timeInForce
        postOnly = None
        postOnly, params = self.handle_post_only(type == 'market', False, params)
        if postOnly:
            request['postOnly'] = True
        hidden = self.safe_value(params, 'hidden')
        if postOnly and (hidden is not None):
            raise BadRequest(self.id + ' createOrder() does not support the postOnly parameter together with a hidden parameter')
        iceberg = self.safe_value(params, 'iceberg')
        if iceberg:
            visibleSize = self.safe_value(params, 'visibleSize')
            if visibleSize is None:
                raise ArgumentsRequired(self.id + ' createOrder() requires a visibleSize parameter for iceberg orders')
        params = self.omit(params, ['timeInForce', 'stopPrice', 'triggerPrice', 'stopLossPrice', 'takeProfitPrice'])  # Time in force only valid for limit orders, exchange error when gtc for market orders
        return self.extend(request, params)

    def handle_trigger_prices(self, params):
        triggerPrice = self.safe_value_2(params, 'triggerPrice', 'stopPrice')
        stopLossPrice = self.safe_value(params, 'stopLossPrice')
        takeProfitPrice = self.safe_value(params, 'takeProfitPrice')
        isStopLoss = stopLossPrice is not None
        isTakeProfit = takeProfitPrice is not None
        if (isStopLoss and isTakeProfit) or (triggerPrice and stopLossPrice) or (triggerPrice and isTakeProfit):
            raise ExchangeError(self.id + ' createOrder() - you should use either triggerPrice or stopLossPrice or takeProfitPrice')
        return [triggerPrice, stopLossPrice, takeProfitPrice]

    def close_position(self, symbol: str, side: OrderSide = None, params={}) -> Order:
        """
        closes open positions for a market

        https://www.astros.com/docs/rest/futures-trading/orders/place-order

        :param str symbol: Unified CCXT market symbol
        :param str side: not used by astros closePositions
        :param dict [params]: extra parameters specific to the okx api endpoint
        :param str [params.clientOrderId]: client order id of the order
        :returns dict[]: `A list of position structures <https://docs.ccxt.com/#/?id=position-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        clientOrderId = self.safe_string(params, 'clientOrderId')
        params = self.omit(params, ['test', 'clientOrderId'])
        if clientOrderId is None:
            clientOrderId = self.number_to_string(self.nonce())
        request: dict = {
            'symbol': market['id'],
            'closeOrder': True,
            'clientOid': clientOrderId,
            'type': 'market',
        }
        response = None
        response = self.privatePostHotOrderCloseOrder(self.extend(request, params))
        return self.parse_order(response, market)

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

        https://www.astros.com/docs/rest/futures-trading/orders/cancel-futures-order-by-orderid

        :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
        :param str [params.clientOrderId]: cancel order by client order id
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        clientOrderId = self.safe_string_2(params, 'clientOid', 'clientOrderId')
        params = self.omit(params, ['clientOrderId'])
        request: dict = {}
        response = None
        if clientOrderId is not None:
            if symbol is None:
                raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument when cancelling by clientOrderId')
            market = self.market(symbol)
            request['symbol'] = market['id']
            request['clientOid'] = clientOrderId
            response = self.privatePostOrderCancelEntrustByCli(self.extend(request, params))
        else:
            request['orderId'] = id
            response = self.privatePostOrderCancelEntrust(self.extend(request, params))
        #
        #   {
        #       "code": "200000",
        #       "data": {
        #           "cancelledOrderIds": [
        #                "619714b8b6353000014c505a",
        #           ],
        #       },
        #   }
        #
        return self.safe_value(response, 'data')

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

        https://www.astros.com/docs/rest/futures-trading/orders/batch-cancel-orders

        :param str[] ids: order ids
        :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.clientOrderIds]: client order ids
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        market = None
        if symbol is not None:
            market = self.market(symbol)
        ordersRequests = []
        clientOrderIds = self.safe_list_2(params, 'clientOrderIds', 'clientOids', [])
        params = self.omit(params, ['clientOrderIds', 'clientOids'])
        useClientorderId = False
        for i in range(0, len(clientOrderIds)):
            useClientorderId = True
            if symbol is None:
                raise ArgumentsRequired(self.id + ' cancelOrders() requires a symbol argument when cancelling by clientOrderIds')
            ordersRequests.append({
                'symbol': market['id'],
                'clientOid': self.safe_string(clientOrderIds, i),
            })
        for i in range(0, len(ids)):
            ordersRequests.append(ids[i])
        requestKey = 'clientOidsList' if useClientorderId else 'orderIdsList'
        request: dict = {}
        request[requestKey] = ordersRequests
        response = self.privatePostOrderBatchCancelEntrust(self.extend(request, params))
        #
        #   {
        #       "code": "200000",
        #       "data":
        #       [
        #           {
        #               "orderId": "80465574458560512",
        #               "clientOid": null,
        #               "code": "200",
        #               "msg": "success"
        #           },
        #           {
        #               "orderId": "80465575289094144",
        #               "clientOid": null,
        #               "code": "200",
        #               "msg": "success"
        #           }
        #       ]
        #   }
        #
        orders = self.safe_list(response, 'data', [])
        return self.parse_orders(orders, market)

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

        https://www.astros.com/docs/rest/futures-trading/orders/cancel-multiple-futures-limit-orders
        https://www.astros.com/docs/rest/futures-trading/orders/cancel-multiple-futures-stop-orders

        :param str symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param dict [params.trigger]: When True, all the trigger orders will be cancelled
        :returns: Response from the exchange
        """
        self.load_markets()
        request: dict = {}
        if symbol is not None:
            request['symbol'] = self.market_id(symbol)
        params = self.omit(params, ['stop', 'trigger'])
        response = None
        response = self.privatePostOrderBatchCancelEntrust(self.extend(request, params))
        #
        #   {
        #       "code": "200000",
        #       "data": {
        #           "cancelledOrderIds": [
        #                "619714b8b6353000014c505a",
        #           ],
        #       },
        #   }
        #
        return self.safe_value(response, 'data')

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

        https://www.astros.com/docs/rest/futures-trading/positions/add-margin-manually

        :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>`
        """
        self.load_markets()
        market = self.market(symbol)
        uuid = self.uuid()
        request: dict = {
            'symbol': market['id'],
            'margin': self.amount_to_precision(symbol, amount),
            'bizNo': uuid,
        }
        response = self.privatePostOrderCallMarginAmount(self.extend(request, params))
        #
        #    {
        #        "code": "200000",
        #        "data": {
        #            "id": "62311d26064e8f00013f2c6d",
        #            "symbol": "XRPUSDTM",
        #            "autoDeposit": False,
        #            "maintMarginReq": 0.01,
        #            "riskLimit": 200000,
        #            "realLeverage": 0.88,
        #            "crossMode": False,
        #            "delevPercentage": 0.4,
        #            "openingTimestamp": 1647385894798,
        #            "currentTimestamp": 1647414510672,
        #            "currentQty": -1,
        #            "currentCost": -7.658,
        #            "currentComm": 0.0053561,
        #            "unrealisedCost": -7.658,
        #            "realisedGrossCost": 0,
        #            "realisedCost": 0.0053561,
        #            "isOpen": True,
        #            "markPrice": 0.7635,
        #            "markValue": -7.635,
        #            "posCost": -7.658,
        #            "posCross": 1.00016084,
        #            "posInit": 7.658,
        #            "posComm": 0.00979006,
        #            "posLoss": 0,
        #            "posMargin": 8.6679509,
        #            "posMaint": 0.08637006,
        #            "maintMargin": 8.6909509,
        #            "realisedGrossPnl": 0,
        #            "realisedPnl": -0.0038335,
        #            "unrealisedPnl": 0.023,
        #            "unrealisedPnlPcnt": 0.003,
        #            "unrealisedRoePcnt": 0.003,
        #            "avgEntryPrice": 0.7658,
        #            "liquidationPrice": 1.6239,
        #            "bankruptPrice": 1.6317,
        #            "settleCurrency": "USDT"
        #        }
        #    }
        #
        #
        #    {
        #        "code":"200000",
        #        "msg":"Position does not exist"
        #    }
        #
        data = self.safe_value(response, 'data')
        return self.extend(self.parse_margin_modification(data, market), {
            'amount': self.amount_to_precision(symbol, amount),
            'direction': 'in',
        })

    def parse_margin_modification(self, info, market: Market = None) -> MarginModification:
        #
        #    {
        #        "id": "62311d26064e8f00013f2c6d",
        #        "symbol": "XRPUSDTM",
        #        "autoDeposit": False,
        #        "maintMarginReq": 0.01,
        #        "riskLimit": 200000,
        #        "realLeverage": 0.88,
        #        "crossMode": False,
        #        "delevPercentage": 0.4,
        #        "openingTimestamp": 1647385894798,
        #        "currentTimestamp": 1647414510672,
        #        "currentQty": -1,
        #        "currentCost": -7.658,
        #        "currentComm": 0.0053561,
        #        "unrealisedCost": -7.658,
        #        "realisedGrossCost": 0,
        #        "realisedCost": 0.0053561,
        #        "isOpen": True,
        #        "markPrice": 0.7635,
        #        "markValue": -7.635,
        #        "posCost": -7.658,
        #        "posCross": 1.00016084,
        #        "posInit": 7.658,
        #        "posComm": 0.00979006,
        #        "posLoss": 0,
        #        "posMargin": 8.6679509,
        #        "posMaint": 0.08637006,
        #        "maintMargin": 8.6909509,
        #        "realisedGrossPnl": 0,
        #        "realisedPnl": -0.0038335,
        #        "unrealisedPnl": 0.023,
        #        "unrealisedPnlPcnt": 0.003,
        #        "unrealisedRoePcnt": 0.003,
        #        "avgEntryPrice": 0.7658,
        #        "liquidationPrice": 1.6239,
        #        "bankruptPrice": 1.6317,
        #        "settleCurrency": "USDT"
        #    }
        #
        #    {
        #        "code":"200000",
        #        "msg":"Position does not exist"
        #    }
        #
        id = self.safe_string(info, 'id')
        market = self.safe_market(id, market)
        currencyId = self.safe_string(info, 'settleCurrency')
        crossMode = self.safe_value(info, 'crossMode')
        mode = 'cross' if crossMode else 'isolated'
        marketId = self.safe_string(market, 'symbol')
        timestamp = self.safe_integer(info, 'currentTimestamp')
        return {
            'info': info,
            'symbol': self.safe_symbol(marketId, market),
            'type': None,
            'marginMode': mode,
            'amount': None,
            'total': None,
            'code': self.safe_currency_code(currencyId),
            'status': None,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
        }

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

        https://docs.astros.com/futures/#get-order-list
        https://docs.astros.com/futures/#get-untriggered-stop-order-list

        :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]: end time in ms
        :param str [params.side]: buy or sell
        :param str [params.type]: limit, or market
        :param boolean [params.trigger]: set to True to retrieve untriggered stop orders
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        paginate = False
        paginate, params = self.handle_option_and_params(params, 'fetchOpenOrders', 'paginate')
        if paginate:
            return self.fetch_paginated_call_dynamic('fetchOpenOrders', symbol, since, limit, params)
        return self.privatePostOrderSelectContractCurrentEntrustList(params)

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

        https://docs.astros.com/futures/#get-position-list

        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        """
        self.load_markets()
        if symbols is None:
            return []
        symbol = None
        if isinstance(symbols, list):
            symbolsLength = len(symbols)
            if symbolsLength > 1:
                raise BadRequest(self.id + ' fetchPositions() symbols argument cannot contain more than 1 symbol')
            symbol = symbols[0]
        else:
            symbol = symbols
        market = self.market(symbol)
        request: dict = {}
        request['pairName'] = market['symbol']
        response = self.privatePostHotOrderSelectContractPositionList(self.extend(request, params))
        # {
        #     "error": False,
        #     "code": 200,
        #     "msg": "SUCCESS",
        #     "data": [
        #         {
        #             "id": 4796701,
        #             "positionType": 3,
        #             "entrustId": 178754443,
        #             "contractPairId": 1,
        #             "symbol": "ETH-USD",
        #             "isDual": null,
        #             "faceMultiplier": null,
        #             "accountCoinId": null,
        #             "accountCoinSymbol": null,
        #             "accountSettleDecimal": null,
        #             "tradeCoinDecimal": null,
        #             "isLong": True,
        #             "openingPrice": "2300.045",
        #             "quantity": "0.06",
        #             "closingQuantity": "0",
        #             "remainingCloseQuantity": "0.06",
        #             "amount": "138.0027",
        #             "marginCallAmount": "7.5",
        #             "tariffAmount": "-0.179974",
        #             "lever": 20,
        #             "marginAmount": "47.390168",
        #             "restrictPrice": "1547.709113",
        #             "unrealizedPnl": null,
        #             "realizedPnl": null,
        #             "profitType": 0,
        #             "profitPrice": "0",
        #             "lossType": 0,
        #             "lossPrice": "0",
        #             "lights": 5,
        #             "status": 1,
        #             "createTime": "2024-09-07 07:18:13",
        #             "createTimeStamp": null,
        #             "isDelivery": null,
        #             "deliveryTime": null,
        #             "deliveryTimeStamp": null,
        #             "settleShowDecimal": null,
        #             "tradeCoinIcon": null,
        #             "settleCoinIcon": null
        #         }
        #     ],
        #     "sid": "1809704168838144001"
        # }
        data = self.safe_list(response, 'data')
        return self.parse_positions(data, symbols)

    def parse_position(self, position: dict, market: Market = None):
        # {
        #     "id": 4796701,
        #     "positionType": 3,
        #     "entrustId": 178754443,
        #     "contractPairId": 1,
        #     "symbol": "ETH-USD",
        #     "isDual": null,
        #     "faceMultiplier": null,
        #     "accountCoinId": null,
        #     "accountCoinSymbol": null,
        #     "accountSettleDecimal": null,
        #     "tradeCoinDecimal": null,
        #     "isLong": True,
        #     "openingPrice": "2300.045",
        #     "quantity": "0.06",
        #     "closingQuantity": "0",
        #     "remainingCloseQuantity": "0.06",
        #     "amount": "138.0027",
        #     "marginCallAmount": "7.5",
        #     "tariffAmount": "-0.179974",
        #     "lever": 20,
        #     "marginAmount": "47.390168",
        #     "restrictPrice": "1547.709113",
        #     "unrealizedPnl": null,
        #     "realizedPnl": null,
        #     "profitType": 0,
        #     "profitPrice": "0",
        #     "lossType": 0,
        #     "lossPrice": "0",
        #     "lights": 5,
        #     "status": 1,
        #     "createTime": "2024-09-07 07:18:13",
        #     "createTimeStamp": null,
        #     "isDelivery": null,
        #     "deliveryTime": null,
        #     "deliveryTimeStamp": null,
        #     "settleShowDecimal": null,
        #     "tradeCoinIcon": null,
        #     "settleCoinIcon": null
        # }
        symbol = self.safe_string(position, 'symbol')
        market = self.safe_market(symbol, market)
        timestamp = self.safe_integer(position, 'createTimeStamp')
        marginModeId = self.safe_integer(position, 'positionType')
        openingPrice = self.safe_number(position, 'openingPrice')
        marginMode = self.get_supported_mapping(marginModeId, {
            '4': 'cross',
            '3': 'isolated',
        })
        liquidationPrice = self.safe_string(position, 'restrictPrice')
        initialMargin = self.safe_string(position, 'marginAmount')
        contractSize = None
        if market is not None:
            contractSize = market['contractSize']
        direction = self.safe_string(position, 'direction')
        side = self.parse_direction_side(direction)
        size = self.safe_string(position, 'quantity')
        unrealisedPnl = self.safe_string(position, 'unrealizedPnl')
        profitType = self.safe_integer(position, 'profitType')
        profitPrice = None
        if profitType == 1:
            profitPrice = self.safe_string(position, 'profitPrice')
        lossType = self.safe_integer(position, 'lossType')
        lossPrice = None
        if lossType == 1:
            lossPrice = self.safe_string(position, 'lossPrice')
        return self.safe_position({
            'info': position,
            'id': self.safe_string(position, 'id'),
            'symbol': self.safe_string(market, 'symbol'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastUpdateTimestamp': None,
            'initialMargin': self.parse_number(initialMargin),
            'initialMarginPercentage': None,
            'maintenanceMargin': None,
            'maintenanceMarginPercentage': None,
            'entryPrice': openingPrice,
            'notional': None,
            'leverage': self.safe_number(position, 'lever'),
            'unrealizedPnl': self.parse_number(unrealisedPnl),
            'contracts': self.parse_number(Precise.string_abs(size)),
            'contractSize': contractSize,
            'realizedPnl': self.safe_number(position, 'realizedPnl'),
            'marginRatio': None,
            'liquidationPrice': liquidationPrice,
            'markPrice': None,
            'lastPrice': None,
            'collateral': None,
            'marginMode': marginMode,
            'side': side,
            'percentage': None,
            'stopLossPrice': lossPrice,
            'takeProfitPrice': profitPrice,
        })

    def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """

        https://docs.astros.com/futures/#get-fills

        fetch all trades made by the user
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: End time in ms
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        """
        self.load_markets()
        paginate = False
        paginate, params = self.handle_option_and_params(params, 'fetchMyTrades', 'paginate')
        if paginate:
            return self.fetch_paginated_call_dynamic('fetchMyTrades', symbol, since, limit, params)
        request: dict = {}
        if since is not None:
            request['pageNo'] = since
        if limit is not None:
            request['pageSize'] = limit
        response = self.privatePostOrderSelectContractMatchPairList(self.extend(request, params))
        # {
        #     "error": False,
        #     "code": 200,
        #     "msg": "SUCCESS",
        #     "data": [
        #         {
        #             "id": 19862817,
        #             "entrustId": 180577696,
        #             "contractPositionId": 0,
        #             "contractPairId": 1,
        #             "createTime": "2024-09-09 07:08:26",
        #             "createTimeStamp": 1725865706000,
        #             "symbol": "ETH-USD",
        #             "accountCoinSymbol": null,
        #             "accountSettleDecimal": null,
        #             "lever": null,
        #             "isMarket": True,
        #             "isClose": False,
        #             "isLong": True,
        #             "isTaker": True,
        #             "averagePrice": "2315.09",
        #             "quantity": "0.02",
        #             "amount": "46.3018",
        #             "tradeFee": "0.027781",
        #             "positionFee": null,
        #             "profitLoss": "0",
        #             "isDelivery": null,
        #             "deliveryTime": null,
        #             "deliveryTimeStamp": null,
        #             "address": null,
        #             "openingPrice": null,
        #             "type": null,
        #             "restrictPrice": null
        #         }
        #     ],
        #     "sid": "1809703947882209281"
        # }
        trades = self.safe_list(response, 'data', [])
        return self.parse_trades(trades, None, since, limit)

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        endpoint = '/' + self.implode_params(path, params)
        query = self.omit(params, self.extract_params(path))
        headers = headers if (headers is not None) else {}
        headers['Content-Type'] = 'application/x-www-form-urlencoded'
        url = self.urls['api'][api]
        if not self.is_empty(query):
            if url.find('/batch') >= 0:
                body = self.json(query)
                headers['Content-Type'] = 'application/json'
            else:
                endpoint += '?' + self.rawencode(query)
        url = url + endpoint
        isPrivate = (api == 'private')
        if isPrivate:
            self.check_required_credentials()
            headers = self.extend({
                'APIKEY': self.apiKey,
            }, headers)
            sortedQuery = self.keysort(query)
            auth = self.rawencode(sortedQuery)
            signature = self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha256)
            headers['signature'] = signature
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, code: int, reason: str, url: str, method: str, headers: dict, body: str, response, requestHeaders, requestBody):
        if not response:
            self.throw_broadly_matched_exception(self.exceptions['broad'], body, body)
            return None
        #
        # bad
        #     {"code": "400100", "msg": "validation.createOrder.clientOidIsRequired"}
        # good
        #     {code: '200000', data: {...}}
        #
        errorCode = self.safe_string(response, 'code')
        message = self.safe_string_2(response, 'msg', 'data', '')
        feedback = self.id + ' ' + body
        self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
        self.throw_exactly_matched_exception(self.exceptions['exact'], errorCode, feedback)
        self.throw_broadly_matched_exception(self.exceptions['broad'], body, feedback)
        if errorCode != '200000' and errorCode != '200':
            raise ExchangeError(feedback)
        return None

    def parse_order(self, order: dict, market: Market = None) -> Order:
        # fetchOpenOrders
        # {
        #     "id": 65818921,
        #     "contractPairId": 1,
        #     "symbol": "ETH-USD",
        #     "isDual": null,
        #     "faceMultiplier": null,
        #     "accountCoinId": null,
        #     "accountCoinSymbol": null,
        #     "isMarket": False,
        #     "isClose": False,
        #     "isLong": True,
        #     "price": "2001",
        #     "quantity": "0.02",
        #     "amount": "40.02",
        #     "depositAmount": "2.009004",
        #     "lever": 20,
        #     "positionType": 3,
        #     "dealQuantity": "0",
        #     "dealAmount": "0",
        #     "contractPositionId": 0,
        #     "triggerType": 0,
        #     "triggerPrice": null,
        #     "matchType": 1,
        #     "createTime": "2024-05-06 09:04:00",
        #     "createTimeStamp": null,
        #     "isDelivery": null,
        #     "deliveryTime": null,
        #     "deliveryTimeStamp": null,
        #     "activatePrice": null,
        #     "callbackRate": null,
        #     "clientOrderId": "1714986239498"
        # }
        timestamp = self.safe_integer(order, 'createTimeStamp')
        symbol = self.safe_string(order, 'symbol')
        filled = self.safe_string(order, 'dealQuantity')
        quantity = self.safe_string(order, 'quantity')
        status = self.parse_order_status(None)
        isMarket = self.safe_bool(order, 'isMarket')
        type = self.parse_order_type(isMarket)
        isLong = self.safe_bool(order, 'isLong')
        side = self.parse_order_side(isLong)
        symbolRaw = self.safe_string(order, 'symbol')
        if market is None:
            market = self.market(symbolRaw)
        price = self.safe_string(order, 'price')
        remaining = Precise.string_sub(quantity, filled)
        if status != 'CANCELED':
            remaining = str(0)
        amount = self.safe_string(order, 'quantity', Precise.string_add(filled, remaining))
        cost = Precise.string_mul(price, amount)
        # if type == 'market':
        #     price = None
        # }
        clientOrderId = self.safe_string(order, 'clientOrderId')
        matchType = self.safe_integer(order, 'matchType')
        timeInForce = self.parse_time_in_force(matchType)
        postOnly = False
        if timeInForce == 'PO':
            postOnly = True
        return self.safe_order({
            'info': order,
            'id': self.safe_string(order, 'id'),
            'clientOrderId': clientOrderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'lastUpdateTimestamp': None,
            'symbol': symbol,
            'type': type,
            'timeInForce': timeInForce,
            'postOnly': postOnly,
            'reduceOnly': None,
            'side': side,
            'price': price,
            'triggerPrice': self.safe_string(order, 'triggerPrice'),
            'amount': amount,
            'cost': cost,
            'average': None,
            'filled': filled,
            'remaining': None,
            'status': status,
            'fee': None,
            'trades': None,
        }, market)

    def parse_order_side(self, isLong: bool):
        if isLong:
            return 'buy'
        return 'sell'

    def parse_time_in_force(self, matchType: float):
        # 1.GTC 2.IOC 3.FOK 4.POST_ONLY
        timeInForces: dict = {
            '1': 'GTC',
            '2': 'IOC',
            '3': 'FOK',
            '4': 'PO',
        }
        return self.safe_string(timeInForces, matchType, 'GTC')

    def parse_order_status(self, status: Str, dealQuantity: str, quantity: str):
        if status is None:
            return 'open'
        # NEW/ENTRUST/TRADE/CANCELED/UPDATED
        status_res = None
        if status == 'TRADE':
            status_res = 'open'
            if Precise.string_eq(dealQuantity, quantity):
                status_res = 'closed'
            return status_res
        statuses: dict = {
            'NEW': 'open',
            'ENTRUST': 'open',
            'UPDATED': 'open',
            'CANCELED': 'canceled',
        }
        return self.safe_string(statuses, status, status)

    def parse_order_type(self, isMarket: bool):
        if isMarket:
            return 'market'
        return 'limit'

    def parse_direction_side(self, direction: str):
        sides = {
            'LONG': 'buy',
            'SHORT': 'sell',
        }
        return self.safe_string(sides, direction, direction)

    def parse_taker_or_maker(self, isTaker: bool):
        if isTaker:
            return 'taker'
        return 'maker'

    def parse_order_type_for_trade(self, typeRaw: float):
        # 0.Limit 1.Market 2.Liquidation 3.Auto-Deleveraging
        type = {
            '0': 'limit',
            '1': 'market',
        }
        return self.safe_string(type, typeRaw)
