# -*- 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
import hashlib
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
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 NotSupported
from ccxt.base.errors import InvalidNonce
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class mexc3(Exchange):

    def describe(self):
        return self.deep_extend(super(mexc3, self).describe(), {
            'id': 'mexc3',
            'name': 'MEXC Global',
            'countries': ['SC'],  # Seychelles
            'rateLimit': 50,  # default rate limit is 20 times per second
            'version': 'v3',
            'has': {
                'CORS': None,
                'spot': True,
                'margin': True,
                'swap': True,
                'future': True,
                'option': None,
                'addMargin': True,
                'borrowMargin': True,
                'cancelAllOrders': True,
                'cancelOrder': True,
                'cancelOrders': None,
                'createDepositAddress': None,
                'createLimitOrder': None,
                'createMarketOrder': None,
                'createOrder': True,
                'createReduceOnlyOrder': True,
                'deposit': None,
                'editOrder': None,
                'fetchAccounts': True,
                'fetchBalance': True,
                'fetchBidsAsks': True,
                'fetchBorrowRate': None,
                'fetchBorrowRateHistory': None,
                'fetchBorrowRates': None,
                'fetchBorrowRatesPerSymbol': None,
                'fetchCanceledOrders': True,
                'fetchClosedOrder': None,
                'fetchClosedOrders': True,
                'fetchCurrencies': True,
                'fetchDeposit': None,
                'fetchDepositAddress': True,
                'fetchDepositAddresses': None,
                'fetchDepositAddressesByNetwork': True,
                'fetchDeposits': True,
                'fetchDepositWithdrawFee': 'emulated',
                'fetchDepositWithdrawFees': True,
                'fetchFundingHistory': True,
                'fetchFundingRate': True,
                'fetchFundingRateHistory': True,
                'fetchFundingRates': None,
                'fetchIndexOHLCV': True,
                'fetchL2OrderBook': True,
                'fetchLedger': None,
                'fetchLedgerEntry': None,
                'fetchLeverageTiers': True,
                'fetchMarginMode': False,
                'fetchMarketLeverageTiers': None,
                'fetchMarkets': True,
                'fetchMarkOHLCV': True,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenOrder': None,
                'fetchOpenOrders': True,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrderBooks': None,
                'fetchOrders': True,
                'fetchOrderTrades': True,
                'fetchPosition': True,
                'fetchPositionMode': True,
                'fetchPositions': True,
                'fetchPositionsRisk': None,
                'fetchPremiumIndexOHLCV': False,
                'fetchStatus': True,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTime': True,
                'fetchTrades': True,
                'fetchTradingFee': None,
                'fetchTradingFees': True,
                'fetchTradingLimits': None,
                'fetchTransactionFee': 'emulated',
                'fetchTransactionFees': True,
                'fetchTransactions': None,
                'fetchTransfer': True,
                'fetchTransfers': True,
                'fetchWithdrawal': None,
                'fetchWithdrawals': True,
                'reduceMargin': True,
                'repayMargin': True,
                'setLeverage': True,
                'setMarginMode': None,
                'setPositionMode': True,
                'signIn': None,
                'transfer': None,
                'withdraw': True,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/137283979-8b2a818d-8633-461b-bfca-de89e8c446b2.jpg',
                'api': {
                    'spot': {
                        'public': 'https://api.mexc.com',
                        'private': 'https://api.mexc.com',
                    },
                    'spot2': {
                        'public': 'https://www.mexc.com/open/api/v2',
                        'private': 'https://www.mexc.com/open/api/v2',
                    },
                    'contract': {
                        'public': 'https://contract.mexc.com/api/v1/contract',
                        'private': 'https://contract.mexc.com/api/v1/private',
                    },
                },
                'www': 'https://www.mexc.com/',
                'doc': [
                    'https://mxcdevelop.github.io/apidocs/spot_v3_en/',
                    'https://mxcdevelop.github.io/APIDoc/',  # v1 & v2 : soon to be deprecated
                ],
                'fees': [
                    'https://www.mexc.com/fee',
                ],
                'referral': 'https://m.mexc.com/auth/signup?inviteCode=1FQ1G',
            },
            'api': {
                'spot': {
                    'public': {
                        'get': {
                            'ping': 1,
                            'time': 1,
                            'exchangeInfo': 1,
                            'depth': 1,
                            'trades': 1,
                            'historicalTrades': 1,
                            'aggTrades': 1,
                            'klines': 1,
                            'avgPrice': 1,
                            'ticker/24hr': 1,
                            'ticker/price': 1,
                            'ticker/bookTicker': 1,
                            'etf/info': 1,
                        },
                    },
                    'private': {
                        'get': {
                            'order': 1,
                            'openOrders': 1,
                            'allOrders': 1,
                            'account': 1,
                            'myTrades': 1,
                            'sub-account/list': 1,
                            'sub-account/apiKey': 1,
                            'capital/config/getall': 1,
                            'capital/deposit/hisrec': 1,
                            'capital/withdraw/history': 1,
                            'capital/deposit/address': 1,
                            'capital/transfer': 1,
                            'capital/sub-account/universalTransfer': 1,
                            'capital/convert': 1,
                            'capital/convert/list': 1,
                            'margin/loan': 1,
                            'margin/allOrders': 1,
                            'margin/myTrades': 1,
                            'margin/openOrders': 1,
                            'margin/maxTransferable': 1,
                            'margin/priceIndex': 1,
                            'margin/order': 1,
                            'margin/isolated/account': 1,
                            'margin/maxBorrowable': 1,
                            'margin/repay': 1,
                            'margin/isolated/pair': 1,
                            'margin/forceLiquidationRec': 1,
                            'margin/isolatedMarginData': 1,
                            'margin/isolatedMarginTier': 1,
                            'rebate/taxQuery': 1,
                            'rebate/detail': 1,
                            'rebate/detail/kickback': 1,
                            'rebate/referCode': 1,
                            'mxDeduct/enable': 1,
                        },
                        'post': {
                            'order': 1,
                            'order/test': 1,
                            'sub-account/virtualSubAccount': 1,
                            'sub-account/apiKey': 1,
                            'sub-account/futures': 1,
                            'sub-account/margin': 1,
                            'batchOrders': 1,
                            'capital/withdraw/apply': 1,
                            'capital/transfer': 1,
                            'capital/deposit/address': 1,
                            'capital/sub-account/universalTransfer': 1,
                            'capital/convert': 1,
                            'margin/tradeMode': 1,
                            'margin/order': 1,
                            'margin/loan': 1,
                            'margin/repay': 1,
                            'mxDeduct/enable': 1,
                        },
                        'delete': {
                            'order': 1,
                            'openOrders': 1,
                            'sub-account/apiKey': 1,
                            'margin/order': 1,
                            'margin/openOrders': 1,
                        },
                    },
                },
                'contract': {
                    'public': {
                        'get': {
                            'ping': 2,
                            'detail': 2,
                            'support_currencies': 2,  # TODO: should we implement 'fetchCurrencies' solely for swap? because spot doesnt have it atm
                            'depth/{symbol}': 2,
                            'depth_commits/{symbol}/{limit}': 2,
                            'index_price/{symbol}': 2,
                            'fair_price/{symbol}': 2,
                            'funding_rate/{symbol}': 2,
                            'kline/{symbol}': 2,
                            'kline/index_price/{symbol}': 2,
                            'kline/fair_price/{symbol}': 2,
                            'deals/{symbol}': 2,
                            'ticker': 2,
                            'risk_reverse': 2,
                            'risk_reverse/history': 2,
                            'funding_rate/history': 2,
                        },
                    },
                    'private': {
                        'get': {
                            'account/assets': 2,
                            'account/asset/{currency}': 2,
                            'account/transfer_record': 2,
                            'position/list/history_positions': 2,
                            'position/open_positions': 2,
                            'position/funding_records': 2,
                            'position/position_mode': 2,
                            'order/list/open_orders/{symbol}': 2,
                            'order/list/history_orders': 2,
                            'order/external/{symbol}/{external_oid}': 2,
                            'order/get/{order_id}': 2,
                            'order/batch_query': 8,
                            'order/deal_details/{order_id}': 2,
                            'order/list/order_deals': 2,
                            'planorder/list/orders': 2,
                            'stoporder/list/orders': 2,
                            'stoporder/order_details/{stop_order_id}': 2,
                            'account/risk_limit': 2,  # TO_DO: gets max/min position size, allowed sides, leverage, maintenance margin, initial margin, etc...
                            'account/tiered_fee_rate': 2,  # TO_DO: taker/maker fees for account
                            'position/leverage': 2,
                        },
                        'post': {
                            'position/change_margin': 2,
                            'position/change_leverage': 2,
                            'position/change_position_mode': 2,
                            'order/submit': 2,
                            'order/submit_batch': 40,
                            'order/cancel': 2,
                            'order/cancel_with_external': 2,
                            'order/cancel_all': 2,
                            'account/change_risk_level': 2,
                            'planorder/place': 2,
                            'planorder/cancel': 2,
                            'planorder/cancel_all': 2,
                            'stoporder/cancel': 2,
                            'stoporder/cancel_all': 2,
                            'stoporder/change_price': 2,
                            'stoporder/change_plan_price': 2,
                        },
                    },
                },
                'spot2': {
                    'public': {
                        'get': {
                            'market/symbols': 1,
                            'market/coin/list': 2,
                            'common/timestamp': 1,
                            'common/ping': 1,
                            'market/ticker': 1,
                            'market/depth': 1,
                            'market/deals': 1,
                            'market/kline': 1,
                            'market/api_default_symbols': 2,
                        },
                    },
                    'private': {
                        'get': {
                            'account/info': 1,
                            'order/open_orders': 1,
                            'order/list': 1,
                            'order/query': 1,
                            'order/deals': 1,
                            'order/deal_detail': 1,
                            'asset/deposit/address/list': 2,
                            'asset/deposit/list': 2,
                            'asset/address/list': 2,
                            'asset/withdraw/list': 2,
                            'asset/internal/transfer/record': 10,
                            'account/balance': 10,
                            'asset/internal/transfer/info': 10,
                            'market/api_symbols': 2,
                        },
                        'post': {
                            'order/place': 1,
                            'order/place_batch': 1,
                            'order/advanced/place_batch': 1,
                            'asset/withdraw': 2,
                            'asset/internal/transfer': 10,
                        },
                        'delete': {
                            'order/cancel': 1,
                            'order/cancel_by_symbol': 1,
                            'asset/withdraw': 2,
                        },
                    },
                },
            },
            'precisionMode': TICK_SIZE,
            'timeframes': {
                '1m': '1m',  # spot, swap
                '3m': '3m',  # spot
                '5m': '5m',  # spot, swap
                '15m': '15m',  # spot, swap
                '30m': '30m',  # spot, swap
                '1h': '1h',  # spot, swap
                '2h': '2h',  # spot
                '4h': '4h',  # spot, swap
                '6h': '6h',  # spot
                '8h': '8h',  # spot, swap
                '12h': '12h',  # spot
                '1d': '1d',  # spot, swap
                '3d': '3d',  # spot
                '1w': '1w',  # spot, swap
                '1M': '1M',  # spot, swap
            },
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'maker': self.parse_number('0.002'),  # maker / taker
                    'taker': self.parse_number('0.002'),
                },
            },
            'options': {
                'createMarketBuyOrderRequiresPrice': True,
                'unavailableContracts': {
                    'BTC/USDT:USDT': True,
                    'LTC/USDT:USDT': True,
                    'ETH/USDT:USDT': True,
                },
                'fetchMarkets': {
                    'types': {
                        'spot': True,
                        'future': {
                            'linear': False,
                            'inverse': False,
                        },
                        'swap': {
                            'linear': True,
                            'inverse': False,
                        },
                    },
                },
                'timeframes': {
                    'spot': {
                        '1m': '1m',
                        '3m': '3m',
                        '5m': '5m',
                        '15m': '15m',
                        '30m': '30m',
                        '1h': '1h',
                        '2h': '2h',
                        '4h': '4h',
                        '6h': '6h',
                        '8h': '8h',
                        '12h': '12h',
                        '1d': '1d',
                        '3d': '3d',
                        '1w': '1w',
                        '1M': '1M',
                    },
                    'swap': {
                        '1m': 'Min1',
                        '5m': 'Min5',
                        '15m': 'Min15',
                        '30m': 'Min30',
                        '1h': 'Min60',
                        '4h': 'Hour4',
                        '8h': 'Hour8',
                        '1d': 'Day1',
                        '1w': 'Week1',
                        '1M': 'Month1',
                    },
                },
                'defaultType': 'spot',  # spot, swap
                'networks': {
                    'TRX': 'TRC20',
                    'ETH': 'ERC20',
                    'BEP20': 'BEP20(BSC)',
                    'BSC': 'BEP20(BSC)',
                },
                'networksById': {
                    'BEP20(BSC)': 'BSC',
                },
                'networkAliases': {
                    'BSC(BEP20)': 'BSC',
                },
                'recvWindow': 5 * 1000,  # 5 sec, default
                'maxTimeTillEnd': 90 * 86400 * 1000 - 1,  # 90 days
                'broker': 'CCXT',
            },
            'commonCurrencies': {
                'BEYONDPROTOCOL': 'BEYOND',
                'BIFI': 'BIFIF',
                'BYN': 'BeyondFi',
                'COFI': 'COFIX',  # conflict with CoinFi
                'DFI': 'DfiStarter',
                'DFT': 'dFuture',
                'DRK': 'DRK',
                'EGC': 'Egoras Credit',
                'FLUX1': 'FLUX',  # switched places
                'FLUX': 'FLUX1',  # switched places
                'FREE': 'FreeRossDAO',  # conflict with FREE Coin
                'GMT': 'GMT Token',  # Conflict with GMT(STEPN)
                'STEPN': 'GMT',  # Conflict with GMT Token
                'HERO': 'Step Hero',  # conflict with Metahero
                'MIMO': 'Mimosa',
                'PROS': 'Pros.Finance',  # conflict with Prosper
                'SIN': 'Sin City Token',
                'SOUL': 'Soul Swap',
            },
            'exceptions': {
                'exact': {
                    # until mexc migrates fully to v3, it might be worth to note the version & market aside errors, not easily remove obsolete version's exceptions in future
                    '-1128': BadRequest,
                    '-2011': BadRequest,
                    '-1121': BadSymbol,
                    '10101': InsufficientFunds,  # {"msg":"资金不足","code":10101}
                    '2009': InvalidOrder,  # {"success":false,"code":2009,"message":"Position is not exists or closed."}
                    '2011': BadRequest,
                    '30004': InsufficientFunds,
                    '33333': BadRequest,  # {"msg":"Not support transfer","code":33333}
                    '44444': BadRequest,
                    '1002': InvalidOrder,
                    '30019': BadRequest,
                    '30005': InvalidOrder,
                    '2003': InvalidOrder,
                    '2005': InsufficientFunds,
                    '600': BadRequest,
                    '70011': PermissionDenied,  # {"code":70011,"msg":"Pair user ban trade apikey."}
                    '88004': InsufficientFunds,  # {"msg":"超出最大可借，最大可借币为:18.09833211","code":88004}
                    '88009': ExchangeError,  # v3 {"msg":"Loan record does not exist","code":88009}
                    '88013': InvalidOrder,  # {"msg":"最小交易额不能小于：5USDT","code":88013}
                    '88015': InsufficientFunds,  # {"msg":"持仓不足","code":88015}
                    '700003': InvalidNonce,  # {"code":700003,"msg":"Timestamp for self request is outside of the recvWindow."}
                    '26': ExchangeError,  # operation not allowed
                    '602': AuthenticationError,  # Signature verification failed
                    '10001': AuthenticationError,  # user does not exist
                    '10007': BadRequest,  # bad symbol
                    '10015': BadRequest,  # user id cannot be null
                    '10072': BadRequest,  # invalid access key
                    '10073': BadRequest,  # invalid Request-Time
                    '10095': InvalidOrder,  # amount cannot be null
                    '10096': InvalidOrder,  # amount decimal places is too long
                    '10097': InvalidOrder,  # amount is error
                    '10098': InvalidOrder,  # risk control system detected abnormal
                    '10099': BadRequest,  # user sub account does not open
                    '10100': BadRequest,  # self currency transfer is not supported
                    '10102': InvalidOrder,  # amount cannot be zero or negative
                    '10103': ExchangeError,  # self account transfer is not supported
                    '10200': BadRequest,  # transfer operation processing
                    '10201': BadRequest,  # transfer in failed
                    '10202': BadRequest,  # transfer out failed
                    '10206': BadRequest,  # transfer is disabled
                    '10211': BadRequest,  # transfer is forbidden
                    '10212': BadRequest,  # This withdrawal address is not on the commonly used address list or has been invalidated
                    '10216': ExchangeError,  # no address available. Please try again later
                    '10219': ExchangeError,  # asset flow writing failed please try again
                    '10222': BadRequest,  # currency cannot be null
                    '10232': BadRequest,  # currency does not exist
                    '10259': ExchangeError,  # Intermediate account does not configured in redisredis
                    '10265': ExchangeError,  # Due to risk control, withdrawal is unavailable, please try again later
                    '10268': BadRequest,  # remark length is too long
                    '20001': ExchangeError,  # subsystem is not supported
                    '20002': ExchangeError,  # Internal system error please contact support
                    '22222': BadRequest,  # record does not exist
                    '30000': ExchangeError,  # suspended transaction for the symbol
                    '30001': InvalidOrder,  # The current transaction direction is not allowed to place an order
                    '30002': InvalidOrder,  # The minimum transaction volume cannot be less than :
                    '30003': InvalidOrder,  # The maximum transaction volume cannot be greater than :
                    '30010': InvalidOrder,  # no valid trade price
                    '30014': InvalidOrder,  # invalid symbol
                    '30016': InvalidOrder,  # trading disabled
                    '30018': InvalidOrder,  # market order is disabled
                    '30020': AuthenticationError,  # no permission for the symbol
                    '30021': BadRequest,  # invalid symbol
                    '30025': InvalidOrder,  # no exist opponent order
                    '30026': BadRequest,  # invalid order ids
                    '30027': InvalidOrder,  # The currency has reached the maximum position limit, the buying is suspended
                    '30028': InvalidOrder,  # The currency triggered the platform risk control, the selling is suspended
                    '30029': InvalidOrder,  # Cannot exceed the maximum order limit
                    '30032': InvalidOrder,  # Cannot exceed the maximum position
                    '30041': InvalidOrder,  # current order type can not place order
                    '60005': ExchangeError,  # your account is abnormal
                    '700001': BadRequest,  # API-key format invalid
                    '700002': AuthenticationError,  # Signature for self request is not valid
                    '700004': BadRequest,  # Param 'origClientOrderId' or 'orderId' must be sent, but both were empty/null
                    '700005': InvalidNonce,  # recvWindow must less than 60000
                    '700006': BadRequest,  # IP non white list
                    '700007': AuthenticationError,  # No permission to access the endpoint
                    '700008': BadRequest,  # Illegal characters found in parameter
                    '730001': BadRequest,  # Pair not found
                    '730002': BadRequest,  # Your input param is invalid
                    '730000': ExchangeError,  # Request failed, please contact the customer service
                    '730003': ExchangeError,  # Unsupported operation, please contact the customer service
                    '730100': ExchangeError,  # Unusual user status
                    '730600': BadRequest,  # Sub-account Name cannot be null
                    '730601': BadRequest,  # Sub-account Name must be a combination of 8-32 letters and numbers
                    '730602': BadRequest,  # Sub-account remarks cannot be null
                    '730700': BadRequest,  # API KEY remarks cannot be null
                    '730701': BadRequest,  # API KEY permission cannot be null
                    '730702': BadRequest,  # API KEY permission does not exist
                    '730703': BadRequest,  # The IP information is incorrect, and a maximum of 10 IPs are allowed to be bound only
                    '730704': BadRequest,  # The bound IP format is incorrect, please refill
                    '730705': BadRequest,  # At most 30 groups of Api Keys are allowed to be created only
                    '730706': BadRequest,  # API KEY information does not exist
                    '730707': BadRequest,  # accessKey cannot be null
                    '730101': BadRequest,  # The user Name already exists
                    '140001': BadRequest,  # sub account does not exist
                    '140002': AuthenticationError,  # sub account is forbidden
                },
                'broad': {
                    'Order quantity error, please try to modify.': BadRequest,  # code:2011
                    'Combination of optional parameters invalid': BadRequest,  # code:-2011
                    'api market order is disabled': BadRequest,  #
                    'Contract not allow place order!': InvalidOrder,  # code:1002
                    'Oversold': InvalidOrder,  # code:30005
                    'Insufficient position': InsufficientFunds,  # code:30004
                    'Insufficient balance!': InsufficientFunds,  # code:2005
                    'Bid price is great than max allow price': InvalidOrder,  # code:2003
                    'Invalid symbol.': BadSymbol,  # code:-1121
                    'Param error!': BadRequest,  # code:600
                },
            },
        })

    def fetch_status(self, params={}):
        """
        the latest known information on the availability of the exchange API
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/en/latest/manual.html#exchange-status-structure>`
        """
        marketType, query = self.handle_market_type_and_params('fetchStatus', None, params)
        response = None
        status = None
        updated = None
        if marketType == 'spot':
            response = self.spotPublicGetPing(query)
            #
            #     {}
            #
            status = self.json(response) if response else 'ok'
        elif marketType == 'swap':
            response = self.contractPublicGetPing(query)
            #
            #     {"success":true,"code":"0","data":"1648124374985"}
            #
            status = 'ok' if self.safe_value(response, 'success') else self.json(response)
            updated = self.safe_integer(response, 'data')
        return {
            'status': status,
            'updated': updated,
            'url': None,
            'eta': None,
            'info': response,
        }

    def fetch_time(self, params={}):
        """
        fetches the current integer timestamp in milliseconds from the exchange server
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        """
        marketType, query = self.handle_market_type_and_params('fetchTime', None, params)
        response = None
        if marketType == 'spot':
            response = self.spotPublicGetTime(query)
            #
            #     {"serverTime": "1647519277579"}
            #
            return self.safe_integer(response, 'serverTime')
        elif marketType == 'swap':
            response = self.contractPublicGetPing(query)
            #
            #     {"success":true,"code":"0","data":"1648124374985"}
            #
            return self.safe_integer(response, 'data')

    def fetch_currencies(self, params={}):
        """
        fetches all available currencies on an exchange
        see https://mxcdevelop.github.io/apidocs/spot_v3_en/#query-the-currency-information
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: an associative dictionary of currencies
        """
        # self endpoint requires authentication
        # while fetchCurrencies is a public API method by design
        # therefore we check the keys here
        # and fallback to generating the currencies from the markets
        if not self.check_required_credentials(False):
            return None
        response = self.spotPrivateGetCapitalConfigGetall(params)
        #
        # {
        #     coin: 'QANX',
        #     name: 'QANplatform',
        #     networkList: [
        #       {
        #         coin: 'QANX',
        #         depositDesc: null,
        #         depositEnable: True,
        #         minConfirm: '0',
        #         name: 'QANplatform',
        #         network: 'BEP20(BSC)',
        #         withdrawEnable: False,
        #         withdrawFee: '42.000000000000000000',
        #         withdrawIntegerMultiple: null,
        #         withdrawMax: '24000000.000000000000000000',
        #         withdrawMin: '20.000000000000000000',
        #         sameAddress: False,
        #         contract: '0xAAA7A10a8ee237ea61E8AC46C50A8Db8bCC1baaa'
        #       },
        #       {
        #         coin: 'QANX',
        #         depositDesc: null,
        #         depositEnable: True,
        #         minConfirm: '0',
        #         name: 'QANplatform',
        #         network: 'ERC20',
        #         withdrawEnable: True,
        #         withdrawFee: '2732.000000000000000000',
        #         withdrawIntegerMultiple: null,
        #         withdrawMax: '24000000.000000000000000000',
        #         withdrawMin: '240.000000000000000000',
        #         sameAddress: False,
        #         contract: '0xAAA7A10a8ee237ea61E8AC46C50A8Db8bCC1baaa'
        #       }
        #     ]
        #   }
        #
        result = {}
        for i in range(0, len(response)):
            currency = response[i]
            id = self.safe_string(currency, 'coin')
            code = self.safe_currency_code(id)
            name = self.safe_string(currency, 'name')
            currencyActive = False
            currencyFee = None
            currencyWithdrawMin = None
            currencyWithdrawMax = None
            depositEnabled = False
            withdrawEnabled = False
            networks = {}
            chains = self.safe_value(currency, 'networkList', [])
            for j in range(0, len(chains)):
                chain = chains[j]
                networkId = self.safe_string(chain, 'network')
                network = self.safe_network(networkId)
                isDepositEnabled = self.safe_value(chain, 'depositEnable', False)
                isWithdrawEnabled = self.safe_value(chain, 'withdrawEnable', False)
                active = (isDepositEnabled and isWithdrawEnabled)
                currencyActive = active or currencyActive
                withdrawMin = self.safe_string(chain, 'withdrawMin')
                withdrawMax = self.safe_string(chain, 'withdrawMax')
                currencyWithdrawMin = withdrawMin if (currencyWithdrawMin is None) else currencyWithdrawMin
                currencyWithdrawMax = withdrawMax if (currencyWithdrawMax is None) else currencyWithdrawMax
                fee = self.safe_number(chain, 'withdrawFee')
                currencyFee = fee if (currencyFee is None) else currencyFee
                if Precise.string_gt(currencyWithdrawMin, withdrawMin):
                    currencyWithdrawMin = withdrawMin
                if Precise.string_lt(currencyWithdrawMax, withdrawMax):
                    currencyWithdrawMax = withdrawMax
                if isDepositEnabled:
                    depositEnabled = True
                if isWithdrawEnabled:
                    withdrawEnabled = True
                networks[network] = {
                    'info': chain,
                    'id': networkId,
                    'network': network,
                    'active': active,
                    'deposit': isDepositEnabled,
                    'withdraw': isWithdrawEnabled,
                    'fee': fee,
                    'precision': None,
                    'limits': {
                        'withdraw': {
                            'min': withdrawMin,
                            'max': withdrawMax,
                        },
                    },
                }
            networkKeys = list(networks.keys())
            networkKeysLength = len(networkKeys)
            if (networkKeysLength == 1) or ('NONE' in networks):
                defaultNetwork = self.safe_value_2(networks, 'NONE', networkKeysLength - 1)
                if defaultNetwork is not None:
                    currencyFee = defaultNetwork['fee']
            result[code] = {
                'info': currency,
                'id': id,
                'code': code,
                'name': name,
                'active': currencyActive,
                'deposit': depositEnabled,
                'withdraw': withdrawEnabled,
                'fee': currencyFee,
                'precision': None,
                'limits': {
                    'amount': {
                        'min': None,
                        'max': None,
                    },
                    'withdraw': {
                        'min': currencyWithdrawMin,
                        'max': currencyWithdrawMax,
                    },
                },
                'networks': networks,
            }
        return result

    def safe_network(self, networkId):
        if networkId.find('BSC') >= 0:
            return 'BEP20'
        parts = networkId.split(' ')
        networkId = ''.join(parts)
        networkId = networkId.replace('-20', '20')
        networksById = {
            'ETH': 'ETH',
            'ERC20': 'ERC20',
            'BEP20(BSC)': 'BEP20',
            'TRX': 'TRC20',
        }
        return self.safe_string(networksById, networkId, networkId)

    def fetch_markets(self, params={}):
        """
        retrieves data on all markets for mexc3
        :param dict params: extra parameters specific to the exchange api endpoint
        :returns [dict]: an array of objects representing market data
        """
        spotMarket = self.fetch_spot_markets(params)
        swapMarket = self.fetch_swap_markets(params)
        return self.array_concat(spotMarket, swapMarket)

    def fetch_spot_markets(self, params={}):
        response = self.spotPublicGetExchangeInfo(params)
        #
        #     {
        #         "timezone": "CST",
        #         "serverTime": 1647521860402,
        #         "rateLimits": [],
        #         "exchangeFilters": [],
        #         "symbols": [
        #           {
        #                "symbol": "OGNUSDT",
        #                "status": "ENABLED",
        #                "baseAsset": "OGN",
        #                "baseAssetPrecision": "2",
        #                "quoteAsset": "USDT",
        #                "quoteAssetPrecision": "4",
        #                "orderTypes": [
        #                    "LIMIT",
        #                    "LIMIT_MAKER"
        #                ],
        #                "baseCommissionPrecision": "2",
        #                "quoteCommissionPrecision": "4",
        #                "quoteOrderQtyMarketAllowed": False,
        #                "isSpotTradingAllowed": True,
        #                "isMarginTradingAllowed": True,
        #                "permissions": [
        #                    "SPOT",
        #                    "MARGIN"
        #                ],
        #                "filters": [],
        #                "baseSizePrecision": "0.01",  # self turned out to be a minimum base amount for order
        #                "maxQuoteAmount": "5000000",
        #                "makerCommission": "0.002",
        #                "takerCommission": "0.002"
        #                "quoteAmountPrecision": "5",  # self turned out to be a minimum cost amount for order
        #                "quotePrecision": "4",  # deprecated in favor of 'quoteAssetPrecision'( https://dev.binance.vision/t/what-is-the-difference-between-quoteprecision-and-quoteassetprecision/4333 )
        #                # note, "icebergAllowed" & "ocoAllowed" fields were recently removed
        #            },
        #         ]
        #     }
        #
        # Notes:
        # - 'quoteAssetPrecision' & 'baseAssetPrecision' are not currency's real blockchain precision(to view currency's actual individual precision, refer to fetchCurrencies() method).
        #
        data = self.safe_value(response, 'symbols', [])
        result = []
        for i in range(0, len(data)):
            market = data[i]
            id = self.safe_string(market, 'symbol')
            baseId = self.safe_string(market, 'baseAsset')
            quoteId = self.safe_string(market, 'quoteAsset')
            base = self.safe_currency_code(baseId)
            quote = self.safe_currency_code(quoteId)
            status = self.safe_string(market, 'status')
            isSpotTradingAllowed = self.safe_value(market, 'isSpotTradingAllowed')
            active = False
            if (status == 'ENABLED') and (isSpotTradingAllowed):
                active = True
            isMarginTradingAllowed = self.safe_value(market, 'isMarginTradingAllowed')
            makerCommission = self.safe_number(market, 'makerCommission')
            takerCommission = self.safe_number(market, 'takerCommission')
            maxQuoteAmount = self.safe_number(market, 'maxQuoteAmount')
            result.append({
                'id': id,
                'symbol': base + '/' + quote,
                'base': base,
                'quote': quote,
                'settle': None,
                'baseId': baseId,
                'quoteId': quoteId,
                'settleId': None,
                'type': 'spot',
                'spot': True,
                'margin': isMarginTradingAllowed,
                'swap': False,
                'future': False,
                'option': False,
                'active': active,
                'contract': False,
                'linear': None,
                'inverse': None,
                'taker': takerCommission,
                'maker': makerCommission,
                'contractSize': None,
                'expiry': None,
                'expiryDatetime': None,
                'strike': None,
                'optionType': None,
                'precision': {
                    'amount': self.parse_number(self.parse_precision(self.safe_string(market, 'baseAssetPrecision'))),
                    'price': self.parse_number(self.parse_precision(self.safe_string(market, 'quoteAssetPrecision'))),
                },
                'limits': {
                    'leverage': {
                        'min': None,
                        'max': None,
                    },
                    'amount': {
                        'min': self.safe_number(market, 'baseSizePrecision'),
                        'max': None,
                    },
                    'price': {
                        'min': None,
                        'max': None,
                    },
                    'cost': {
                        'min': self.safe_number(market, 'quoteAmountPrecision'),
                        'max': maxQuoteAmount,
                    },
                },
                'info': market,
            })
        return result

    def fetch_swap_markets(self, params={}):
        response = self.contractPublicGetDetail(params)
        #
        #     {
        #         "success":true,
        #         "code":0,
        #         "data":[
        #             {
        #                 "symbol":"BTC_USDT",
        #                 "displayName":"BTC_USDT永续",
        #                 "displayNameEn":"BTC_USDT SWAP",
        #                 "positionOpenType":3,
        #                 "baseCoin":"BTC",
        #                 "quoteCoin":"USDT",
        #                 "settleCoin":"USDT",
        #                 "contractSize":0.0001,
        #                 "minLeverage":1,
        #                 "maxLeverage":125,
        #                 "priceScale":2,  # seems useless atm, as it's just how UI shows the price, i.e. 29583.50 for BTC/USDT:USDT, while price ticksize is 0.5
        #                 "volScale":0,  # probably: contract amount precision
        #                 "amountScale":4,  # probably: quote currency precision
        #                 "priceUnit":0.5,  # price tick size
        #                 "volUnit":1,  # probably: contract tick size
        #                 "minVol":1,
        #                 "maxVol":1000000,
        #                 "bidLimitPriceRate":0.1,
        #                 "askLimitPriceRate":0.1,
        #                 "takerFeeRate":0.0006,
        #                 "makerFeeRate":0.0002,
        #                 "maintenanceMarginRate":0.004,
        #                 "initialMarginRate":0.008,
        #                 "riskBaseVol":10000,
        #                 "riskIncrVol":200000,
        #                 "riskIncrMmr":0.004,
        #                 "riskIncrImr":0.004,
        #                 "riskLevelLimit":5,
        #                 "priceCoefficientVariation":0.1,
        #                 "indexOrigin":["BINANCE","GATEIO","HUOBI","MXC"],
        #                 "state":0,  # 0 enabled, 1 delivery, 2 completed, 3 offline, 4 pause
        #                 "isNew":false,
        #                 "isHot":true,
        #                 "isHidden":false
        #             },
        #         ]
        #     }
        #
        data = self.safe_value(response, 'data', [])
        result = []
        for i in range(0, len(data)):
            market = data[i]
            id = self.safe_string(market, 'symbol')
            baseId = self.safe_string(market, 'baseCoin')
            quoteId = self.safe_string(market, 'quoteCoin')
            settleId = self.safe_string(market, 'settleCoin')
            base = self.safe_currency_code(baseId)
            quote = self.safe_currency_code(quoteId)
            settle = self.safe_currency_code(settleId)
            state = self.safe_string(market, 'state')
            result.append({
                'id': id,
                'symbol': base + '/' + quote + ':' + settle,
                'base': base,
                'quote': quote,
                'settle': settle,
                'baseId': baseId,
                'quoteId': quoteId,
                'settleId': settleId,
                'type': 'swap',
                'spot': False,
                'margin': False,
                'swap': True,
                'future': False,
                'option': False,
                'active': (state == '0'),
                'contract': True,
                'linear': True,
                'inverse': False,
                'taker': self.safe_number(market, 'takerFeeRate'),
                'maker': self.safe_number(market, 'makerFeeRate'),
                'contractSize': self.safe_number(market, 'contractSize'),
                'expiry': None,
                'expiryDatetime': None,
                'strike': None,
                'optionType': None,
                'precision': {
                    'amount': self.safe_number(market, 'volUnit'),
                    'price': self.safe_number(market, 'priceUnit'),
                },
                'limits': {
                    'leverage': {
                        'min': self.safe_number(market, 'minLeverage'),
                        'max': self.safe_number(market, 'maxLeverage'),
                    },
                    'amount': {
                        'min': self.safe_number(market, 'minVol'),
                        'max': self.safe_number(market, 'maxVol'),
                    },
                    'price': {
                        'min': None,
                        'max': None,
                    },
                    'cost': {
                        'min': None,
                        'max': None,
                    },
                },
                'info': market,
            })
        return result

    def fetch_order_book(self, symbol, limit=None, params={}):
        """
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str symbol: unified symbol of the market to fetch the order book for
        :param int|None limit: the maximum amount of order book entries to return
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbols
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit
        orderbook = None
        if market['spot']:
            response = self.spotPublicGetDepth(self.extend(request, params))
            #
            #     {
            #         "lastUpdateId": "744267132",
            #         "bids": [
            #             ["40838.50","0.387864"],
            #             ["40837.95","0.008400"],
            #         ],
            #         "asks": [
            #             ["40838.61","6.544908"],
            #             ["40838.88","0.498000"],
            #         ]
            #     }
            #
            orderbook = self.parse_order_book(response, symbol)
            orderbook['nonce'] = self.safe_integer(response, 'lastUpdateId')
        elif market['swap']:
            response = self.contractPublicGetDepthSymbol(self.extend(request, params))
            #
            #     {
            #         "success":true,
            #         "code":0,
            #         "data":{
            #             "asks":[
            #                 [3445.72,48379,1],
            #                 [3445.75,34994,1],
            #             ],
            #             "bids":[
            #                 [3445.55,44081,1],
            #                 [3445.51,24857,1],
            #             ],
            #             "version":2827730444,
            #             "timestamp":1634117846232
            #         }
            #     }
            #
            data = self.safe_value(response, 'data')
            timestamp = self.safe_integer(data, 'timestamp')
            orderbook = self.parse_order_book(data, symbol, timestamp)
            orderbook['nonce'] = self.safe_integer(data, 'version')
        return orderbook

    def fetch_trades(self, symbol, since=None, limit=None, params={}):
        """
        get the list of most recent trades for a particular symbol
        :param str symbol: unified symbol of the market to fetch trades for
        :param int|None since: timestamp in ms of the earliest trade to fetch
        :param int|None limit: the maximum amount of trades to fetch
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html?#public-trades>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit
        # if since is not None:
        #     request['startTime'] = since; bug in api, waiting for fix
        # }
        trades = None
        if market['spot']:
            method = self.safe_string(self.options, 'fetchTradesMethod', 'spotPublicGetAggTrades')
            method = self.safe_string(params, 'method', method)  # AggTrades, HistoricalTrades, Trades
            trades = getattr(self, method)(self.extend(request, params))
            #
            #     /trades, /historicalTrades
            #
            #     [
            #         {
            #             "id": null,
            #             "price": "40798.94",
            #             "qty": "0.000508",
            #             "quoteQty": "20.72586152",
            #             "time": "1647546934374",
            #             "isBuyerMaker": True,
            #             "isBestMatch": True
            #         },
            #     ]
            #
            #     /aggrTrades
            #
            #     [
            #         {
            #           "a": null,
            #           "f": null,
            #           "l": null,
            #           "p": "40679",
            #           "q": "0.001309",
            #           "T": 1647551328000,
            #           "m": True,
            #           "M": True
            #         },
            #     ]
            #
        elif market['swap']:
            response = self.contractPublicGetDealsSymbol(self.extend(request, params))
            #
            #     {
            #         "success": True,
            #         "code": 0,
            #         "data": [
            #             {
            #                 "p": 31199,
            #                 "v": 18,
            #                 "T": 1,
            #                 "O": 3,
            #                 "M": 2,
            #                 "t": 1609831235985
            #             },
            #         ]
            #     }
            #
            trades = self.safe_value(response, 'data')
        return self.parse_trades(trades, market, since, limit)

    def parse_trade(self, trade, market=None):
        id = None
        timestamp = None
        orderId = None
        symbol = None
        fee = None
        type = None
        side = None
        takerOrMaker = None
        priceString = None
        amountString = None
        costString = None
        # if swap
        if 'v' in trade:
            #
            # swap: fetchTrades
            #
            #     {
            #         "p": 31199,
            #         "v": 18,
            #         "T": 1,
            #         "O": 3,
            #         "M": 2,
            #         "t": 1609831235985
            #     }
            #
            timestamp = self.safe_integer(trade, 't')
            market = self.safe_market(None, market)
            symbol = market['symbol']
            priceString = self.safe_string(trade, 'p')
            amountString = self.safe_string(trade, 'v')
            side = self.parse_order_side(self.safe_string(trade, 'T'))
            takerOrMaker = 'taker'
        else:
            #
            # spot: fetchTrades(for aggTrades)
            #
            #         {
            #             "a": null,
            #             "f": null,
            #             "l": null,
            #             "p": "40679",
            #             "q": "0.001309",
            #             "T": 1647551328000,
            #             "m": True,
            #             "M": True
            #         }
            #
            # spot: fetchMyTrades, fetchOrderTrades
            #
            #         {
            #             "symbol": "BTCUSDT",
            #             "id": "133948532984922113",
            #             "orderId": "133948532531949568",
            #             "orderListId": "-1",
            #             "price": "41995.51",
            #             "qty": "0.0002",
            #             "quoteQty": "8.399102",
            #             "commission": "0.016798204",
            #             "commissionAsset": "USDT",
            #             "time": "1647718055000",
            #             "isBuyer": True,
            #             "isMaker": False,
            #             "isBestMatch": True
            #         }
            #
            # swap: fetchMyTrades, fetchOrderTrades
            #
            #         {
            #             "id": "299444585",
            #             "symbol": "STEPN_USDT",
            #             "side": "1",
            #             "vol": "1",
            #             "price": "2.45455",
            #             "feeCurrency": "USDT",
            #             "fee": "0.00147273",
            #             "timestamp": "1648924557000",
            #             "profit": "0",
            #             "category": "1",
            #             "orderId": "265307163526610432",
            #             "positionMode": "1",
            #             "taker": True
            #         }
            #
            marketId = self.safe_string(trade, 'symbol')
            market = self.safe_market(marketId, market)
            symbol = market['symbol']
            id = self.safe_string_2(trade, 'id', 'a')
            priceString = self.safe_string_2(trade, 'price', 'p')
            orderId = self.safe_string(trade, 'orderId')
            # if swap
            if 'positionMode' in trade:
                timestamp = self.safe_integer(trade, 'timestamp')
                amountString = self.safe_string(trade, 'vol')
                side = self.parse_order_side(self.safe_string(trade, 'side'))
                fee = {
                    'cost': self.safe_string(trade, 'fee'),
                    'currency': self.safe_currency_code(self.safe_string(trade, 'feeCurrency')),
                }
                takerOrMaker = 'taker' if self.safe_value(trade, 'taker') else 'maker'
            else:
                timestamp = self.safe_integer_2(trade, 'time', 'T')
                amountString = self.safe_string_2(trade, 'qty', 'q')
                costString = self.safe_string(trade, 'quoteQty')
                isBuyer = self.safe_value(trade, 'isBuyer')
                isMaker = self.safe_value(trade, 'isMaker')
                buyerMaker = self.safe_string_2(trade, 'isBuyerMaker', 'm')
                if isMaker is not None:
                    takerOrMaker = 'maker' if isMaker else 'taker'
                if isBuyer is not None:
                    side = 'buy' if isBuyer else 'sell'
                if buyerMaker is not None:
                    side = 'sell' if buyerMaker else 'buy'
                    takerOrMaker = 'taker'
                feeAsset = self.safe_string(trade, 'commissionAsset')
                if feeAsset is not None:
                    fee = {
                        'cost': self.safe_string(trade, 'commission'),
                        'currency': self.safe_currency_code(feeAsset),
                    }
        if id is None:
            id = self.synthetic_trade_id(market, timestamp, side, amountString, priceString, type, takerOrMaker)
        return self.safe_trade({
            'id': id,
            'order': orderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': symbol,
            'type': type,
            'side': side,
            'takerOrMaker': takerOrMaker,
            'price': priceString,
            'amount': amountString,
            'cost': costString,
            'fee': fee,
            'info': trade,
        }, market)

    def synthetic_trade_id(self, market=None, timestamp=None, side=None, amount=None, price=None, orderType=None, takerOrMaker=None):
        # TODO: can be unified method? self approach is being used by multiple exchanges(mexc, woo-coinsbit, dydx, ...)
        id = ''
        if timestamp is not None:
            id = self.number_to_string(timestamp) + '-' + self.safe_string(market, 'id', '_')
            if side is not None:
                id += '-' + side
            if amount is not None:
                id += '-' + self.number_to_string(amount)
            if price is not None:
                id += '-' + self.number_to_string(price)
            if takerOrMaker is not None:
                id += '-' + takerOrMaker
            if orderType is not None:
                id += '-' + orderType
        return id

    def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
        """
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int|None since: timestamp in ms of the earliest candle to fetch
        :param int|None limit: the maximum amount of candles to fetch
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume
        """
        self.load_markets()
        market = self.market(symbol)
        options = self.safe_value(self.options, 'timeframes', {})
        timeframes = self.safe_value(options, market['type'], {})
        timeframeValue = self.safe_string(timeframes, timeframe)
        request = {
            'symbol': market['id'],
            'interval': timeframeValue,
        }
        candles = None
        if market['spot']:
            if since is not None:
                request['startTime'] = since
            if limit is not None:
                request['limit'] = limit
            response = self.spotPublicGetKlines(self.extend(request, params))
            #
            #     [
            #       [
            #         1640804880000,
            #         "47482.36",
            #         "47482.36",
            #         "47416.57",
            #         "47436.1",
            #         "3.550717",
            #         1640804940000,
            #         "168387.3"
            #       ],
            #     ]
            #
            candles = response
        elif market['swap']:
            if since is not None:
                request['start'] = int(since / 1000)
            priceType = self.safe_string(params, 'price', 'default')
            params = self.omit(params, 'price')
            method = self.get_supported_mapping(priceType, {
                'default': 'contractPublicGetKlineSymbol',
                'index': 'contractPublicGetKlineIndexPriceSymbol',
                'mark': 'contractPublicGetKlineFairPriceSymbol',
            })
            response = getattr(self, method)(self.extend(request, params))
            #
            #     {
            #         "success":true,
            #         "code":0,
            #         "data":{
            #             "time":[1634052300,1634052360,1634052420],
            #             "open":[3492.2,3491.3,3495.65],
            #             "close":[3491.3,3495.65,3495.2],
            #             "high":[3495.85,3496.55,3499.4],
            #             "low":[3491.15,3490.9,3494.2],
            #             "vol":[1740.0,351.0,314.0],
            #             "amount":[60793.623,12260.4885,10983.1375],
            #         }
            #     }
            #
            data = self.safe_value(response, 'data')
            candles = self.convert_trading_view_to_ohlcv(data, 'time', 'open', 'high', 'low', 'close', 'vol')
        return self.parse_ohlcvs(candles, market, timeframe, since, limit)

    def parse_ohlcv(self, ohlcv, market=None):
        return [
            self.safe_integer(ohlcv, 0),
            self.safe_number(ohlcv, 1),
            self.safe_number(ohlcv, 2),
            self.safe_number(ohlcv, 3),
            self.safe_number(ohlcv, 4),
            self.safe_number(ohlcv, 5),
        ]

    def fetch_tickers(self, symbols=None, params={}):
        """
        fetches price tickers for multiple markets, statistical calculations with the information calculated over the past 24 hours each market
        :param [str]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        self.load_markets()
        request = {}
        market = None
        isSingularMarket = False
        if symbols is not None:
            length = len(symbols)
            isSingularMarket = length == 1
            firstSymbol = self.safe_string(symbols, 0)
            market = self.market(firstSymbol)
        marketType, query = self.handle_market_type_and_params('fetchTickers', market, params)
        tickers = None
        if isSingularMarket:
            request['symbol'] = market['id']
        if marketType == 'spot':
            tickers = self.spotPublicGetTicker24hr(self.extend(request, query))
            #
            #     [
            #         {
            #             "symbol": "BTCUSDT",
            #             "priceChange": "184.34",
            #             "priceChangePercent": "0.00400048",
            #             "prevClosePrice": "46079.37",
            #             "lastPrice": "46263.71",
            #             "lastQty": "",
            #             "bidPrice": "46260.38",
            #             "bidQty": "",
            #             "askPrice": "46260.41",
            #             "askQty": "",
            #             "openPrice": "46079.37",
            #             "highPrice": "47550.01",
            #             "lowPrice": "45555.5",
            #             "volume": "1732.461487",
            #             "quoteVolume": null,
            #             "openTime": 1641349500000,
            #             "closeTime": 1641349582808,
            #             "count": null
            #         }
            #     ]
            #
        elif marketType == 'swap':
            response = self.contractPublicGetTicker(self.extend(request, query))
            #
            #     {
            #         "success":true,
            #         "code":0,
            #         "data":[
            #             {
            #                 "symbol":"ETH_USDT",
            #                 "lastPrice":3581.3,
            #                 "bid1":3581.25,
            #                 "ask1":3581.5,
            #                 "volume24":4045530,
            #                 "amount24":141331823.5755,
            #                 "holdVol":5832946,
            #                 "lower24Price":3413.4,
            #                 "high24Price":3588.7,
            #                 "riseFallRate":0.0275,
            #                 "riseFallValue":95.95,
            #                 "indexPrice":3580.7852,
            #                 "fairPrice":3581.08,
            #                 "fundingRate":0.000063,
            #                 "maxBidPrice":3938.85,
            #                 "minAskPrice":3222.7,
            #                 "timestamp":1634162885016
            #             },
            #         ]
            #     }
            #
            tickers = self.safe_value(response, 'data', [])
        # when it's single symbol request, the returned structure is different(singular object) for both spot & swap, thus we need to wrap inside array
        if isSingularMarket:
            tickers = [tickers]
        return self.parse_tickers(tickers, symbols)

    def fetch_ticker(self, symbol, params={}):
        """
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        marketType, query = self.handle_market_type_and_params('fetchTicker', market, params)
        ticker = None
        request = {
            'symbol': market['id'],
        }
        if marketType == 'spot':
            ticker = self.spotPublicGetTicker24hr(self.extend(request, query))
            #
            #     {
            #         "symbol": "BTCUSDT",
            #         "priceChange": "184.34",
            #         "priceChangePercent": "0.00400048",
            #         "prevClosePrice": "46079.37",
            #         "lastPrice": "46263.71",
            #         "lastQty": "",
            #         "bidPrice": "46260.38",
            #         "bidQty": "",
            #         "askPrice": "46260.41",
            #         "askQty": "",
            #         "openPrice": "46079.37",
            #         "highPrice": "47550.01",
            #         "lowPrice": "45555.5",
            #         "volume": "1732.461487",
            #         "quoteVolume": null,
            #         "openTime": 1641349500000,
            #         "closeTime": 1641349582808,
            #         "count": null
            #     }
            #
        elif marketType == 'swap':
            response = self.contractPublicGetTicker(self.extend(request, query))
            #
            #     {
            #         "success":true,
            #         "code":0,
            #         "data":{
            #             "symbol":"ETH_USDT",
            #             "lastPrice":3581.3,
            #             "bid1":3581.25,
            #             "ask1":3581.5,
            #             "volume24":4045530,
            #             "amount24":141331823.5755,
            #             "holdVol":5832946,
            #             "lower24Price":3413.4,
            #             "high24Price":3588.7,
            #             "riseFallRate":0.0275,
            #             "riseFallValue":95.95,
            #             "indexPrice":3580.7852,
            #             "fairPrice":3581.08,
            #             "fundingRate":0.000063,
            #             "maxBidPrice":3938.85,
            #             "minAskPrice":3222.7,
            #             "timestamp":1634162885016
            #         }
            #     }
            #
            ticker = self.safe_value(response, 'data', {})
        # when it's single symbol request, the returned structure is different(singular object) for both spot & swap, thus we need to wrap inside array
        return self.parse_ticker(ticker, market)

    def parse_ticker(self, ticker, market=None):
        marketId = self.safe_string(ticker, 'symbol')
        market = self.safe_market(marketId, market)
        timestamp = None
        bid = None
        ask = None
        bidVolume = None
        askVolume = None
        baseVolume = None
        quoteVolume = None
        open = None
        high = None
        low = None
        changePcnt = None
        changeValue = None
        prevClose = None
        isSwap = self.safe_value(market, 'swap')
        # if swap
        if isSwap or ('timestamp' in ticker):
            #
            #     {
            #         "symbol": "ETH_USDT",
            #         "lastPrice": 3581.3,
            #         "bid1": 3581.25,
            #         "ask1": 3581.5,
            #         "volume24": 4045530,
            #         "amount24": 141331823.5755,
            #         "holdVol": 5832946,
            #         "lower24Price": 3413.4,
            #         "high24Price": 3588.7,
            #         "riseFallRate": 0.0275,
            #         "riseFallValue": 95.95,
            #         "indexPrice": 3580.7852,
            #         "fairPrice": 3581.08,
            #         "fundingRate": 0.000063,
            #         "maxBidPrice": 3938.85,
            #         "minAskPrice": 3222.7,
            #         "timestamp": 1634162885016
            #     }
            #
            timestamp = self.safe_integer(ticker, 'timestamp')
            bid = self.safe_string(ticker, 'bid1')
            ask = self.safe_string(ticker, 'ask1')
            baseVolume = self.safe_string(ticker, 'volume24')
            quoteVolume = self.safe_string(ticker, 'amount24')
            high = self.safe_string(ticker, 'high24Price')
            low = self.safe_string(ticker, 'lower24Price')
            changeValue = self.safe_string(ticker, 'riseFallValue')
            changePcnt = self.safe_string(ticker, 'riseFallRate')
            changePcnt = Precise.string_mul(changePcnt, '100')
        else:
            #
            #     {
            #         "symbol": "BTCUSDT",
            #         "priceChange": "184.34",
            #         "priceChangePercent": "0.00400048",
            #         "prevClosePrice": "46079.37",
            #         "lastPrice": "46263.71",
            #         "lastQty": "",
            #         "bidPrice": "46260.38",
            #         "bidQty": "",
            #         "askPrice": "46260.41",
            #         "askQty": "",
            #         "openPrice": "46079.37",
            #         "highPrice": "47550.01",
            #         "lowPrice": "45555.5",
            #         "volume": "1732.461487",
            #         "quoteVolume": null,
            #         "openTime": 1641349500000,
            #         "closeTime": 1641349582808,
            #         "count": null
            #     }
            #
            timestamp = self.safe_integer(ticker, 'closeTime')
            bid = self.safe_string(ticker, 'bidPrice')
            ask = self.safe_string(ticker, 'askPrice')
            bidVolume = self.safe_string(ticker, 'bidQty')
            askVolume = self.safe_string(ticker, 'askQty')
            if Precise.string_eq(bidVolume, '0'):
                bidVolume = None
            if Precise.string_eq(askVolume, '0'):
                askVolume = None
            baseVolume = self.safe_string(ticker, 'volume')
            quoteVolume = self.safe_string(ticker, 'quoteVolume')
            open = self.safe_string(ticker, 'openPrice')
            high = self.safe_string(ticker, 'highPrice')
            low = self.safe_string(ticker, 'lowPrice')
            prevClose = self.safe_string(ticker, 'prevClosePrice')
            changeValue = self.safe_string(ticker, 'priceChange')
            changePcnt = self.safe_string(ticker, 'priceChangePercent')
            changePcnt = Precise.string_mul(changePcnt, '100')
        return self.safe_ticker({
            'symbol': market['symbol'],
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'open': open,
            'high': high,
            'low': low,
            'close': self.safe_string(ticker, 'lastPrice'),
            'bid': bid,
            'bidVolume': bidVolume,
            'ask': ask,
            'askVolume': askVolume,
            'vwap': None,
            'previousClose': prevClose,
            'change': changeValue,
            'percentage': changePcnt,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market)

    def fetch_bids_asks(self, symbols=None, params={}):
        """
        fetches the bid and ask price and volume for multiple markets
        :param [str]|None symbols: unified symbols of the markets to fetch the bids and asks for, all markets are returned if not assigned
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        self.load_markets()
        market = None
        isSingularMarket = False
        if symbols is not None:
            length = len(symbols)
            isSingularMarket = length == 1
            market = self.market(symbols[0])
        marketType, query = self.handle_market_type_and_params('fetchBidsAsks', market, params)
        tickers = None
        if marketType == 'spot':
            tickers = self.spotPublicGetTickerBookTicker(query)
            #
            #     [
            #       {
            #         "symbol": "AEUSDT",
            #         "bidPrice": "0.11001",
            #         "bidQty": "115.59",
            #         "askPrice": "0.11127",
            #         "askQty": "215.48"
            #       },
            #     ]
            #
        elif marketType == 'swap':
            raise NotSupported(self.id + ' fetchBidsAsks() is not available for ' + marketType + ' markets')
        # when it's single symbol request, the returned structure is different(singular object) for both spot & swap, thus we need to wrap inside array
        if isSingularMarket:
            tickers = [tickers]
        return self.parse_tickers(tickers, symbols)

    def create_order(self, symbol, type, side, amount, price=None, params={}):
        """
        create a trade order
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float|None price: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :param str|None params['marginMode']: only 'isolated' is supported for spot-margin trading
        :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        marginMode, query = self.handle_margin_mode_and_params('createOrder', params)
        if market['spot']:
            return self.create_spot_order(market, type, side, amount, price, marginMode, query)
        elif market['swap']:
            return self.create_swap_order(market, type, side, amount, price, marginMode, query)

    def create_spot_order(self, market, type, side, amount, price=None, marginMode=None, params={}):
        symbol = market['symbol']
        orderSide = 'BUY' if (side == 'buy') else 'SELL'
        request = {
            'symbol': market['id'],
            'side': orderSide,
            'type': type.upper(),
        }
        if orderSide == 'BUY' and type == 'market':
            quoteOrderQty = self.safe_number(params, 'quoteOrderQty')
            if quoteOrderQty is not None:
                amount = quoteOrderQty
            elif self.options['createMarketBuyOrderRequiresPrice']:
                if price is None:
                    raise InvalidOrder(self.id + " createOrder() requires the price argument with market buy orders to calculate total order cost(amount to spend), where cost = amount * price. Supply a price argument to createOrder() call if you want the cost to be calculated for you from price and amount, or, alternatively, add .options['createMarketBuyOrderRequiresPrice'] = False to supply the cost in the amount argument(the exchange-specific behaviour)")
                else:
                    amountString = self.number_to_string(amount)
                    priceString = self.number_to_string(price)
                    quoteAmount = Precise.string_mul(amountString, priceString)
                    amount = self.parse_number(quoteAmount)
            request['quoteOrderQty'] = amount
        else:
            request['quantity'] = self.amount_to_precision(symbol, amount)
        if price is not None:
            request['price'] = self.price_to_precision(symbol, price)
        clientOrderId = self.safe_string(params, 'clientOrderId')
        if clientOrderId is not None:
            request['newClientOrderId'] = clientOrderId
            params = self.omit(params, ['type', 'clientOrderId'])
        method = 'spotPrivatePostOrder'
        if marginMode is not None:
            if marginMode != 'isolated':
                raise BadRequest(self.id + ' createOrder() does not support marginMode ' + marginMode + ' for spot-margin trading')
            method = 'spotPrivatePostMarginOrder'
        response = getattr(self, method)(self.extend(request, params))
        #
        # spot
        #
        #     {
        #         "symbol": "BTCUSDT",
        #         "orderId": "123738410679123456",
        #         "orderListId": -1
        #     }
        #
        # margin
        #
        #     {
        #         "symbol": "BTCUSDT",
        #         "orderId": "762634301354414080",
        #         "clientOrderId": null,
        #         "isIsolated": True,
        #         "transactTime": 1661992652132
        #     }
        #
        return self.extend(self.parse_order(response, market), {
            'side': side,
            'type': type,
            'price': price,
            'amount': amount,
        })

    def create_swap_order(self, market, type, side, amount, price=None, marginMode=None, params={}):
        self.load_markets()
        symbol = market['symbol']
        unavailableContracts = self.safe_value(self.options, 'unavailableContracts', {})
        isContractUnavaiable = self.safe_value(unavailableContracts, symbol, False)
        if isContractUnavaiable:
            raise NotSupported(self.id + ' createSwapOrder() does not support yet self symbol:' + symbol)
        openType = None
        if marginMode is not None:
            if marginMode == 'cross':
                openType = 2
            elif marginMode == 'isolated':
                openType = 1
            else:
                raise ArgumentsRequired(self.id + ' createSwapOrder() marginMode parameter should be either "cross" or "isolated"')
        else:
            openType = self.safe_integer(params, 'openType', 2)  # defaulting to cross margin
        if (type != 'limit') and (type != 'market') and (type != 1) and (type != 2) and (type != 3) and (type != 4) and (type != 5) and (type != 6):
            raise InvalidOrder(self.id + ' createSwapOrder() order type must either limit, market, or 1 for limit orders, 2 for post-only orders, 3 for IOC orders, 4 for FOK orders, 5 for market orders or 6 to convert market price to current price')
        postOnly = self.safe_value(params, 'postOnly', False)
        if postOnly:
            type = 2
        elif type == 'limit':
            type = 1
        elif type == 'market':
            type = 6
        request = {
            'symbol': market['id'],
            # 'price': float(self.price_to_precision(symbol, price)),
            'vol': float(self.amount_to_precision(symbol, amount)),
            # 'leverage': int,  # required for isolated margin
            # 'side': side,  # 1 open long, 2 close short, 3 open short, 4 close long
            #
            # supported order types
            #
            #     1 limit
            #     2 post only maker(PO)
            #     3 transact or cancel instantly(IOC)
            #     4 transact completely or cancel completely(FOK)
            #     5 market orders
            #     6 convert market price to current price
            #
            'type': type,
            'openType': openType,  # 1 isolated, 2 cross
            # 'positionId': 1394650,  # long, filling in self parameter when closing a position is recommended
            # 'externalOid': clientOrderId,
            # 'triggerPrice': 10.0,  # Required for trigger order
            # 'triggerType': 1,  # Required for trigger order 1: more than or equal, 2: less than or equal
            # 'executeCycle': 1,  # Required for trigger order 1: 24 hours,2: 7 days
            # 'trend': 1,  # Required for trigger order 1: latest price, 2: fair price, 3: index price
            # 'orderType': 1,  # Required for trigger order 1: limit order,2:Post Only Maker,3: close or cancel instantly ,4: close or cancel completely,5: Market order
        }
        method = 'contractPrivatePostOrderSubmit'
        stopPrice = self.safe_number_2(params, 'triggerPrice', 'stopPrice')
        params = self.omit(params, ['stopPrice', 'triggerPrice'])
        if stopPrice:
            method = 'contractPrivatePostPlanorderPlace'
            request['triggerPrice'] = self.price_to_precision(symbol, stopPrice)
            request['triggerType'] = self.safe_integer(params, 'triggerType', 1)
            request['executeCycle'] = self.safe_integer(params, 'executeCycle', 1)
            request['trend'] = self.safe_integer(params, 'trend', 1)
            request['orderType'] = self.safe_integer(params, 'orderType', 1)
        if (type != 5) and (type != 6) and (type != 'market'):
            request['price'] = float(self.price_to_precision(symbol, price))
        if openType == 1:
            leverage = self.safe_integer(params, 'leverage')
            if leverage is None:
                raise ArgumentsRequired(self.id + ' createSwapOrder() requires a leverage parameter for isolated margin orders')
        reduceOnly = self.safe_value(params, 'reduceOnly', False)
        if reduceOnly:
            request['side'] = 2 if (side == 'buy') else 4
        else:
            request['side'] = 1 if (side == 'buy') else 3
        clientOrderId = self.safe_string_2(params, 'clientOrderId', 'externalOid')
        if clientOrderId is not None:
            request['externalOid'] = clientOrderId
        params = self.omit(params, ['clientOrderId', 'externalOid', 'postOnly'])
        response = getattr(self, method)(self.extend(request, params))
        #
        # Swap
        #     {"code":200,"data":"2ff3163e8617443cb9c6fc19d42b1ca4"}
        #
        # Trigger
        #     {"success":true,"code":0,"data":259208506303929856}
        #
        data = self.safe_string(response, 'data')
        return self.parse_order(data, market)

    def fetch_order(self, id, symbol=None, params={}):
        """
        fetches information on an order made by the user
        :param str symbol: unified symbol of the market the order was made in
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :param str|None params['marginMode']: only 'isolated' is supported, for spot-margin trading
        :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchOrder() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        data = None
        if market['spot']:
            clientOrderId = self.safe_string(params, 'clientOrderId')
            if clientOrderId is not None:
                params = self.omit(params, 'clientOrderId')
                request['origClientOrderId'] = clientOrderId
            else:
                request['orderId'] = id
            marginMode, query = self.handle_margin_mode_and_params('fetchOrder', params)
            method = 'spotPrivateGetOrder'
            if marginMode is not None:
                if marginMode != 'isolated':
                    raise BadRequest(self.id + ' fetchOrder() does not support marginMode ' + marginMode + ' for spot-margin trading')
                method = 'spotPrivateGetMarginOrder'
            data = getattr(self, method)(self.extend(request, query))
            #
            # spot
            #
            #     {
            #         "symbol": "BTCUSDT",
            #         "orderId": "133734823834147272",
            #         "orderListId": "-1",
            #         "clientOrderId": null,
            #         "price": "30000",
            #         "origQty": "0.0002",
            #         "executedQty": "0",
            #         "cummulativeQuoteQty": "0",
            #         "status": "CANCELED",
            #         "timeInForce": null,
            #         "type": "LIMIT",
            #         "side": "BUY",
            #         "stopPrice": null,
            #         "icebergQty": null,
            #         "time": "1647667102000",
            #         "updateTime": "1647708567000",
            #         "isWorking": True,
            #         "origQuoteOrderQty": "6"
            #     }
            #
            # margin
            #
            #     {
            #         "symbol": "BTCUSDT",
            #         "orderId": "763307297891028992",
            #         "orderListId": "-1",
            #         "clientOrderId": null,
            #         "price": "18000",
            #         "origQty": "0.0014",
            #         "executedQty": "0",
            #         "cummulativeQuoteQty": "0",
            #         "status": "NEW",
            #         "type": "LIMIT",
            #         "side": "BUY",
            #         "isIsolated": True,
            #         "isWorking": True,
            #         "time": 1662153107000,
            #         "updateTime": 1662153107000
            #     }
            #
        elif market['swap']:
            request['order_id'] = id
            response = self.contractPrivateGetOrderGetOrderId(self.extend(request, params))
            #
            #     {
            #         "success": True,
            #         "code": "0",
            #         "data": {
            #             "orderId": "264995729269765120",
            #             "symbol": "STEPN_USDT",
            #             "positionId": "0",
            #             "price": "2.2",
            #             "vol": "15",
            #             "leverage": "20",
            #             "side": "1",
            #             "category": "1",
            #             "orderType": "1",
            #             "dealAvgPrice": "0",
            #             "dealVol": "0",
            #             "orderMargin": "2.2528",
            #             "takerFee": "0",
            #             "makerFee": "0",
            #             "profit": "0",
            #             "feeCurrency": "USDT",
            #             "openType": "1",
            #             "state": "2",
            #             "externalOid": "_m_0e9520c256744d64b942985189026d20",
            #             "errorCode": "0",
            #             "usedMargin": "0",
            #             "createTime": "1648850305236",
            #             "updateTime": "1648850305245",
            #             "positionMode": "1"
            #         }
            #     }
            #
            data = self.safe_value(response, 'data')
        return self.parse_order(data, market)

    def fetch_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches information on multiple orders made by the user
        :param str|None symbol: unified market symbol of the market orders were made in
        :param int|None since: the earliest time in ms to fetch orders for
        :param int|None limit: the maximum number of  orde structures to retrieve
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :param str|None params['marginMode']: only 'isolated' is supported, for spot-margin trading
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        request = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        marketType, query = self.handle_market_type_and_params('fetchOrders', market, params)
        if marketType == 'spot':
            if symbol is None:
                raise ArgumentsRequired(self.id + ' fetchOrders() requires a symbol argument for spot market')
            marginMode, query = self.handle_margin_mode_and_params('fetchOrders', params)
            method = 'spotPrivateGetAllOrders'
            if marginMode is not None:
                if marginMode != 'isolated':
                    raise BadRequest(self.id + ' fetchOrders() does not support marginMode ' + marginMode + ' for spot-margin trading')
                method = 'spotPrivateGetMarginAllOrders'
            if since is not None:
                request['startTime'] = since
            if limit is not None:
                request['limit'] = limit
            response = getattr(self, method)(self.extend(request, query))
            #
            # spot
            #
            #     [
            #         {
            #             "symbol": "BTCUSDT",
            #             "orderId": "133949373632483328",
            #             "orderListId": "-1",
            #             "clientOrderId": null,
            #             "price": "45000",
            #             "origQty": "0.0002",
            #             "executedQty": "0",
            #             "cummulativeQuoteQty": "0",
            #             "status": "NEW",
            #             "timeInForce": null,
            #             "type": "LIMIT",
            #             "side": "SELL",
            #             "stopPrice": null,
            #             "icebergQty": null,
            #             "time": "1647718255000",
            #             "updateTime": "1647718255000",
            #             "isWorking": True,
            #             "origQuoteOrderQty": "9"
            #         },
            #     ]
            #
            # margin
            #
            #     [
            #         {
            #             "symbol": "BTCUSDT",
            #             "orderId": "763307297891028992",
            #             "orderListId": "-1",
            #             "clientOrderId": null,
            #             "price": "18000",
            #             "origQty": "0.0014",
            #             "executedQty": "0",
            #             "cummulativeQuoteQty": "0",
            #             "status": "NEW",
            #             "type": "LIMIT",
            #             "side": "BUY",
            #             "isIsolated": True,
            #             "isWorking": True,
            #             "time": 1662153107000,
            #             "updateTime": 1662153107000
            #         }
            #     ]
            #
            return self.parse_orders(response, market, since, limit)
        else:
            if since is not None:
                request['start_time'] = since
                end = self.safe_integer(params, 'end_time')
                if end is None:
                    request['end_time'] = self.sum(since, self.options['maxTimeTillEnd'])
            if limit is not None:
                request['page_size'] = limit
            method = self.safe_string(self.options, 'fetchOrders', 'contractPrivateGetOrderListHistoryOrders')
            method = self.safe_string(query, 'method', method)
            ordersOfRegular = []
            ordersOfTrigger = []
            if method == 'contractPrivateGetOrderListHistoryOrders':
                response = self.contractPrivateGetOrderListHistoryOrders(self.extend(request, query))
                #
                #     {
                #         "success": True,
                #         "code": "0",
                #         "data": [
                #             {
                #                 "orderId": "265230764677709315",
                #                 "symbol": "STEPN_USDT",
                #                 "positionId": "0",
                #                 "price": "2.1",
                #                 "vol": "102",
                #                 "leverage": "20",
                #                 "side": "1",
                #                 "category": "1",
                #                 "orderType": "1",
                #                 "dealAvgPrice": "0",
                #                 "dealVol": "0",
                #                 "orderMargin": "10.96704",
                #                 "takerFee": "0",
                #                 "makerFee": "0",
                #                 "profit": "0",
                #                 "feeCurrency": "USDT",
                #                 "openType": "1",
                #                 "state": "2",
                #                 "externalOid": "_m_7e42f8df6b324c869e4e200397e2b00f",
                #                 "errorCode": "0",
                #                 "usedMargin": "0",
                #                 "createTime": "1648906342000",
                #                 "updateTime": "1648906342000",
                #                 "positionMode": "1"
                #             },
                #          ]
                #     }
                #
                ordersOfRegular = self.safe_value(response, 'data')
            else:
                # the Planorder endpoints work not only for stop-market orders, but also for stop-limit orders that were supposed to have a separate endpoint
                response = self.contractPrivateGetPlanorderListOrders(self.extend(request, query))
                #
                #     {
                #         "success": True,
                #         "code": "0",
                #         "data": [
                #             {
                #                 "symbol": "STEPN_USDT",
                #                 "leverage": "20",
                #                 "side": "1",
                #                 "vol": "13",
                #                 "openType": "1",
                #                 "state": "1",
                #                 "orderType": "1",
                #                 "errorCode": "0",
                #                 "createTime": "1648984276000",
                #                 "updateTime": "1648984276000",
                #                 "id": "265557643326564352",
                #                 "triggerType": "1",
                #                 "triggerPrice": "3",
                #                 "price": "2.9",  # not present in stop-market, but in stop-limit order
                #                 "executeCycle": "87600",
                #                 "trend": "1",
                #             },
                #         ]
                #     }
                #
                ordersOfTrigger = self.safe_value(response, 'data')
            merged = self.array_concat(ordersOfTrigger, ordersOfRegular)
            return self.parse_orders(merged, market, since, limit, params)

    def fetch_orders_by_ids(self, ids, symbol=None, params={}):
        self.load_markets()
        request = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        marketType, query = self.handle_market_type_and_params('fetchOrdersByIds', market, params)
        if marketType == 'spot':
            raise BadRequest(self.id + ' fetchOrdersByIds() is not supported for ' + marketType)
        else:
            request['order_ids'] = ','.join(ids)
            response = self.contractPrivateGetOrderBatchQuery(self.extend(request, query))
            #
            #     {
            #         "success": True,
            #         "code": "0",
            #         "data": [
            #             {
            #                 "orderId": "265230764677709315",
            #                 "symbol": "STEPN_USDT",
            #                 "positionId": "0",
            #                 "price": "2.1",
            #                 "vol": "102",
            #                 "leverage": "20",
            #                 "side": "1",
            #                 "category": "1",
            #                 "orderType": "1",
            #                 "dealAvgPrice": "0",
            #                 "dealVol": "0",
            #                 "orderMargin": "10.96704",
            #                 "takerFee": "0",
            #                 "makerFee": "0",
            #                 "profit": "0",
            #                 "feeCurrency": "USDT",
            #                 "openType": "1",
            #                 "state": "2",
            #                 "externalOid": "_m_7e42f8df6b324c869e4e200397e2b00f",
            #                 "errorCode": "0",
            #                 "usedMargin": "0",
            #                 "createTime": "1648906342000",
            #                 "updateTime": "1648906342000",
            #                 "positionMode": "1"
            #             }
            #         ]
            #     }
            #
            data = self.safe_value(response, 'data')
            return self.parse_orders(data, market)

    def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetch all unfilled currently open orders
        :param str|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch open orders for
        :param int|None limit: the maximum number of  open orders structures to retrieve
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :param str|None params['marginMode']: only 'isolated' is supported, for spot-margin trading
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        request = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        marketType = None
        marketType, params = self.handle_market_type_and_params('fetchOpenOrders', market, params)
        if marketType == 'spot':
            if symbol is None:
                raise ArgumentsRequired(self.id + ' fetchOpenOrders() requires a symbol argument for spot market')
            method = 'spotPrivateGetOpenOrders'
            marginMode, query = self.handle_margin_mode_and_params('fetchOpenOrders', params)
            if marginMode is not None:
                if marginMode != 'isolated':
                    raise BadRequest(self.id + ' fetchOpenOrders() does not support marginMode ' + marginMode + ' for spot-margin trading')
                method = 'spotPrivateGetMarginOpenOrders'
            response = getattr(self, method)(self.extend(request, query))
            #
            # spot
            #
            #     [
            #         {
            #             "symbol": "BTCUSDT",
            #             "orderId": "133949373632483328",
            #             "orderListId": "-1",
            #             "clientOrderId": "",
            #             "price": "45000",
            #             "origQty": "0.0002",
            #             "executedQty": "0",
            #             "cummulativeQuoteQty": "0",
            #             "status": "NEW",
            #             "timeInForce": null,
            #             "type": "LIMIT",
            #             "side": "SELL",
            #             "stopPrice": null,
            #             "icebergQty": null,
            #             "time": "1647718255199",
            #             "updateTime": null,
            #             "isWorking": True,
            #             "origQuoteOrderQty": "9"
            #         }
            #     ]
            #
            # margin
            #
            #     [
            #         {
            #             "symbol": "BTCUSDT",
            #             "orderId": "764547676405633024",
            #             "orderListId": "-1",
            #             "clientOrderId": null,
            #             "price": "18000",
            #             "origQty": "0.0013",
            #             "executedQty": "0",
            #             "cummulativeQuoteQty": "0",
            #             "status": "NEW",
            #             "type": "LIMIT",
            #             "side": "BUY",
            #             "isIsolated": True,
            #             "isWorking": True,
            #             "time": 1662448836000,
            #             "updateTime": 1662448836000
            #         }
            #     ]
            #
            return self.parse_orders(response, market, since, limit)
        else:
            # TO_DO: another possible way is through: open_orders/{symbol}, but as they have same ratelimits, and less granularity, i think historical orders are more convenient, as it supports more params(however, theoretically, open-orders endpoint might be sligthly fast)
            return self.fetch_orders_by_state(2, symbol, since, limit, params)

    def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches information on multiple closed orders made by the user
        :param str|None symbol: unified market symbol of the market orders were made in
        :param int|None since: the earliest time in ms to fetch orders for
        :param int|None limit: the maximum number of  orde structures to retrieve
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        return self.fetch_orders_by_state(3, symbol, since, limit, params)

    def fetch_canceled_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches information on multiple canceled orders made by the user
        :param str|None symbol: unified market symbol of the market orders were made in
        :param int|None since: timestamp in ms of the earliest order, default is None
        :param int|None limit: max number of orders to return, default is None
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        return self.fetch_orders_by_state(4, symbol, since, limit, params)

    def fetch_orders_by_state(self, state, symbol=None, since=None, limit=None, params={}):
        self.load_markets()
        request = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        marketType = self.handle_market_type_and_params('fetchOrdersByState', market, params)
        if marketType == 'spot':
            raise BadRequest(self.id + ' fetchOrdersByState() is not supported for ' + marketType)
        else:
            params['states'] = state
            return self.fetch_orders(symbol, since, limit, params)

    def cancel_order(self, id, symbol=None, params={}):
        """
        cancels an open order
        :param str id: order id
        :param str|None symbol: unified symbol of the market the order was made in
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :param str|None params['marginMode']: only 'isolated' is supported for spot-margin trading
        :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        request = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        marketType = None
        marketType, params = self.handle_market_type_and_params('cancelOrder', market, params)
        marginMode, query = self.handle_margin_mode_and_params('cancelOrder', params)
        data = None
        if marketType == 'spot':
            if symbol is None:
                raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
            request = {
                'symbol': market['id'],
            }
            clientOrderId = self.safe_string(params, 'clientOrderId')
            if clientOrderId is not None:
                params = self.omit(query, 'clientOrderId')
                request['origClientOrderId'] = clientOrderId
            else:
                request['orderId'] = id
            method = 'spotPrivateDeleteOrder'
            if marginMode is not None:
                if marginMode != 'isolated':
                    raise BadRequest(self.id + ' cancelOrder() does not support marginMode ' + marginMode + ' for spot-margin trading')
                method = 'spotPrivateDeleteMarginOrder'
            data = getattr(self, method)(self.extend(request, query))
            #
            # spot
            #
            #     {
            #         "symbol": "BTCUSDT",
            #         "orderId": "133734823834447872",
            #         "price": "30000",
            #         "origQty": "0.0002",
            #         "type": "LIMIT",
            #         "side": "BUY"
            #     }
            #
            # margin
            #
            #     [
            #         {
            #             "symbol": "BTCUSDT",
            #             "orderId": "762640232574226432",
            #             "orderListId": "-1",
            #             "clientOrderId": null,
            #             "price": "18000",
            #             "origQty": "0.00147",
            #             "executedQty": "0",
            #             "cummulativeQuoteQty": "0",
            #             "status": "NEW",
            #             "type": "LIMIT",
            #             "side": "BUY",
            #             "isIsolated": True,
            #             "isWorking": True,
            #             "time": 1661994066000,
            #             "updateTime": 1661994066000
            #         }
            #     ]
            #
        else:
            # TODO: PlanorderCancel endpoint has bug atm. waiting for fix.
            method = self.safe_string(self.options, 'cancelOrder', 'contractPrivatePostOrderCancel')  # contractPrivatePostOrderCancel, contractPrivatePostPlanorderCancel
            method = self.safe_string(query, 'method', method)
            response = getattr(self, method)([id])  # the request cannot be changed or extended. This is the only way to send.
            #
            #     {
            #         "success": True,
            #         "code": "0",
            #         "data": [
            #             {
            #                 "orderId": "264995729269765120",
            #                 "errorCode": "0",         # if already canceled: "2041"; if doesn't exist: "2040"
            #                 "errorMsg": "success",    # if already canceled: "order state cannot be cancelled"; if doesn't exist: "order not exist"
            #             }
            #         ]
            #     }
            #
            data = self.safe_value(response, 'data')
            order = self.safe_value(data, 0)
            errorMsg = self.safe_value(order, 'errorMsg', '')
            if errorMsg != 'success':
                raise InvalidOrder(self.id + ' cancelOrder() the order with id ' + id + ' cannot be cancelled: ' + errorMsg)
        return self.parse_order(data, market)

    def cancel_orders(self, ids, symbol=None, params={}):
        """
        cancel multiple orders
        :param [str] ids: order ids
        :param str|None symbol: unified market symbol, default is None
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: an list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        market = self.market(symbol) if (symbol is not None) else None
        marketType = self.handle_market_type_and_params('cancelOrders', market, params)
        if marketType == 'spot':
            raise BadRequest(self.id + ' cancelOrders() is not supported for ' + marketType)
        else:
            response = self.contractPrivatePostOrderCancel(ids)  # the request cannot be changed or extended. The only way to send.
            #
            #     {
            #         "success": True,
            #         "code": "0",
            #         "data": [
            #             {
            #                 "orderId": "264995729269765120",
            #                 "errorCode": "0",         # if already canceled: "2041"
            #                 "errorMsg": "success",    # if already canceled: "order state cannot be cancelled"
            #             },
            #         ]
            #     }
            #
            data = self.safe_value(response, 'data')
            return self.parse_orders(data, market)

    def cancel_all_orders(self, symbol=None, params={}):
        """
        cancel all open orders
        :param str|None 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 mexc3 api endpoint
        :param str|None params['marginMode']: only 'isolated' is supported for spot-margin trading
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        market = self.market(symbol) if (symbol is not None) else None
        request = {}
        marketType = None
        marketType, params = self.handle_market_type_and_params('cancelAllOrders', market, params)
        marginMode, query = self.handle_margin_mode_and_params('cancelAllOrders', params)
        if marketType == 'spot':
            if symbol is None:
                raise ArgumentsRequired(self.id + ' cancelAllOrders() requires a symbol argument on spot')
            request['symbol'] = market['id']
            method = 'spotPrivateDeleteOpenOrders'
            if marginMode is not None:
                if marginMode != 'isolated':
                    raise BadRequest(self.id + ' cancelAllOrders() does not support marginMode ' + marginMode + ' for spot-margin trading')
                method = 'spotPrivateDeleteMarginOpenOrders'
            response = getattr(self, method)(self.extend(request, query))
            #
            # spot
            #
            #     [
            #         {
            #             "symbol": "BTCUSDT",
            #             "orderId": "133926492139692032",
            #             "price": "30000",
            #             "origQty": "0.0002",
            #             "type": "LIMIT",
            #             "side": "BUY"
            #         },
            #     ]
            #
            # margin
            #
            #     [
            #         {
            #             "symbol": "BTCUSDT",
            #             "orderId": "762640232574226432",
            #             "orderListId": "-1",
            #             "clientOrderId": null,
            #             "price": "18000",
            #             "origQty": "0.00147",
            #             "executedQty": "0",
            #             "cummulativeQuoteQty": "0",
            #             "status": "NEW",
            #             "type": "LIMIT",
            #             "side": "BUY",
            #             "isIsolated": True,
            #             "isWorking": True,
            #             "time": 1661994066000,
            #             "updateTime": 1661994066000
            #         }
            #     ]
            #
            return self.parse_orders(response, market)
        else:
            if symbol is not None:
                request['symbol'] = market['id']
            # method can be either: contractPrivatePostOrderCancelAll or contractPrivatePostPlanorderCancelAll
            # the Planorder endpoints work not only for stop-market orders but also for stop-limit orders that are supposed to have separate endpoint
            method = self.safe_string(self.options, 'cancelAllOrders', 'contractPrivatePostOrderCancelAll')
            method = self.safe_string(query, 'method', method)
            response = getattr(self, method)(self.extend(request, query))
            #
            #     {
            #         "success": True,
            #         "code": "0"
            #     }
            #
            data = self.safe_value(response, 'data', [])
            return self.parse_orders(data, market)

    def parse_order(self, order, market=None):
        #
        # spot: createOrder
        #
        #     {
        #         "symbol": "BTCUSDT",
        #         "orderId": "123738410679123456",
        #         "orderListId": -1
        #     }
        #
        # margin: createOrder
        #
        #     {
        #         "symbol": "BTCUSDT",
        #         "orderId": "762634301354414080",
        #         "clientOrderId": null,
        #         "isIsolated": True,
        #         "transactTime": 1661992652132
        #     }
        #
        # spot: cancelOrder, cancelAllOrders
        #
        #     {
        #         "symbol": "BTCUSDT",
        #         "orderId": "133926441921286144",
        #         "price": "30000",
        #         "origQty": "0.0002",
        #         "type": "LIMIT",
        #         "side": "BUY"
        #     }
        #
        # margin: cancelOrder, cancelAllOrders
        #
        #     {
        #         "symbol": "BTCUSDT",
        #         "orderId": "762640232574226432",
        #         "orderListId": "-1",
        #         "clientOrderId": null,
        #         "price": "18000",
        #         "origQty": "0.00147",
        #         "executedQty": "0",
        #         "cummulativeQuoteQty": "0",
        #         "status": "NEW",
        #         "type": "LIMIT",
        #         "side": "BUY",
        #         "isIsolated": True,
        #         "isWorking": True,
        #         "time": 1661994066000,
        #         "updateTime": 1661994066000
        #     }
        #
        # spot: fetchOrder, fetchOpenOrders, fetchOrders
        #
        #     {
        #         "symbol": "BTCUSDT",
        #         "orderId": "133734823834147272",
        #         "orderListId": "-1",
        #         "clientOrderId": null,
        #         "price": "30000",
        #         "origQty": "0.0002",
        #         "executedQty": "0",
        #         "cummulativeQuoteQty": "0",
        #         "status": "CANCELED",
        #         "timeInForce": null,
        #         "type": "LIMIT",
        #         "side": "BUY",
        #         "stopPrice": null,
        #         "icebergQty": null,
        #         "time": "1647667102000",
        #         "updateTime": "1647708567000",
        #         "isWorking": True,
        #         "origQuoteOrderQty": "6"
        #     }
        #
        # margin: fetchOrder, fetchOrders
        #
        #     {
        #         "symbol": "BTCUSDT",
        #         "orderId": "763307297891028992",
        #         "orderListId": "-1",
        #         "clientOrderId": null,
        #         "price": "18000",
        #         "origQty": "0.0014",
        #         "executedQty": "0",
        #         "cummulativeQuoteQty": "0",
        #         "status": "NEW",
        #         "type": "LIMIT",
        #         "side": "BUY",
        #         "isIsolated": True,
        #         "isWorking": True,
        #         "time": 1662153107000,
        #         "updateTime": 1662153107000
        #     }
        #
        # swap: createOrder
        #
        #     2ff3163e8617443cb9c6fc19d42b1ca4
        #
        # swap: fetchOrder, fetchOrders
        #
        #     regular
        #     {
        #         "orderId": "264995729269765120",
        #         "symbol": "STEPN_USDT",
        #         "positionId": "0",
        #         "price": "2.2",
        #         "vol": "15",
        #         "leverage": "20",
        #         "side": "1",  # TODO: not unified
        #         "category": "1",
        #         "orderType": "1",  # TODO: not unified
        #         "dealAvgPrice": "0",
        #         "dealVol": "0",
        #         "orderMargin": "2.2528",
        #         "takerFee": "0",
        #         "makerFee": "0",
        #         "profit": "0",
        #         "feeCurrency": "USDT",
        #         "openType": "1",
        #         "state": "2",  # TODO
        #         "externalOid": "_m_0e9520c256744d64b942985189026d20",
        #         "errorCode": "0",
        #         "usedMargin": "0",
        #         "createTime": "1648850305236",
        #         "updateTime": "1648850305245",
        #         "positionMode": "1"
        #     }
        #
        #     stop
        #     {
        #         "id": "265557643326564352",
        #         "triggerType": "1",
        #         "triggerPrice": "3",
        #         "price": "2.9",  # not present in stop-market, but in stop-limit order
        #         "executeCycle": "87600",
        #         "trend": "1",
        #          # below keys are same as in regular order structure
        #         "symbol": "STEPN_USDT",
        #         "leverage": "20",
        #         "side": "1",
        #         "vol": "13",
        #         "openType": "1",
        #         "state": "1",
        #         "orderType": "1",
        #         "errorCode": "0",
        #         "createTime": "1648984276000",
        #         "updateTime": "1648984276000",
        #     }
        #
        id = None
        if isinstance(order, str):
            id = order
        else:
            id = self.safe_string_2(order, 'orderId', 'id')
        marketId = self.safe_string(order, 'symbol')
        market = self.safe_market(marketId, market)
        timestamp = self.safe_integer_n(order, ['time', 'createTime', 'transactTime'])
        fee = None
        feeCurrency = self.safe_string(order, 'feeCurrency')
        if feeCurrency is not None:
            takerFee = self.safe_string(order, 'takerFee')
            makerFee = self.safe_string(order, 'makerFee')
            feeSum = Precise.string_add(takerFee, makerFee)
            fee = {
                'currency': feeCurrency,
                'cost': self.parse_number(feeSum),
            }
        return self.safe_order({
            'id': id,
            'clientOrderId': self.safe_string(order, 'clientOrderId'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,  # TODO: self might be 'updateTime' if order-status is filled, otherwise cancellation time. needs to be checked
            'status': self.parse_order_status(self.safe_string_2(order, 'status', 'state')),
            'symbol': market['symbol'],
            'type': self.parse_order_type(self.safe_string(order, 'type')),
            'timeInForce': self.parse_order_time_in_force(self.safe_string(order, 'timeInForce')),
            'side': self.parse_order_side(self.safe_string(order, 'side')),
            'price': self.safe_number(order, 'price'),
            'stopPrice': self.safe_number_2(order, 'stopPrice', 'triggerPrice'),
            'triggerPrice': self.safe_number_2(order, 'stopPrice', 'triggerPrice'),
            'average': self.safe_number(order, 'dealAvgPrice'),
            'amount': self.safe_number_2(order, 'origQty', 'vol'),
            'cost': self.safe_number(order, 'cummulativeQuoteQty'),  # 'cummulativeQuoteQty' vs 'origQuoteOrderQty'
            'filled': self.safe_number_2(order, 'executedQty', 'dealVol'),
            'remaining': None,
            'fee': fee,
            'trades': None,
            'info': order,
        }, market)

    def parse_order_side(self, status):
        statuses = {
            'BUY': 'buy',
            'SELL': 'sell',
            # contracts v1 : TODO
        }
        return self.safe_string(statuses, status, status)

    def parse_order_type(self, status):
        statuses = {
            'MARKET': 'market',
            'LIMIT': 'limit',
            'LIMIT_MAKER': 'limit',
        }
        return self.safe_string(statuses, status, status)

    def parse_order_status(self, status):
        statuses = {
            'NEW': 'open',
            'FILLED': 'closed',
            'CANCELED': 'canceled',
            'PARTIALLY_FILLED': 'open',
            'PARTIALLY_CANCELED': 'canceled',
            # contracts v1
            # '1': 'uninformed',  # TODO: wt?
            '2': 'open',
            '3': 'closed',
            '4': 'canceled',
            # '5': 'invalid',  #  TODO: wt?
        }
        return self.safe_string(statuses, status, status)

    def parse_order_time_in_force(self, status):
        statuses = {
            'GTC': 'GTC',
            'FOK': 'FOK',
            'IOC': 'IOC',
        }
        return self.safe_string(statuses, status, status)

    def fetch_account_helper(self, type, params):
        if type == 'spot':
            return self.spotPrivateGetAccount(params)
            #
            #     {
            #         "makerCommission": "20",
            #         "takerCommission": "20",
            #         "buyerCommission": "0",
            #         "sellerCommission": "0",
            #         "canTrade": True,
            #         "canWithdraw": True,
            #         "canDeposit": True,
            #         "updateTime": null,
            #         "accountType": "SPOT",
            #         "balances": [
            #             {
            #                 "asset": "BTC",
            #                 "free": "0.002",
            #                 "locked": "0"
            #             },
            #             {
            #                 "asset": "USDT",
            #                 "free": "88.120131350620957006",
            #                 "locked": "0"
            #             },
            #         ],
            #         "permissions": [
            #             "SPOT"
            #         ]
            #     }
            #
        elif type == 'swap':
            response = self.contractPrivateGetAccountAssets(params)
            #
            #     {
            #         "success":true,
            #         "code":0,
            #         "data":[
            #            {
            #              "currency":"BSV",
            #              "positionMargin":0,
            #              "availableBalance":0,
            #              "cashBalance":0,
            #              "frozenBalance":0,
            #              "equity":0,
            #              "unrealized":0,
            #              "bonus":0
            #           },
            #         ]
            #     }
            #
            return self.safe_value(response, 'data')

    def fetch_accounts(self, params={}):
        """
        fetch all the accounts associated with a profile
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a dictionary of `account structures <https://docs.ccxt.com/en/latest/manual.html#account-structure>` indexed by the account type
        """
        # TODO: is the below endpoints suitable for fetchAccounts?
        marketType, query = self.handle_market_type_and_params('fetchAccounts', None, params)
        self.load_markets()
        response = self.fetch_account_helper(marketType, query)
        data = self.safe_value(response, 'balances', [])
        result = []
        for i in range(0, len(data)):
            account = data[i]
            currencyId = self.safe_string_2(account, 'asset', 'currency')
            code = self.safe_currency_code(currencyId)
            result.append({
                'id': self.safe_string(account, 'id'),
                'type': self.safe_string(account, 'type'),
                'code': code,
                'info': account,
            })
        return result

    def fetch_trading_fees(self, params={}):
        """
        fetch the trading fees for multiple markets
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/en/latest/manual.html#fee-structure>` indexed by market symbols
        """
        self.load_markets()
        response = self.fetch_account_helper('spot', params)
        makerFee = self.safe_string(response, 'makerCommission')
        takerFee = self.safe_string(response, 'takerCommission')
        makerFee = Precise.string_div(makerFee, '1000')
        takerFee = Precise.string_div(takerFee, '1000')
        result = {}
        for i in range(0, len(self.symbols)):
            symbol = self.symbols[i]
            result[symbol] = {
                'symbol': symbol,
                'maker': self.parse_number(makerFee),
                'taker': self.parse_number(takerFee),
                'percentage': True,
                'tierBased': False,
                'info': response,
            }
        return result

    def parse_balance(self, response, marketType):
        #
        # spot
        #
        #     {
        #         "asset": "USDT",
        #         "free": "0.000000000674",
        #         "locked": "0"
        #     }
        #
        # swap
        #
        #     {
        #         "currency": "BSV",
        #         "positionMargin": 0,
        #         "availableBalance": 0,
        #         "cashBalance": 0,
        #         "frozenBalance": 0,
        #         "equity": 0,
        #         "unrealized": 0,
        #         "bonus": 0
        #     }
        #
        # margin
        #
        #     {
        #         "baseAsset": {
        #             "asset": "BTC",
        #             "borrowEnabled": True,
        #             "borrowed": "0",
        #             "free": "0",
        #             "interest": "0",
        #             "locked": "0",
        #             "netAsset": "0",
        #             "netAssetOfBtc": "0",
        #             "repayEnabled": True,
        #             "totalAsset": "0"
        #         }
        #         "quoteAsset": {
        #             "asset": "USDT",
        #             "borrowEnabled": True,
        #             "borrowed": "0",
        #             "free": "10",
        #             "interest": "0",
        #             "locked": "0",
        #             "netAsset": "10",
        #             "netAssetOfBtc": "0",
        #             "repayEnabled": True,
        #             "totalAsset": "10"
        #         }
        #         "symbol": "BTCUSDT",
        #         "isolatedCreated": True,
        #         "enabled": True,
        #         "marginLevel": "999",
        #         "marginRatio": "9",
        #         "indexPrice": "16741.137068965517241379",
        #         "liquidatePrice": "--",
        #         "liquidateRate": "--",
        #         "tradeEnabled": True
        #     }
        #
        wallet = None
        if marketType == 'margin':
            wallet = self.safe_value(response, 'assets', [])
        elif marketType == 'swap':
            wallet = self.safe_value(response, 'data', [])
        else:
            wallet = self.safe_value(response, 'balances', [])
        result = {'info': response}
        if marketType == 'margin':
            for i in range(0, len(wallet)):
                entry = wallet[i]
                marketId = self.safe_string(entry, 'symbol')
                symbol = self.safe_symbol(marketId, None)
                base = self.safe_value(entry, 'baseAsset', {})
                quote = self.safe_value(entry, 'quoteAsset', {})
                baseCode = self.safe_currency_code(self.safe_string(base, 'asset'))
                quoteCode = self.safe_currency_code(self.safe_string(quote, 'asset'))
                subResult = {}
                subResult[baseCode] = self.parse_balance_helper(base)
                subResult[quoteCode] = self.parse_balance_helper(quote)
                result[symbol] = self.safe_balance(subResult)
            return result
        elif marketType == 'swap':
            for i in range(0, len(wallet)):
                entry = wallet[i]
                currencyId = self.safe_string(entry, 'currency')
                code = self.safe_currency_code(currencyId)
                account = self.account()
                account['free'] = self.safe_string(entry, 'availableBalance')
                account['used'] = self.safe_string(entry, 'frozenBalance')
                result[code] = account
            return self.safe_balance(result)
        else:
            for i in range(0, len(wallet)):
                entry = wallet[i]
                currencyId = self.safe_string(entry, 'asset')
                code = self.safe_currency_code(currencyId)
                account = self.account()
                account['free'] = self.safe_string(entry, 'free')
                account['used'] = self.safe_string(entry, 'locked')
                result[code] = account
            return self.safe_balance(result)

    def parse_balance_helper(self, entry):
        account = self.account()
        account['used'] = self.safe_string(entry, 'locked')
        account['free'] = self.safe_string(entry, 'free')
        account['total'] = self.safe_string(entry, 'totalAsset')
        debt = self.safe_string(entry, 'borrowed')
        interest = self.safe_string(entry, 'interest')
        account['debt'] = Precise.string_add(debt, interest)
        return account

    def fetch_balance(self, params={}):
        """
        query for balance and get the amount of funds available for trading or funds locked in orders
        see https://mxcdevelop.github.io/apidocs/spot_v3_en/#account-information
        see https://mxcdevelop.github.io/apidocs/contract_v1_en/#get-all-informations-of-user-39-s-asset
        see https://mxcdevelop.github.io/apidocs/spot_v3_en/#isolated-account
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :param str|None params['symbols']:  # required for margin, market id's separated by commas
        :returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>`
        """
        self.load_markets()
        marketType = None
        request = {}
        marketType, params = self.handle_market_type_and_params('fetchBalance', None, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'spotPrivateGetAccount',
            'swap': 'contractPrivateGetAccountAssets',
            'margin': 'spotPrivateGetMarginIsolatedAccount',
        })
        marginMode = self.safe_string(params, 'marginMode')
        isMargin = self.safe_value(params, 'margin', False)
        if (marginMode is not None) or (isMargin) or (marketType == 'margin'):
            parsedSymbols = None
            symbol = self.safe_string(params, 'symbol')
            if symbol is None:
                symbols = self.safe_value(params, 'symbols')
                if symbols is not None:
                    parsedSymbols = ','.join(self.market_ids(symbols))
            else:
                market = self.market(symbol)
                parsedSymbols = market['id']
            self.check_required_argument('fetchBalance', parsedSymbols, 'symbol or symbols')
            method = 'spotPrivateGetMarginIsolatedAccount'
            marketType = 'margin'
            request['symbols'] = parsedSymbols
        params = self.omit(params, ['margin', 'marginMode', 'symbol', 'symbols'])
        response = getattr(self, method)(self.extend(request, params))
        #
        # spot
        #
        #     {
        #         "makerCommission": 0,
        #         "takerCommission": 20,
        #         "buyerCommission": 0,
        #         "sellerCommission": 0,
        #         "canTrade": True,
        #         "canWithdraw": True,
        #         "canDeposit": True,
        #         "updateTime": null,
        #         "accountType": "SPOT",
        #         "balances": [
        #             {
        #                 "asset": "USDT",
        #                 "free": "0.000000000674",
        #                 "locked": "0"
        #             },
        #         ],
        #         "permissions": ["SPOT"]
        #     }
        #
        # swap
        #
        #     {
        #         "success": True,
        #         "code": 0,
        #         "data": [
        #             {
        #                 "currency": "BSV",
        #                 "positionMargin": 0,
        #                 "availableBalance": 0,
        #                 "cashBalance": 0,
        #                 "frozenBalance": 0,
        #                 "equity": 0,
        #                 "unrealized": 0,
        #                 "bonus": 0
        #             },
        #         ]
        #     }
        #
        # margin
        #
        #     {
        #         "assets": [
        #             {
        #                 "baseAsset": {
        #                     "asset": "BTC",
        #                     "borrowEnabled": True,
        #                     "borrowed": "0",
        #                     "free": "0",
        #                     "interest": "0",
        #                     "locked": "0",
        #                     "netAsset": "0",
        #                     "netAssetOfBtc": "0",
        #                     "repayEnabled": True,
        #                     "totalAsset": "0"
        #                 },
        #                 "quoteAsset": {
        #                     "asset": "USDT",
        #                     "borrowEnabled": True,
        #                     "borrowed": "0",
        #                     "free": "10",
        #                     "interest": "0",
        #                     "locked": "0",
        #                     "netAsset": "10",
        #                     "netAssetOfBtc": "0",
        #                     "repayEnabled": True,
        #                     "totalAsset": "10"
        #                 },
        #                 "symbol": "BTCUSDT",
        #                 "isolatedCreated": True,
        #                 "enabled": True,
        #                 "marginLevel": "999",
        #                 "marginRatio": "9",
        #                 "indexPrice": "16741.137068965517241379",
        #                 "liquidatePrice": "--",
        #                 "liquidateRate": "--",
        #                 "tradeEnabled": True
        #             }
        #         ]
        #     }
        #
        return self.parse_balance(response, marketType)

    def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
        """
        fetch all trades made by the user
        :param str symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch trades for
        :param int|None limit: the maximum number of trades structures to retrieve
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchMyTrades() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        marketType, query = self.handle_market_type_and_params('fetchMyTrades', market, params)
        request = {
            'symbol': market['id'],
        }
        trades = None
        if marketType == 'spot':
            if since is not None:
                request['start_time'] = since
            if limit is not None:
                request['limit'] = limit
            trades = self.spotPrivateGetMyTrades(self.extend(request, query))
            #
            # spot
            #
            #     [
            #         {
            #             "symbol": "BTCUSDT",
            #             "id": "133948532984922113",
            #             "orderId": "133948532531949568",
            #             "orderListId": "-1",
            #             "price": "41995.51",
            #             "qty": "0.0002",
            #             "quoteQty": "8.399102",
            #             "commission": "0.016798204",
            #             "commissionAsset": "USDT",
            #             "time": "1647718055000",
            #             "isBuyer": True,
            #             "isMaker": False,
            #             "isBestMatch": True
            #         }
            #     ]
            #
        else:
            if since is not None:
                request['start_time'] = since
                end = self.safe_integer(params, 'end_time')
                if end is None:
                    request['end_time'] = self.sum(since, self.options['maxTimeTillEnd'])
            if limit is not None:
                request['page_size'] = limit
            response = self.contractPrivateGetOrderListOrderDeals(self.extend(request, query))
            #
            #     {
            #         "success": True,
            #         "code": "0",
            #         "data": [
            #             {
            #                 "id": "299444585",
            #                 "symbol": "STEPN_USDT",
            #                 "side": "1",
            #                 "vol": "1",
            #                 "price": "2.45455",
            #                 "feeCurrency": "USDT",
            #                 "fee": "0.00147273",
            #                 "timestamp": "1648924557000",
            #                 "profit": "0",
            #                 "category": "1",
            #                 "orderId": "265307163526610432",
            #                 "positionMode": "1",
            #                 "taker": True
            #             }
            #         ]
            #     }
            #
            trades = self.safe_value(response, 'data')
        return self.parse_trades(trades, market, since, limit)

    def fetch_order_trades(self, id, symbol=None, since=None, limit=None, params={}):
        """
        fetch all the trades made from a single order
        :param str id: order id
        :param str|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch trades for
        :param int|None limit: the maximum number of trades to retrieve
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
        """
        self.load_markets()
        request = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
        marketType, query = self.handle_market_type_and_params('fetchOrderTrades', market, params)
        trades = None
        if marketType == 'spot':
            if symbol is None:
                raise ArgumentsRequired(self.id + ' fetchOrderTrades() requires a symbol argument')
            request['symbol'] = market['id']
            request['orderId'] = id
            trades = self.spotPrivateGetMyTrades(self.extend(request, query))
            #
            # spot
            #
            #     [
            #         {
            #             "symbol": "BTCUSDT",
            #             "id": "133948532984922113",
            #             "orderId": "133948532531949568",
            #             "orderListId": "-1",
            #             "price": "41995.51",
            #             "qty": "0.0002",
            #             "quoteQty": "8.399102",
            #             "commission": "0.016798204",
            #             "commissionAsset": "USDT",
            #             "time": "1647718055000",
            #             "isBuyer": True,
            #             "isMaker": False,
            #             "isBestMatch": True
            #         }
            #     ]
            #
        else:
            request['order_id'] = id
            response = self.contractPrivateGetOrderDealDetailsOrderId(self.extend(request, query))
            #
            #     {
            #         "success": True,
            #         "code": "0",
            #         "data": [
            #             {
            #                 "id": "299444585",
            #                 "symbol": "STEPN_USDT",
            #                 "side": "1",
            #                 "vol": "1",
            #                 "price": "2.45455",
            #                 "feeCurrency": "USDT",
            #                 "fee": "0.00147273",
            #                 "timestamp": "1648924557000",
            #                 "profit": "0",
            #                 "category": "1",
            #                 "orderId": "265307163526610432",
            #                 "positionMode": "1",
            #                 "taker": True
            #             }
            #         ]
            #     }
            #
            trades = self.safe_value(response, 'data')
        return self.parse_trades(trades, market, since, limit, query)

    def modify_margin_helper(self, symbol, amount, addOrReduce, params={}):
        positionId = self.safe_integer(params, 'positionId')
        if positionId is None:
            raise ArgumentsRequired(self.id + ' modifyMarginHelper() requires a positionId parameter')
        self.load_markets()
        request = {
            'positionId': positionId,
            'amount': amount,
            'type': addOrReduce,
        }
        response = self.contractPrivatePostPositionChangeMargin(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #         "code": 0
        #     }
        return response

    def reduce_margin(self, symbol, amount, params={}):
        """
        remove margin from a position
        :param str symbol: unified market symbol
        :param float amount: the amount of margin to remove
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/en/latest/manual.html#reduce-margin-structure>`
        """
        return self.modify_margin_helper(symbol, amount, 'SUB', params)

    def add_margin(self, symbol, amount, params={}):
        """
        add margin
        :param str symbol: unified market symbol
        :param float amount: amount of margin to add
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/en/latest/manual.html#add-margin-structure>`
        """
        return self.modify_margin_helper(symbol, amount, 'ADD', params)

    def set_leverage(self, leverage, symbol=None, params={}):
        """
        set the level of leverage for a market
        :param float leverage: the rate of leverage
        :param str|None symbol: unified market symbol
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: response from the exchange
        """
        self.load_markets()
        request = {
            'leverage': leverage,
        }
        positionId = self.safe_integer(params, 'positionId')
        if positionId is None:
            openType = self.safe_number(params, 'openType')  # 1 or 2
            positionType = self.safe_number(params, 'positionType')  # 1 or 2
            market = self.market(symbol) if (symbol is not None) else None
            if (openType is None) or (positionType is None) or (market is None):
                raise ArgumentsRequired(self.id + ' setLeverage() requires a positionId parameter or a symbol argument with openType and positionType parameters, use openType 1 or 2 for isolated or cross margin respectively, use positionType 1 or 2 for long or short positions')
            else:
                request['openType'] = openType
                request['symbol'] = market['symbol']
                request['positionType'] = positionType
        else:
            request['positionId'] = positionId
        return self.contractPrivatePostPositionChangeLeverage(self.extend(request, params))

    def fetch_funding_history(self, symbol=None, since=None, limit=None, params={}):
        """
        fetch the history of funding payments paid and received on self account
        :param str|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch funding history for
        :param int|None limit: the maximum number of funding history structures to retrieve
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a `funding history structure <https://docs.ccxt.com/en/latest/manual.html#funding-history-structure>`
        """
        self.load_markets()
        market = None
        request = {
            # 'symbol': market['id'],
            # 'position_id': positionId,
            # 'page_num': 1,
            # 'page_size': limit,  # default 20, max 100
        }
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if limit is not None:
            request['page_size'] = limit
        response = self.contractPrivateGetPositionFundingRecords(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #         "code": 0,
        #         "data": {
        #             "pageSize": 20,
        #             "totalCount": 2,
        #             "totalPage": 1,
        #             "currentPage": 1,
        #             "resultList": [
        #                 {
        #                     "id": 7423910,
        #                     "symbol": "BTC_USDT",
        #                     "positionType": 1,
        #                     "positionValue": 29.30024,
        #                     "funding": 0.00076180624,
        #                     "rate": -0.000026,
        #                     "settleTime": 1643299200000
        #                 },
        #                 {
        #                     "id": 7416473,
        #                     "symbol": "BTC_USDT",
        #                     "positionType": 1,
        #                     "positionValue": 28.9188,
        #                     "funding": 0.0014748588,
        #                     "rate": -0.000051,
        #                     "settleTime": 1643270400000
        #                 }
        #             ]
        #         }
        #     }
        #
        data = self.safe_value(response, 'data', {})
        resultList = self.safe_value(data, 'resultList', [])
        result = []
        for i in range(0, len(resultList)):
            entry = resultList[i]
            timestamp = self.safe_integer(entry, 'settleTime')
            result.append({
                'info': entry,
                'symbol': symbol,
                'code': None,
                'timestamp': timestamp,
                'datetime': self.iso8601(timestamp),
                'id': self.safe_number(entry, 'id'),
                'amount': self.safe_number(entry, 'funding'),
            })
        return result

    def parse_funding_rate(self, contract, market=None):
        #
        #     {
        #         "symbol": "BTC_USDT",
        #         "fundingRate": 0.000014,
        #         "maxFundingRate": 0.003,
        #         "minFundingRate": -0.003,
        #         "collectCycle": 8,
        #         "nextSettleTime": 1643241600000,
        #         "timestamp": 1643240373359
        #     }
        #
        nextFundingRate = self.safe_number(contract, 'fundingRate')
        nextFundingTimestamp = self.safe_integer(contract, 'nextSettleTime')
        marketId = self.safe_string(contract, 'symbol')
        symbol = self.safe_symbol(marketId, market)
        timestamp = self.safe_integer(contract, 'timestamp')
        datetime = self.iso8601(timestamp)
        return {
            'info': contract,
            'symbol': symbol,
            'markPrice': None,
            'indexPrice': None,
            'interestRate': None,
            'estimatedSettlePrice': None,
            'timestamp': timestamp,
            'datetime': datetime,
            'fundingRate': nextFundingRate,
            'fundingTimestamp': nextFundingTimestamp,
            'fundingDatetime': self.iso8601(nextFundingTimestamp),
            'nextFundingRate': None,
            'nextFundingTimestamp': None,
            'nextFundingDatetime': None,
            'previousFundingRate': None,
            'previousFundingTimestamp': None,
            'previousFundingDatetime': None,
        }

    def fetch_funding_rate(self, symbol, params={}):
        """
        fetch the current funding rate
        :param str symbol: unified market symbol
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/en/latest/manual.html#funding-rate-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = self.contractPublicGetFundingRateSymbol(self.extend(request, params))
        #
        #     {
        #         "success": True,
        #         "code": 0,
        #         "data": {
        #             "symbol": "BTC_USDT",
        #             "fundingRate": 0.000014,
        #             "maxFundingRate": 0.003,
        #             "minFundingRate": -0.003,
        #             "collectCycle": 8,
        #             "nextSettleTime": 1643241600000,
        #             "timestamp": 1643240373359
        #         }
        #     }
        #
        result = self.safe_value(response, 'data', {})
        return self.parse_funding_rate(result, market)

    def fetch_funding_rate_history(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches historical funding rate prices
        :param str|None symbol: unified symbol of the market to fetch the funding rate history for
        :param int|None since: not used by mexc, but filtered internally by ccxt
        :param int|None limit: mexc limit is page_size default 20, maximum is 100
        :param dict params: extra parameters specific to the mexc api endpoint
        :returns [dict]: a list of `funding rate structures <https://docs.ccxt.com/en/latest/manual.html?#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 = {
            'symbol': market['id'],
            # 'page_size': limit,  # optional
            # 'page_num': 1,  # optional, current page number, default is 1
        }
        if limit is not None:
            request['page_size'] = limit
        response = self.contractPublicGetFundingRateHistory(self.extend(request, params))
        #
        #    {
        #        "success": True,
        #        "code": 0,
        #        "data": {
        #            "pageSize": 2,
        #            "totalCount": 21,
        #            "totalPage": 11,
        #            "currentPage": 1,
        #            "resultList": [
        #                {
        #                    "symbol": "BTC_USDT",
        #                    "fundingRate": 0.000266,
        #                    "settleTime": 1609804800000
        #                },
        #                {
        #                    "symbol": "BTC_USDT",
        #                    "fundingRate": 0.00029,
        #                    "settleTime": 1609776000000
        #                }
        #            ]
        #        }
        #    }
        #
        data = self.safe_value(response, 'data')
        result = self.safe_value(data, 'resultList', [])
        rates = []
        for i in range(0, len(result)):
            entry = result[i]
            marketId = self.safe_string(entry, 'symbol')
            symbol = self.safe_symbol(marketId)
            timestamp = self.safe_integer(entry, 'settleTime')
            rates.append({
                'info': entry,
                'symbol': symbol,
                'fundingRate': self.safe_number(entry, 'fundingRate'),
                'timestamp': timestamp,
                'datetime': self.iso8601(timestamp),
            })
        sorted = self.sort_by(rates, 'timestamp')
        return self.filter_by_symbol_since_limit(sorted, market['symbol'], since, limit)

    def fetch_leverage_tiers(self, symbols=None, params={}):
        """
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes
        :param [str]|None symbols: list of unified market symbols
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a dictionary of `leverage tiers structures <https://docs.ccxt.com/en/latest/manual.html#leverage-tiers-structure>`, indexed by market symbols
        """
        self.load_markets()
        response = self.contractPublicGetDetail(params)
        #
        #     {
        #         "success":true,
        #         "code":0,
        #         "data":[
        #             {
        #                 "symbol": "BTC_USDT",
        #                 "displayName": "BTC_USDT永续",
        #                 "displayNameEn": "BTC_USDT SWAP",
        #                 "positionOpenType": 3,
        #                 "baseCoin": "BTC",
        #                 "quoteCoin": "USDT",
        #                 "settleCoin": "USDT",
        #                 "contractSize": 0.0001,
        #                 "minLeverage": 1,
        #                 "maxLeverage": 125,
        #                 "priceScale": 2,
        #                 "volScale": 0,
        #                 "amountScale": 4,
        #                 "priceUnit": 0.5,
        #                 "volUnit": 1,
        #                 "minVol": 1,
        #                 "maxVol": 1000000,
        #                 "bidLimitPriceRate": 0.1,
        #                 "askLimitPriceRate": 0.1,
        #                 "takerFeeRate": 0.0006,
        #                 "makerFeeRate": 0.0002,
        #                 "maintenanceMarginRate": 0.004,
        #                 "initialMarginRate": 0.008,
        #                 "riskBaseVol": 10000,
        #                 "riskIncrVol": 200000,
        #                 "riskIncrMmr": 0.004,
        #                 "riskIncrImr": 0.004,
        #                 "riskLevelLimit": 5,
        #                 "priceCoefficientVariation": 0.1,
        #                 "indexOrigin": ["BINANCE","GATEIO","HUOBI","MXC"],
        #                 "state": 0,  # 0 enabled, 1 delivery, 2 completed, 3 offline, 4 pause
        #                 "isNew": False,
        #                 "isHot": True,
        #                 "isHidden": False
        #             },
        #             ...
        #         ]
        #     }
        #
        data = self.safe_value(response, 'data')
        return self.parse_leverage_tiers(data, symbols, 'symbol')

    def parse_market_leverage_tiers(self, info, market):
        """
            @param info: Exchange response for 1 market
            {
                "symbol": "BTC_USDT",
                "displayName": "BTC_USDT永续",
                "displayNameEn": "BTC_USDT SWAP",
                "positionOpenType": 3,
                "baseCoin": "BTC",
                "quoteCoin": "USDT",
                "settleCoin": "USDT",
                "contractSize": 0.0001,
                "minLeverage": 1,
                "maxLeverage": 125,
                "priceScale": 2,
                "volScale": 0,
                "amountScale": 4,
                "priceUnit": 0.5,
                "volUnit": 1,
                "minVol": 1,
                "maxVol": 1000000,
                "bidLimitPriceRate": 0.1,
                "askLimitPriceRate": 0.1,
                "takerFeeRate": 0.0006,
                "makerFeeRate": 0.0002,
                "maintenanceMarginRate": 0.004,
                "initialMarginRate": 0.008,
                "riskBaseVol": 10000,
                "riskIncrVol": 200000,
                "riskIncrMmr": 0.004,
                "riskIncrImr": 0.004,
                "riskLevelLimit": 5,
                "priceCoefficientVariation": 0.1,
                "indexOrigin": ["BINANCE","GATEIO","HUOBI","MXC"],
                "state": 0,  # 0 enabled, 1 delivery, 2 completed, 3 offline, 4 pause
                "isNew": False,
                "isHot": True,
                "isHidden": False
            @param market: CCXT market
        """
        maintenanceMarginRate = self.safe_string(info, 'maintenanceMarginRate')
        initialMarginRate = self.safe_string(info, 'initialMarginRate')
        maxVol = self.safe_string(info, 'maxVol')
        riskIncrVol = self.safe_string(info, 'riskIncrVol')
        riskIncrMmr = self.safe_string(info, 'riskIncrMmr')
        riskIncrImr = self.safe_string(info, 'riskIncrImr')
        floor = '0'
        tiers = []
        quoteId = self.safe_string(info, 'quoteCoin')
        while(Precise.string_lt(floor, maxVol)):
            cap = Precise.string_add(floor, riskIncrVol)
            tiers.append({
                'tier': self.parse_number(Precise.string_div(cap, riskIncrVol)),
                'currency': self.safe_currency_code(quoteId),
                'notionalFloor': self.parse_number(floor),
                'notionalCap': self.parse_number(cap),
                'maintenanceMarginRate': self.parse_number(maintenanceMarginRate),
                'maxLeverage': self.parse_number(Precise.string_div('1', initialMarginRate)),
                'info': info,
            })
            initialMarginRate = Precise.string_add(initialMarginRate, riskIncrImr)
            maintenanceMarginRate = Precise.string_add(maintenanceMarginRate, riskIncrMmr)
            floor = cap
        return tiers

    def parse_deposit_address(self, depositAddress, currency=None):
        #
        #     {"chain":"ERC-20","address":"0x55cbd73db24eafcca97369e3f2db74b2490586e6"},
        #     {"chain":"MATIC","address":"0x05aa3236f1970eae0f8feb17ec19435b39574d74"},
        #     {"chain":"TRC20","address":"TGaPfhW41EXD3sAfs1grLF6DKfugfqANNw"},
        #     {"chain":"SOL","address":"5FSpUKuh2gjw4mF89T2e7sEjzUA1SkRKjBChFqP43KhV"},
        #     {"chain":"ALGO","address":"B3XTZND2JJTSYR7R2TQVCUDT4QSSYVAIZYDPWVBX34DGAYATBU3AUV43VU"}
        #
        #
        address = self.safe_string(depositAddress, 'address')
        code = self.safe_currency_code(None, currency)
        networkId = self.safe_string(depositAddress, 'chain')
        network = self.safe_network(networkId)
        self.check_address(address)
        return {
            'currency': code,
            'address': address,
            'tag': None,
            'network': network,
            'info': depositAddress,
        }

    def fetch_deposit_addresses_by_network(self, code, params={}):
        """
        fetch a dictionary of addresses for a currency, indexed by network
        see https://mxcdevelop.github.io/apidocs/spot_v3_en/#deposit-address-supporting-network
        :param str code: unified currency code of the currency for the deposit address
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a dictionary of `address structures <https://docs.ccxt.com/en/latest/manual.html#address-structure>` indexed by the network
        """
        self.load_markets()
        currency = self.currency(code)
        request = {
            'coin': currency['id'],
        }
        response = self.spotPrivateGetCapitalDepositAddress(self.extend(request, params))
        result = []
        for i in range(0, len(response)):
            depositAddress = response[i]
            coin = self.safe_string(depositAddress, 'coin')
            currency = self.currency(coin)
            networkId = self.safe_string(depositAddress, 'network')
            network = self.safe_network(networkId)
            address = self.safe_string(depositAddress, 'address', None)
            tag = self.safe_string_2(depositAddress, 'tag', 'memo', None)
            result.append({
                'currency': currency['id'],
                'network': network,
                'address': address,
                'tag': tag,
            })
        return result

    def fetch_deposit_address(self, code, params={}):
        """
        fetch the deposit address for a currency associated with self account
        see https://mxcdevelop.github.io/apidocs/spot_v3_en/#deposit-address-supporting-network
        :param str code: unified currency code
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>`
        """
        rawNetwork = self.safe_string_upper(params, 'network')
        params = self.omit(params, 'network')
        response = self.fetch_deposit_addresses_by_network(code, params)
        if rawNetwork is not None:
            for i in range(0, len(response)):
                depositAddress = response[i]
                network = self.safe_string_upper(depositAddress, 'network')
                if rawNetwork == network:
                    return depositAddress
        result = self.safe_value(response, 0)
        if result is None:
            raise InvalidAddress(self.id + ' fetchDepositAddress() cannot find a deposit address for ' + code + ', consider creating one using the MEXC platform')
        return result

    def fetch_deposits(self, code=None, since=None, limit=None, params={}):
        """
        fetch all deposits made to an account
        see https://mxcdevelop.github.io/apidocs/spot_v3_en/#deposit-history-supporting-network
        :param str code: unified currency code
        :param int|None since: the earliest time in ms to fetch deposits for
        :param int|None limit: the maximum number of deposits structures to retrieve
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        if code is None:
            raise ArgumentsRequired(self.id + ' fetchDeposits() requires a currency code argument')
        self.load_markets()
        request = {
            # 'coin': currency['id'] + network example: USDT-TRX,
            # 'status': 'status',
            # 'startTime': since,  # default 90 days
            # 'endTime': self.milliseconds(),
            # 'limit': limit,  # default 1000, maximum 1000
        }
        currency = None
        rawNetwork = self.safe_string(params, 'network')
        params = self.omit(params, 'network')
        if rawNetwork is None:
            raise ArgumentsRequired(self.id + ' fetchDeposits() requires a network parameter when the currency is specified')
        # currently mexc does not have network names unified so for certain things we might need TRX or TRC-20
        # due to that I'm applying the network parameter directly so the user can control it on its side
        currency = self.currency(code)
        request['coin'] = currency['id'] + '-' + rawNetwork
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            if limit > 1000:
                raise ExchangeError('This exchange supports a maximum limit of 1000')
            request['limit'] = limit
        response = self.spotPrivateGetCapitalDepositHisrec(self.extend(request, params))
        #
        # [
        #     {
        #         amount: '10',
        #         coin: 'USDC-TRX',
        #         network: 'TRX',
        #         status: '5',
        #         address: 'TSMcEDDvkqY9dz8RkFnrS86U59GwEZjfvh',
        #         addressTag: null,
        #         txId: '51a8f49e6f03f2c056e71fe3291aa65e1032880be855b65cecd0595a1b8af95b',
        #         insertTime: '1664805021000',
        #         unlockConfirm: '200',
        #         confirmTimes: '203'
        #     }
        # ]
        #
        return self.parse_transactions(response, currency, since, limit)

    def fetch_withdrawals(self, code=None, since=None, limit=None, params={}):
        """
        fetch all withdrawals made from an account
        see https://mxcdevelop.github.io/apidocs/spot_v3_en/#withdraw-history-supporting-network
        :param str code: unified currency code
        :param int|None since: the earliest time in ms to fetch withdrawals for
        :param int|None limit: the maximum number of withdrawals structures to retrieve
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        if code is None:
            raise ArgumentsRequired(self.id + ' fetchWithdrawals() requires a currency code argument')
        self.load_markets()
        request = {
            # 'coin': currency['id'],
            # 'status': 'status',
            # 'startTime': since,  # default 90 days
            # 'endTime': self.milliseconds(),
            # 'limit': limit,  # default 1000, maximum 1000
        }
        currency = self.currency(code)
        request['coin'] = currency['id']
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            if limit > 1000:
                raise ExchangeError('This exchange supports a maximum limit of 1000')
            request['limit'] = limit
        response = self.spotPrivateGetCapitalWithdrawHistory(self.extend(request, params))
        #
        # [
        #     {
        #       id: 'adcd1c8322154de691b815eedcd10c42',
        #       txId: '0xc8c918cd69b2246db493ef6225a72ffdc664f15b08da3e25c6879b271d05e9d0',
        #       coin: 'USDC-MATIC',
        #       network: 'MATIC',
        #       address: '0xeE6C7a415995312ED52c53a0f8f03e165e0A5D62',
        #       amount: '2',
        #       transferType: '0',
        #       status: '7',
        #       transactionFee: '1',
        #       confirmNo: null,
        #       applyTime: '1664882739000',
        #       remark: ''
        #     }
        # ]
        #
        return self.parse_transactions(response, currency, since, limit)

    def parse_transaction(self, transaction, currency=None):
        #
        # fetchDeposits
        #
        # {
        #     amount: '10',
        #     coin: 'USDC-TRX',
        #     network: 'TRX',
        #     status: '5',
        #     address: 'TSMcEDDvkqY9dz8RkFnrS86U59GwEZjfvh',
        #     addressTag: null,
        #     txId: '51a8f49e6f03f2c056e71fe3291aa65e1032880be855b65cecd0595a1b8af95b',
        #     insertTime: '1664805021000',
        #     unlockConfirm: '200',
        #     confirmTimes: '203'
        # }
        #
        # fetchWithdrawals
        #
        # {
        #     id: 'adcd1c8322154de691b815eedcd10c42',
        #     txId: '0xc8c918cd69b2246db493ef6225a72ffdc664f15b08da3e25c6879b271d05e9d0',
        #     coin: 'USDC-MATIC',
        #     network: 'MATIC',
        #     address: '0xeE6C7a415995312ED52c53a0f8f03e165e0A5D62',
        #     amount: '2',
        #     transferType: '0',
        #     status: '7',
        #     transactionFee: '1',
        #     confirmNo: null,
        #     applyTime: '1664882739000',
        #     remark: ''
        #   }
        #
        # withdraw
        #
        #     {
        #         "withdrawId":"25fb2831fb6d4fc7aa4094612a26c81d"
        #     }
        #
        id = self.safe_string(transaction, 'id')
        type = 'deposit' if (id is None) else 'withdrawal'
        timestamp = self.safe_integer_2(transaction, 'insertTime', 'applyTime')
        currencyId = self.safe_string(transaction, 'currency')
        network = self.safe_string(transaction, 'network')
        code = self.safe_currency_code(currencyId, currency)
        status = self.parse_transaction_status(self.safe_string(transaction, 'status'))
        amountString = self.safe_string(transaction, 'amount')
        address = self.safe_string(transaction, 'address')
        txid = self.safe_string(transaction, 'txId')
        fee = None
        feeCostString = self.safe_string(transaction, 'transactionFee')
        if feeCostString is not None:
            fee = {
                'cost': self.parse_number(feeCostString),
                'currency': code,
            }
        if type == 'withdrawal':
            # mexc withdrawal amount includes the fee
            amountString = Precise.string_sub(amountString, feeCostString)
        return {
            'info': transaction,
            'id': id,
            'txid': txid,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'network': network,
            'address': address,
            'addressTo': address,
            'addressFrom': None,
            'tag': self.safe_string(transaction, 'memo'),
            'tagTo': None,
            'tagFrom': None,
            'type': type,
            'amount': self.parse_number(amountString),
            'currency': code,
            'status': status,
            'updated': None,
            'fee': fee,
        }

    def parse_transaction_status(self, status):
        statuses = {
            'WAIT': 'pending',
            'WAIT_PACKAGING': 'pending',
            'SUCCESS': 'ok',
        }
        return self.safe_string(statuses, status, status)

    def fetch_position(self, symbol, params={}):
        """
        fetch data on a single open contract trade position
        :param str symbol: unified market symbol of the market the position is held in, default is None
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = self.fetch_positions(None, self.extend(request, params))
        return self.safe_value(response, 0)

    def fetch_positions(self, symbols=None, params={}):
        """
        fetch all open positions
        :param [str]|None symbols: list of unified market symbols
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns [dict]: a list of `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        """
        self.load_markets()
        response = self.contractPrivateGetPositionOpenPositions(params)
        #
        #     {
        #         "success": True,
        #         "code": 0,
        #         "data": [
        #             {
        #                 "positionId": 1394650,
        #                 "symbol": "ETH_USDT",
        #                 "positionType": 1,
        #                 "openType": 1,
        #                 "state": 1,
        #                 "holdVol": 1,
        #                 "frozenVol": 0,
        #                 "closeVol": 0,
        #                 "holdAvgPrice": 1217.3,
        #                 "openAvgPrice": 1217.3,
        #                 "closeAvgPrice": 0,
        #                 "liquidatePrice": 1211.2,
        #                 "oim": 0.1290338,
        #                 "im": 0.1290338,
        #                 "holdFee": 0,
        #                 "realised": -0.0073,
        #                 "leverage": 100,
        #                 "createTime": 1609991676000,
        #                 "updateTime": 1609991676000,
        #                 "autoAddIm": False
        #             }
        #         ]
        #     }
        #
        data = self.safe_value(response, 'data', [])
        return self.parse_positions(data, symbols)

    def parse_position(self, position, market=None):
        #
        #     {
        #         "positionId": 1394650,
        #         "symbol": "ETH_USDT",
        #         "positionType": 1,
        #         "openType": 1,
        #         "state": 1,
        #         "holdVol": 1,
        #         "frozenVol": 0,
        #         "closeVol": 0,
        #         "holdAvgPrice": 1217.3,
        #         "openAvgPrice": 1217.3,
        #         "closeAvgPrice": 0,
        #         "liquidatePrice": 1211.2,
        #         "oim": 0.1290338,
        #         "im": 0.1290338,
        #         "holdFee": 0,
        #         "realised": -0.0073,
        #         "leverage": 100,
        #         "createTime": 1609991676000,
        #         "updateTime": 1609991676000,
        #         "autoAddIm": False
        #     }
        #
        market = self.safe_market(self.safe_string(position, 'symbol'), market)
        symbol = market['symbol']
        contracts = self.safe_string(position, 'holdVol')
        entryPrice = self.safe_number(position, 'openAvgPrice')
        initialMargin = self.safe_string(position, 'im')
        rawSide = self.safe_string(position, 'positionType')
        side = 'long' if (rawSide == '1') else 'short'
        openType = self.safe_string(position, 'margin_mode')
        marginType = 'isolated' if (openType == '1') else 'cross'
        leverage = self.safe_number(position, 'leverage')
        liquidationPrice = self.safe_number(position, 'liquidatePrice')
        timestamp = self.safe_number(position, 'updateTime')
        return {
            'info': position,
            'id': None,
            'symbol': symbol,
            'contracts': self.parse_number(contracts),
            'contractSize': None,
            'entryPrice': entryPrice,
            'collateral': None,
            'side': side,
            'unrealizedProfit': None,
            'leverage': self.parse_number(leverage),
            'percentage': None,
            'marginType': marginType,
            'notional': None,
            'markPrice': None,
            'liquidationPrice': liquidationPrice,
            'initialMargin': self.parse_number(initialMargin),
            'initialMarginPercentage': None,
            'maintenanceMargin': None,
            'maintenanceMarginPercentage': None,
            'marginRatio': None,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
        }

    def fetch_transfer(self, id, since=None, limit=None, params={}):
        marketType, query = self.handle_market_type_and_params('fetchTransfer', None, params)
        self.load_markets()
        if marketType == 'spot':
            request = {
                'transact_id': id,
            }
            response = self.spot2PrivateGetAssetInternalTransferInfo(self.extend(request, query))
            #
            #     {
            #         code: '200',
            #         data: {
            #             currency: 'USDT',
            #             amount: '1',
            #             transact_id: '954877a2ef54499db9b28a7cf9ebcf41',
            #             from: 'MAIN',
            #             to: 'CONTRACT',
            #             transact_state: 'SUCCESS'
            #         }
            #     }
            #
            data = self.safe_value(response, 'data', {})
            return self.parse_transfer(data)
        elif marketType == 'swap':
            raise BadRequest(self.id + ' fetchTransfer() is not supported for ' + marketType)

    def fetch_transfers(self, code=None, since=None, limit=None, params={}):
        """
        fetch a history of internal transfers made on an account
        :param str|None code: unified currency code of the currency transferred
        :param int|None since: the earliest time in ms to fetch transfers for
        :param int|None limit: the maximum number of  transfers structures to retrieve
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns [dict]: a list of `transfer structures <https://docs.ccxt.com/en/latest/manual.html#transfer-structure>`
        """
        marketType, query = self.handle_market_type_and_params('fetchTransfers', None, params)
        self.load_markets()
        request = {}
        currency = None
        resultList = None
        if code is not None:
            currency = self.currency(code)
            request['currency'] = currency['id']
        if marketType == 'spot':
            if since is not None:
                request['start_time'] = since
            if limit is not None:
                if limit > 50:
                    raise ExchangeError('This exchange supports a maximum limit of 50')
                request['page-size'] = limit
            response = self.spot2PrivateGetAssetInternalTransferRecord(self.extend(request, query))
            #
            #     {
            #         code: '200',
            #         data: {
            #             total_page: '1',
            #             total_size: '5',
            #             result_list: [{
            #                     currency: 'USDT',
            #                     amount: '1',
            #                     transact_id: '954877a2ef54499db9b28a7cf9ebcf41',
            #                     from: 'MAIN',
            #                     to: 'CONTRACT',
            #                     transact_state: 'SUCCESS'
            #                 },
            #                 ...
            #             ]
            #         }
            #     }
            #
            data = self.safe_value(response, 'data', {})
            resultList = self.safe_value(data, 'result_list', [])
        elif marketType == 'swap':
            if limit is not None:
                request['page_size'] = limit
            response = self.contractPrivateGetAccountTransferRecord(self.extend(request, query))
            data = self.safe_value(response, 'data')
            resultList = self.safe_value(data, 'resultList')
            #
            #     {
            #         "success": True,
            #         "code": "0",
            #         "data": {
            #             "pageSize": "20",
            #             "totalCount": "10",
            #             "totalPage": "1",
            #             "currentPage": "1",
            #             "resultList": [
            #                 {
            #                     "id": "2980812",
            #                     "txid": "fa8a1e7bf05940a3b7025856dc48d025",
            #                     "currency": "USDT",
            #                     "amount": "22.90213135",
            #                     "type": "IN",
            #                     "state": "SUCCESS",
            #                     "createTime": "1648849076000",
            #                     "updateTime": "1648849076000"
            #                 },
            #             ]
            #         }
            #     }
            #
        return self.parse_transfers(resultList, currency, since, limit)

    def transfer(self, code, amount, fromAccount, toAccount, params={}):
        """
        transfer currency internally between wallets on the same account
        see https://mxcdevelop.github.io/apidocs/spot_v3_en/#user-universal-transfer
        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account to transfer from
        :param str toAccount: account to transfer to
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :param str|None params['symbol']: market symbol required for margin account transfers eg:BTCUSDT
        :returns dict: a `transfer structure <https://docs.ccxt.com/en/latest/manual.html#transfer-structure>`
        """
        self.load_markets()
        currency = self.currency(code)
        accounts = {
            'spot': 'SPOT',
            'swap': 'FUTURES',
            'margin': 'ISOLATED_MARGIN',
        }
        fromId = self.safe_string(accounts, fromAccount)
        toId = self.safe_string(accounts, toAccount)
        if fromId is None:
            keys = list(accounts.keys())
            raise ExchangeError(self.id + ' fromAccount must be one of ' + ', '.join(keys))
        if toId is None:
            keys = list(accounts.keys())
            raise ExchangeError(self.id + ' toAccount must be one of ' + ', '.join(keys))
        request = {
            'asset': currency['id'],
            'amount': amount,
            'fromAccountType': fromId,
            'toAccountType': toId,
        }
        if (fromId == 'ISOLATED_MARGIN') or (toId == 'ISOLATED_MARGIN'):
            symbol = self.safe_string(params, 'symbol')
            params = self.omit(params, 'symbol')
            if symbol is None:
                raise ArgumentsRequired(self.id + ' transfer() requires a symbol argument for isolated margin')
            market = self.market(symbol)
            request['symbol'] = market['id']
        response = self.spotPrivatePostCapitalTransfer(self.extend(request, params))
        #
        #     {
        #         "tranId": "ebb06123e6a64f4ab234b396c548d57e"
        #     }
        #
        transaction = self.parse_transfer(response, currency)
        return self.extend(transaction, {
            'amount': amount,
            'fromAccount': fromAccount,
            'toAccount': toAccount,
        })

    def parse_transfer(self, transfer, currency=None):
        #
        # spot: fetchTransfer
        #
        #     {
        #         currency: 'USDT',
        #         amount: '1',
        #         transact_id: 'b60c1df8e7b24b268858003f374ecb75',
        #         from: 'MAIN',
        #         to: 'CONTRACT',
        #         transact_state: 'WAIT'
        #     }
        #
        # swap: fetchTransfer
        #
        #     {
        #         "currency": "USDT",
        #         "amount": "22.90213135",
        #         "txid": "fa8a1e7bf05940a3b7025856dc48d025",
        #         "id": "2980812",
        #         "type": "IN",
        #         "state": "SUCCESS",
        #         "createTime": "1648849076000",
        #         "updateTime": "1648849076000"
        #     }
        #
        # transfer
        #
        #     {
        #         "tranId": "ebb06123e6a64f4ab234b396c548d57e"
        #     }
        #
        currencyId = self.safe_string(transfer, 'currency')
        id = self.safe_string_n(transfer, ['transact_id', 'txid', 'tranId'])
        timestamp = self.safe_integer(transfer, 'createTime')
        datetime = self.iso8601(timestamp) if (timestamp is not None) else None
        direction = self.safe_string(transfer, 'type')
        accountFrom = None
        accountTo = None
        if direction is not None:
            accountFrom = 'MAIN' if (direction == 'IN') else 'CONTRACT'
            accountTo = 'CONTRACT' if (direction == 'IN') else 'MAIN'
        else:
            accountFrom = self.safe_string(transfer, 'from')
            accountTo = self.safe_string(transfer, 'to')
        return {
            'info': transfer,
            'id': id,
            'timestamp': timestamp,
            'datetime': datetime,
            'currency': self.safe_currency_code(currencyId, currency),
            'amount': self.safe_number(transfer, 'amount'),
            'fromAccount': self.parse_account_id(accountFrom),
            'toAccount': self.parse_account_id(accountTo),
            'status': self.parse_transfer_status(self.safe_string_2(transfer, 'transact_state', 'state')),
        }

    def parse_account_id(self, status):
        statuses = {
            'MAIN': 'spot',
            'CONTRACT': 'swap',
        }
        return self.safe_string(statuses, status, status)

    def parse_transfer_status(self, status):
        statuses = {
            'SUCCESS': 'ok',
            'FAILED': 'failed',
            'WAIT': 'pending',
        }
        return self.safe_string(statuses, status, status)

    def withdraw(self, code, amount, address, tag=None, params={}):
        """
        make a withdrawal
        see https://mxcdevelop.github.io/apidocs/spot_v3_en/#withdraw
        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str|None tag:
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        tag, params = self.handle_withdraw_tag_and_params(tag, params)
        networks = self.safe_value(self.options, 'networks', {})
        network = self.safe_string_upper_2(params, 'network', 'chain')  # self line allows the user to specify either ERC20 or ETH
        network = self.safe_string(networks, network, network)  # handle ETH > ERC-20 alias
        self.check_address(address)
        self.load_markets()
        currency = self.currency(code)
        request = {
            'coin': currency['id'],
            'address': address,
            'amount': amount,
        }
        if tag is not None:
            request['memo'] = tag
        if network is not None:
            request['network'] = network
            params = self.omit(params, 'network')
        response = self.spotPrivatePostCapitalWithdrawApply(self.extend(request, params))
        #
        #     {
        #       "id":"7213fea8e94b4a5593d507237e5a555b"
        #     }
        #
        return self.parse_transaction(response, currency)

    def set_position_mode(self, hedged, symbol=None, params={}):
        request = {
            'positionMode': 1 if hedged else 2,  # 1 Hedge, 2 One-way, before changing position mode make sure that there are no active orders, planned orders, or open positions, the risk limit level will be reset to 1
        }
        response = self.contractPrivatePostPositionChangePositionMode(self.extend(request, params))
        #
        #     {
        #         "success":true,
        #         "code":0
        #     }
        #
        return response

    def fetch_position_mode(self, symbol=None, params={}):
        response = self.contractPrivateGetPositionPositionMode(params)
        #
        #     {
        #         "success":true,
        #         "code":0,
        #         "data":2
        #     }
        #
        positionMode = self.safe_integer(response, 'data')
        return {
            'info': response,
            'hedged': (positionMode == 1),
        }

    def borrow_margin(self, code, amount, symbol=None, params={}):
        """
        create a loan to borrow margin
        see https://mxcdevelop.github.io/apidocs/spot_v3_en/#loan
        :param str code: unified currency code of the currency to borrow
        :param float amount: the amount to borrow
        :param str symbol: unified market symbol
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns dict: a `margin loan structure <https://docs.ccxt.com/en/latest/manual.html#margin-loan-structure>`
        """
        self.load_markets()
        if symbol is None:
            raise ArgumentsRequired(self.id + ' borrowMargin() requires a symbol argument for isolated margin')
        market = self.market(symbol)
        currency = self.currency(code)
        request = {
            'asset': currency['id'],
            'amount': self.currency_to_precision(code, amount),
            'symbol': market['id'],
        }
        response = self.spotPrivatePostMarginLoan(self.extend(request, params))
        #
        #     {
        #         "tranId": "762407666453712896"
        #     }
        #
        transaction = self.parse_margin_loan(response, currency)
        return self.extend(transaction, {
            'amount': amount,
            'symbol': symbol,
        })

    def repay_margin(self, code, amount, symbol=None, params={}):
        """
        repay borrowed margin and interest
        see https://mxcdevelop.github.io/apidocs/spot_v3_en/#repayment
        :param str code: unified currency code of the currency to repay
        :param float amount: the amount to repay
        :param str symbol: unified market symbol
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :param str params['borrowId']: transaction id '762407666453712896'
        :returns dict: a `margin loan structure <https://docs.ccxt.com/en/latest/manual.html#margin-loan-structure>`
        """
        self.load_markets()
        if symbol is None:
            raise ArgumentsRequired(self.id + ' repayMargin() requires a symbol argument for isolated margin')
        id = self.safe_string_2(params, 'id', 'borrowId')
        if id is None:
            raise ArgumentsRequired(self.id + ' repayMargin() requires a borrowId argument in the params')
        market = self.market(symbol)
        currency = self.currency(code)
        request = {
            'asset': currency['id'],
            'amount': self.currency_to_precision(code, amount),
            'borrowId': id,
            'symbol': market['id'],
        }
        response = self.spotPrivatePostMarginRepay(self.extend(request, params))
        #
        #     {
        #         "tranId": "762407666453712896"
        #     }
        #
        transaction = self.parse_margin_loan(response, currency)
        return self.extend(transaction, {
            'amount': amount,
            'symbol': symbol,
        })

    def fetch_transaction_fees(self, codes=None, params={}):
        """
        fetch deposit and withdrawal fees
        see https://mxcdevelop.github.io/apidocs/spot_v3_en/#query-the-currency-information
        :param [str]|None codes: returns fees for all currencies if None
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns [dict]: a list of `fee structures <https://docs.ccxt.com/en/latest/manual.html#fee-structure>`
        """
        self.load_markets()
        response = self.spotPrivateGetCapitalConfigGetall(params)
        #
        #    [
        #       {
        #           coin: 'AGLD',
        #           name: 'Adventure Gold',
        #           networkList: [
        #               {
        #                   coin: 'AGLD',
        #                   depositDesc: null,
        #                   depositEnable: True,
        #                   minConfirm: '0',
        #                   name: 'Adventure Gold',
        #                   network: 'ERC20',
        #                   withdrawEnable: True,
        #                   withdrawFee: '10.000000000000000000',
        #                   withdrawIntegerMultiple: null,
        #                   withdrawMax: '1200000.000000000000000000',
        #                   withdrawMin: '20.000000000000000000',
        #                   sameAddress: False,
        #                   contract: '0x32353a6c91143bfd6c7d363b546e62a9a2489a20',
        #                   withdrawTips: null,
        #                   depositTips: null
        #               }
        #               ...
        #           ]
        #       },
        #       ...
        #    ]
        #
        return self.parse_transaction_fees(response, codes)

    def parse_transaction_fees(self, response, codes=None):
        withdrawFees = {}
        for i in range(0, len(response)):
            entry = response[i]
            currencyId = self.safe_string(entry, 'coin')
            currency = self.safe_currency(currencyId)
            code = self.safe_string(currency, 'code')
            if (codes is None) or (self.in_array(code, codes)):
                withdrawFees[code] = self.parse_transaction_fee(entry, currency)
        return {
            'withdraw': withdrawFees,
            'deposit': {},
            'info': response,
        }

    def parse_transaction_fee(self, transaction, currency=None):
        #
        #    {
        #        coin: 'AGLD',
        #        name: 'Adventure Gold',
        #        networkList: [
        #            {
        #                coin: 'AGLD',
        #                depositDesc: null,
        #                depositEnable: True,
        #                minConfirm: '0',
        #                name: 'Adventure Gold',
        #                network: 'ERC20',
        #                withdrawEnable: True,
        #                withdrawFee: '10.000000000000000000',
        #                withdrawIntegerMultiple: null,
        #                withdrawMax: '1200000.000000000000000000',
        #                withdrawMin: '20.000000000000000000',
        #                sameAddress: False,
        #                contract: '0x32353a6c91143bfd6c7d363b546e62a9a2489a20',
        #                withdrawTips: null,
        #                depositTips: null
        #            }
        #            ...
        #        ]
        #    }
        #
        networkList = self.safe_value(transaction, 'networkList', [])
        result = {}
        for j in range(0, len(networkList)):
            networkEntry = networkList[j]
            networkId = self.safe_string(networkEntry, 'network')
            networkCode = self.safe_string(self.options['networks'], networkId, networkId)
            fee = self.safe_number(networkEntry, 'withdrawFee')
            result[networkCode] = fee
        return result

    def fetch_deposit_withdraw_fees(self, codes=None, params={}):
        """
        fetch deposit and withdrawal fees
        see https://mxcdevelop.github.io/apidocs/spot_v3_en/#query-the-currency-information
        :param [str]|None codes: returns fees for all currencies if None
        :param dict params: extra parameters specific to the mexc3 api endpoint
        :returns [dict]: a list of `fee structures <https://docs.ccxt.com/en/latest/manual.html#fee-structure>`
        """
        self.load_markets()
        response = self.spotPrivateGetCapitalConfigGetall(params)
        #
        #    [
        #       {
        #           coin: 'AGLD',
        #           name: 'Adventure Gold',
        #           networkList: [
        #               {
        #                   coin: 'AGLD',
        #                   depositDesc: null,
        #                   depositEnable: True,
        #                   minConfirm: '0',
        #                   name: 'Adventure Gold',
        #                   network: 'ERC20',
        #                   withdrawEnable: True,
        #                   withdrawFee: '10.000000000000000000',
        #                   withdrawIntegerMultiple: null,
        #                   withdrawMax: '1200000.000000000000000000',
        #                   withdrawMin: '20.000000000000000000',
        #                   sameAddress: False,
        #                   contract: '0x32353a6c91143bfd6c7d363b546e62a9a2489a20',
        #                   withdrawTips: null,
        #                   depositTips: null
        #               }
        #               ...
        #           ]
        #       },
        #       ...
        #    ]
        #
        return self.parse_deposit_withdraw_fees(response, codes, 'coin')

    def parse_deposit_withdraw_fee(self, fee, currency=None):
        #
        #    {
        #        coin: 'AGLD',
        #        name: 'Adventure Gold',
        #        networkList: [
        #            {
        #                coin: 'AGLD',
        #                depositDesc: null,
        #                depositEnable: True,
        #                minConfirm: '0',
        #                name: 'Adventure Gold',
        #                network: 'ERC20',
        #                withdrawEnable: True,
        #                withdrawFee: '10.000000000000000000',
        #                withdrawIntegerMultiple: null,
        #                withdrawMax: '1200000.000000000000000000',
        #                withdrawMin: '20.000000000000000000',
        #                sameAddress: False,
        #                contract: '0x32353a6c91143bfd6c7d363b546e62a9a2489a20',
        #                withdrawTips: null,
        #                depositTips: null
        #            }
        #            ...
        #        ]
        #    }
        #
        networkList = self.safe_value(fee, 'networkList', [])
        result = self.deposit_withdraw_fee(fee)
        for j in range(0, len(networkList)):
            networkEntry = networkList[j]
            networkId = self.safe_string(networkEntry, 'network')
            networkCode = self.network_id_to_code(networkId, self.safe_string(currency, 'code'))
            result['networks'][networkCode] = {
                'withdraw': {
                    'fee': self.safe_number(networkEntry, 'withdrawFee'),
                    'percentage': None,
                },
                'deposit': {
                    'fee': None,
                    'percentage': None,
                },
            }
        return self.assign_default_deposit_withdraw_fees(result)

    def parse_margin_loan(self, info, currency=None):
        #
        #     {
        #         "tranId": "762407666453712896"
        #     }
        #
        return {
            'id': self.safe_string(info, 'tranId'),
            'currency': self.safe_currency_code(None, currency),
            'amount': None,
            'symbol': None,
            'timestamp': None,
            'datetime': None,
            'info': info,
        }

    def handle_margin_mode_and_params(self, methodName, params={}, defaultValue=None):
        """
         * @ignore
        marginMode specified by params["marginMode"], self.options["marginMode"], self.options["defaultMarginMode"], params["margin"] = True or self.options["defaultType"] = 'margin'
        :param dict params: extra parameters specific to the exchange api endpoint
        :param bool|None params['margin']: True for trading spot-margin
        :returns [str|None, dict]: the marginMode in lowercase
        """
        defaultType = self.safe_string(self.options, 'defaultType')
        isMargin = self.safe_value(params, 'margin', False)
        marginMode = None
        marginMode, params = super(mexc3, self).handle_margin_mode_and_params(methodName, params, defaultValue)
        if (defaultType == 'margin') or (isMargin is True):
            marginMode = 'isolated'
        return [marginMode, params]

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        section, access = api
        path, params = self.resolve_path(path, params)
        url = None
        if section == 'spot':
            url = self.urls['api'][section][access] + '/api/' + self.version + '/' + path
            paramsEncoded = ''
            if access == 'private':
                params['timestamp'] = self.milliseconds()
                params['recvWindow'] = self.safe_integer(self.options, 'recvWindow', 5000)
            if params:
                paramsEncoded = self.urlencode(params)
                url += '?' + paramsEncoded
            if access == 'private':
                self.check_required_credentials()
                signature = self.hmac(self.encode(paramsEncoded), self.encode(self.secret), hashlib.sha256)
                url += '&' + 'signature=' + signature
                headers = {
                    'X-MEXC-APIKEY': self.apiKey,
                    'source': self.safe_string(self.options, 'broker', 'CCXT'),
                }
            if method == 'POST':
                headers['Content-Type'] = 'application/json'
        elif section == 'contract' or section == 'spot2':
            url = self.urls['api'][section][access] + '/' + self.implode_params(path, params)
            params = self.omit(params, self.extract_params(path))
            if access == 'public':
                if params:
                    url += '?' + self.urlencode(params)
            else:
                self.check_required_credentials()
                timestamp = str(self.milliseconds())
                auth = ''
                headers = {
                    'ApiKey': self.apiKey,
                    'Request-Time': timestamp,
                    'Content-Type': 'application/json',
                    'source': self.safe_string(self.options, 'broker', 'CCXT'),
                }
                if method == 'POST':
                    auth = self.json(params)
                    body = auth
                else:
                    params = self.keysort(params)
                    if params:
                        auth += self.urlencode(params)
                        url += '?' + auth
                auth = self.apiKey + timestamp + auth
                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, reason, url, method, headers, body, response, requestHeaders, requestBody):
        if response is None:
            return
        # spot
        #     {"code":-1128,"msg":"Combination of optional parameters invalid.","_extend":null}
        #     {"success":false,"code":123456,"message":"Order quantity error...."}
        #
        # contract
        #
        #     {"code":10232,"msg":"The currency not exist"}
        #     {"code":10216,"msg":"No available deposit address"}
        #     {"success":true, "code":0, "data":1634095541710}
        #
        success = self.safe_value(response, 'success', False)  # v1
        if success is True:
            return
        responseCode = self.safe_string(response, 'code', None)
        if (responseCode is not None) and (responseCode != '200') and (responseCode != '0'):
            feedback = self.id + ' ' + body
            self.throw_broadly_matched_exception(self.exceptions['broad'], body, feedback)
            self.throw_exactly_matched_exception(self.exceptions['exact'], responseCode, feedback)
            raise ExchangeError(feedback)
